Interstitial Ad doesn't appear - html

I can't do a simply html page with an Interstitial Add. I'm new in programming and I have no idea what's wrong in this code. I'm doing an app with phonegap. I added also <gap:plugin name="com.admob.plugin" version="3.0.0" source="plugins.cordova.io" /> to my config.xml. Please help. That's what I already have:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
function showInterstitial(){
admob.isInterstitialReady(function(isReady){
if(isReady){
admob.showInterstitial();
}else{
alert("need cached before show");
}
});
}
function onInterstitialReceive (message) {
alert("onMInterstitialReceive ,you can show it now");
}
function onReceiveFail (message) {
var msg=admob.Error[message.data];
if(msg==undefined){
msg=message.data;
}
alert("load fail: "+message.type+" "+msg);
}
function onDeviceReady() {
admob.initAdmob("ca-app-pub-5461976332457981/1789654352","ca-app-pub-5461976332457981/7220849555");
document.addEventListener(admob.Event.onInterstitialReceive, onInterstitialReceive, false);
document.addEventListener(admob.Event.onInterstitialFailedReceive,onReceiveFail, false);
}
document.addEventListener('deviceready',onDeviceReady, false);
</script>
</body>
</html>

Use the new plugin specification (with hyphens instead of dots):
<gap:plugin name="phonegap-admob" source="npm"/>
Then your code should be like this (you can also see here an example on how autoshow interstitials every 2 minutes: https://github.com/appfeel/admob-google-cordova/wiki/setOptions):
var isAppForeground = true;
var isInterstitialAvailable = false;
function onAdLoaded(e) {
if (isAppForeground && e.adType === admob.AD_TYPE.INTERSTITIAL) {
isInterstitialAvailable = true;
}
}
function onAdOpened(e) {
if (isAppForeground && e.adType === admob.AD_TYPE.INTERSTITIAL) {
isInterstitialAvailable = false;
admob.requestInterstitialAd(); // Request next interstitial
}
}
function onPause() {
if (isAppForeground) {
admob.destroyBannerView();
isAppForeground = false;
isInterstitialAvailable = false;
}
}
function onResume() {
if (!isAppForeground) {
setTimeout(admob.createBannerView, 1);
setTimeout(admob.requestInterstitialAd, 1);
isAppForeground = true;
}
}
function registerAdEvents() {
document.addEventListener(admob.events.onAdLoaded, onAdLoaded);
document.addEventListener(admob.events.onAdOpened, onAdOpened);
document.addEventListener("pause", onPause, false);
document.addEventListener("resume", onResume, false);
}
function initAds() {
var ids = {
ios : {
banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
},
android : {
banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
}
};
var admobid = (/(android)/i.test(navigator.userAgent)) ? ids.android : ids.ios;
admob.setOptions({
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
autoShowInterstitial: false,
isTesting: true // False on production apps
});
registerAdEvents();
}
function onDeviceReady() {
document.removeEventListener('deviceready', onDeviceReady, false);
if (window.admob) {
initAds();
admob.createBannerView(); // display a banner at startup
admob.requestInterstitialAd(); // cache an interstitial
} else {
alert('Admob plugin not ready');
}
}
document.addEventListener("deviceready", onDeviceReady, false);
function showInterstitial() {
if (isInterstitialAvailable) {
admob.showInterstitialAd();
} else {
console.log('Interstitial is not yet available');
}
}

Related

Got some trouble with canvas in html5

I don't know where my code is broken.
Why my context is not recognized in my script?
I have trouble in this line :
this.context = this.canvas.getContext("2d");
Error message :
Uncaught TypeError: this.canvas.getContext is not a function
I'd like to know why my canvas doses not recognize?
Could you give me an advice?
var myGameArea = {
canvas : document.getElementById("canvas_screen"),
start : function() {
this.context = this.canvas.getContext("2d");
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
logger : function() {
alert("log---");
}
}
I tried your code in both Google chrome and Mozilla Firefox browser, but it seems to work fine.
Below is the code I tried:
<html>
<head>
<script type="text/javascript">
var myGameArea = {
canvas : document.getElementById("canvas_screen"),
start : function() {
this.context = this.canvas.getContext("2d");
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
logger : function() {
alert("log---");
}
}
</script>
</head>
<body>
<canvas id="canvas_screen" style="z-index:0;background-color:#000000; position:fixed;top:20%;left:2%;">
</body>
</html>

How to add Google Drive Picker in Google web app

what I'm trying to do is to show the Google Picker in my Google Web app. I already tried many ways to accomplish that, but nothing works.
At the moment my code looks like this:
WebApp.html
<!-- rest of the code -->
<button type="button" id="pick">Pick File</button>
</div>
<script>
function initPicker() {
var picker = new FilePicker({
apiKey: "####################",
clientId: "##########-##########################",
buttonEl: document.getElementById('pick'),
onSelect: function(file) {
alert('Selected ' + file.title);
} // onSelect
}); // var picker
} // function initPicker()
</script>
<!-- rest of the code -->
WebAppJS.html
/* rest of the code */
var FilePicker = window.FilePicker = function(options) {
this.apiKey = options.apiKey;
this.clientId = options.clientId;
this.buttonEl = options.buttonEl;
this.onSelect = options.onSelect;
this.buttonEl.addEventListener('click', this.open.bind(this));
this.buttonEl.disabled = true;
gapi.client.setApiKey(this.apiKey);
gapi.client.load('drive', 'v2', this._driveApiLoaded.bind(this));
google.load('picker', '1', { callback: this._pickerApiLoaded.bind(this) });
}
FilePicker.prototype = {
open: function() {
var token = gapi.auth.getToken();
if (token) {
this._showPicker();
} else {
this._doAuth(false, function() { this._showPicker(); }.bind(this));
}
},
_showPicker: function() {
var accessToken = gapi.auth.getToken().access_token;
this.picker = new google.picker.PickerBuilder().
addView(google.picker.ViewId.DOCUMENTS).
setAppId(this.clientId).
setOAuthToken(accessToken).
setCallback(this._pickerCallback.bind(this)).
build().
setVisible(true);
},
_pickerCallback: function(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var file = data[google.picker.Response.DOCUMENTS][0],
id = file[google.picker.Document.ID],
request = gapi.client.drive.files.get({ fileId: id });
request.execute(this._fileGetCallback.bind(this));
}
},
_fileGetCallback: function(file) {
if (this.onSelect) {
this.onSelect(file);
}
},
_pickerApiLoaded: function() {
this.buttonEl.disabled = false;
},
_driveApiLoaded: function() {
this._doAuth(true);
},
_doAuth: function(immediate1, callback) {
gapi.auth.authorize({
client_id: this.clientId + '.apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/drive.readonly',
immediate: immediate1
}, callback);
}
}; // FilePicker.prototype
/* rest of the code */
For now, what this code does is showing kind of a popup, but empty. Code is based on Daniel15's code.
What I already tried is:
relocating chunks of code, to server-side and client-side,
using htmlOutput, htmlTemplate - non of those works,
many other things, that i can't exactly remember.
What I would like to get is answer to the question: Why this code doesn't show Google Picker.
Thanks in advance.
Try adding a call origin and developer key
_showPicker: function() {
var accessToken = gapi.auth.getToken().access_token;
this.picker = new google.picker.PickerBuilder()
.addView(google.picker.ViewId.DOCUMENTS)
.setAppId(this.clientId)
.setOAuthToken(accessToken)
.setCallback(this._pickerCallback.bind(this))
.setOrigin('https://script.google.com') //
.setDeveloperKey(BROWSERKEYCREATEDINAPICONSOLE) //
.build()
.setVisible(true);
},

Creating Waypoints using Bing Maps API

I'm creating a program that would allow users to save a route to a database - however, that's against the terms for Bing Maps, so I am allowing waypoints to be created and saved. I'm not quite sure how to start doing that. I thought I knew how to create the waypoints - but it's not working I'm using Visual Studio - VB.NET/ASP.NET. Would it be recommended to put it in through HTML or Visual Basic? HTML is where all the other Bing coding is located.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'AohjORMDA3Vf0mCtDaEsnVHlza-E9AQMlGa0fKhH-6cvoT09Wjhc2RVzCpKG9HbP' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createDrivingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to driving
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Bismarck, ND' });
directionsManager.addWaypoint(startWaypoint);
var destinationWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('hometown').value });
directionsManager.addWaypoint(destinationWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
}
else {
createDrivingRoute();
}
}
function hometown_onclick() {
}
This is what I have as of right now. This is the code I need to put in for a waypoint - when I have tried putting it in, the directions did not show up:
function addWaypoint() {
if (!directionsManager) { createDirectionsManager(); }
if (directionsManager.getAllWaypoints().length < 2) {
directionsManager.resetDirections();
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: 'Bismarck, ND' });
directionsManager.addWaypoint(startWaypoint);
var destinationWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('hometown').value });
directionsManager.addWaypoint(destinationWaypoint);
}
// Insert a waypoint
directionsManager.addWaypoint(new Microsoft.Maps.Directions.Waypoint({ address: 'Mandan, ND' });
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
displayAlert('Calculating directions...');
directionsManager.calculateDirections();
}
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: addWaypoint });
}
else {
addWaypoint();
}
Let's start with this problem. How can I fix this?
I found the answer. The waypoint will load automatically once the form is loaded.
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol /mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
var map = null;
var directionsManager;
var directionsErrorEventObj;
var directionsUpdatedEventObj;
function getMap() {
map = new Microsoft.Maps.Map(document.getElementById('myMap'), { credentials: 'AohjORMDA3Vf0mCtDaEsnVHlza-E9AQMlGa0fKhH-6cvoT09Wjhc2RVzCpKG9HbP' });
}
function createDirectionsManager() {
var displayMessage;
if (!directionsManager) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(map);
displayMessage = 'Directions Module loaded\n';
displayMessage += 'Directions Manager loaded';
}
alert(displayMessage);
directionsManager.resetDirections();
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', function (arg) { alert(arg.message) });
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', function () { alert('Directions updated') });
}
function createDrivingRoute() {
if (!directionsManager) { createDirectionsManager(); }
directionsManager.resetDirections();
// Set Route Mode to driving
{
directionsManager.setRequestOptions({ routeMode: Microsoft.Maps.Directions.RouteMode.driving });
var startWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: '7500 University Dr., Bismarck, ND' });
directionsManager.addWaypoint(startWaypoint);
var destinationWaypoint = new Microsoft.Maps.Directions.Waypoint({ address: document.getElementById('hometown').value });
directionsManager.addWaypoint(destinationWaypoint);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
// Insert a waypoint
directionsManager.addWaypoint(new Microsoft.Maps.Directions.Waypoint({ address: 'Bismarck, ND'}), 1);
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: document.getElementById('directionsItinerary') });
alert('Calculating directions...');
directionsManager.calculateDirections();
}
function createDirections() {
if (!directionsManager) {
Microsoft.Maps.loadModule('Microsoft.Maps.Directions', { callback: createDrivingRoute });
}
else {
createDrivingRoute();
}
}

drag and drop cross frames use html5

I know how to drag and drop in one window with html5. But how to drag and drop across frames?
Here is my script which can work in one window. Can someone help me?
<script>
var drag = document.getElementById("drag");
var drop = document.getElementById("drop");
drag.onselectstart = function () {
return false;
}
drag.ondragstart = function (ev) {
ev.dataTransfer.effectAllowed = "move";
ev.dataTransfer.setData("text", ev.target.innerHTML);
}
drag.ondragend = function (ev) {
var text = ev.dataTransfer.getData("text");
alert(text);
ev.dataTransfer.clearData("text");
return false;
}
drop.ondragover = function (ev) {
ev.preventDefault();
return true;
}
drop.ondragenter = function (ev) {
this.background = "#ffffff";
return true;
}
drop.ondrop = function (ev) {
}
</script>
#Nickolay: oh, ok.
There's an example at http://www.useragentman.com/blog/2010/01/10/cross-browser-html5-drag-and-drop/ .
Added:
I'm not sure why the OP's code didn't work - maybe it wasn't loaded in both frames? I modified their Javascript a little to give more indications:
window.onload = function () {
var drag = document.getElementById('drag');
var drop = document.getElementById("drop");
if (drag) {
drag.style.backgroundColor = '#00ff00';
drag.onselectstart = function () {
return false;
}
drag.ondragstart = function (ev) {
ev.dataTransfer.effectAllowed = "move";
ev.dataTransfer.setData("text", ev.target.innerHTML);
}
drag.ondragend = function (ev) {
var text = ev.dataTransfer.getData("text");
alert(text);
//ev.dataTransfer.clearData("text");
return false;
}
}
if (drop != null) {
drop.style.backgroundColor = '#0000ff';
drop.ondragover = function (ev) {
ev.preventDefault();
return false;
}
drop.ondragenter = function (ev) {
this.style.backgroundColor = "#ff0000";
return false;
}
drop.ondrop = function (ev) {
return false;
}
}
}
It works between iframes and between browser windows (only tested in Firefox 11 and IE9 on Windows 7 x64).
I modified your script to work in the case that the iframe name is "frame1". Please check it now.
<script type="text/javascript">
window.onload = function ()
{
var drag = document.getElementById("drag");
var drop = frame1.document.getElementById("drop");
drag.draggable = true;
drag.onselectstart = function () {
return false;
}
drag.ondragstart = function (ev) {
ev.dataTransfer.effectAllowed = "move";
ev.dataTransfer.setData("text", ev.target.innerHTML);
}
drop.ondragover = function (ev) {
ev.preventDefault();
return true;
}
drop.ondragenter = function (ev) {
this.background = "#ffffff";
return true;
}
drop.ondrop = function (ev) {
var data = ev.dataTransfer.getData("text");
drop.innerHTML += data;
ev.preventDefault();
}
}
Check out the tutorial for Cross-Frame Drag and Drop. It explains the events required and the basic flow when working with multiple frames.
http://blog.dockphp.com/post/78640660324/cross-browser-drag-and-drop-interface-development-using
How are the iframes hosted? are you just using html files? as this could potentially be the issue.
I created a couple of html files with the drag and drop code in your question, this didn't work when just referencing each other. However when I added the files to IIS server and referenced the files using localhost it then started to work.

Chrome tab.create and tab.getSelected

I have some problems to pass message from background page to my content_script.js. I hope someone can point out where i am wrong.
background.html
//in a function
function myFunction() {
chrome.tabs.create({"url":"myurl","selected":true},function(tab){
updateTab(tab.id);
});
}
//update Created new tab
function updateTab(tabId){
chrome.tabs.getSelected(null, function(tab) {
makeRequest(tab.id);
});}
//make request
function makeRequest(tabId) {
chrome.tabs.sendRequest(tabId, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
}
content_script.js
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
else
sendResponse({}); // snub them.
});
manifest.json
"permissions": [
"tabs","notifications","http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["content_script.js"]
}],
My problem is the request from background.html has never been passed to the content_script.js. I think there must be some problems about the sequence of creating new tab and selecting that tab, but i do not know how to fix this.
Thanks.
EDIT:
There is what i have done so far.
background.html
chrome.browserAction.onClicked.addListener(function(tab) {
var tabId = tab.id;
chrome.tabs.getSelected(null, function(tab) {
validate(tab.url,tabId);
});
});
function validate(url,tabId) {
var filter = support(url);
if(filter!=null) {
getHTML(tabId,url,filter);
}
else{
var notification = webkitNotifications.createHTMLNotification(
'notification.html' // html url - can be relative
);
notification.show();
setTimeout(function(){
notification.cancel();
}, 10000); //10 sec
}
}
function getHTML(tabId,url,filter) {
console.log("request");
chrome.tabs.sendRequest(tabId, {action:"getHTML"}, function(response) {
var html = response.html;
console.log(html);
var taburl = ("some thing on server");
chrome.tabs.create({"url":taburl,"selected":true}, function(tab){
var tabId = tab.id;
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo){
if(changeInfo.status == "loading"){
console.log("loading");
}
if(changeInfo.status == "complete"){
chrome.tabs.onUpdated. removeListene(arguments.callee);
updateTab(tabId,url,filter,html);
}
});
});
});
}
function updateTab(tabId,url,filter,html) {
chrome.tabs.sendRequest(tabId, {action:"updateTab"}, function(response) {
//submit form
chrome.tabs.executeScript(tabId, {code: 'document.getElementById(\"hiddenbutton\").click();'});
});
}
content_script.js
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
var action = request.action;
console.log(action);
if(action == "getHTML") {
var html = document.body.innerHTML;
console.log(html);
sendResponse({html:document.body.innerHTML});
}
else{
//do update on page from server
sendResponse({});
}
});
It works as i expected, but there are still some points that i do not understand, espically removing listener chrome.tabs.onUpdated.removeListene(arguments.callee);. I hope if someone can have a chance to have a look and correct me if any thing is wrong. Thanks.
The background.html can be simplified to:
//in a function
function myFunction() {
chrome.tabs.create({"url":"myurl","selected":true}, function(tab){
makeRequest(tab.id);
});
}
//make request
function makeRequest(tabId) {
chrome.tabs.sendRequest(tabId, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
}
If it still doesn't work correctly then it might be because the tab hasn't finished loading (log tab.status in the chrome.tabs.create callback to check if this is true). There are two solutions for this, or you add an listener to chrome.tabs.onUpdated while filtering for this tab id or you make the tab send the request instead of background.html.