Load Admob interstitial programmatically in Phonegap - javascript

I'm trying to load Admob interstitials programmatically in a Phonegap app.
I'm using a plugin that I found on Github:
https://github.com/admob-google/admob-phonegap
I built a test app with the example html provided in the repo. The only problem is that I want to be able to cache the interstitial and load it programmatically. The example uses buttons to trigger the Javascript.
I did get the ads to work in the app, but only by pressing the buttons. I would like to trigger the interstitial on Game Over in a HTML 5 game. No user interaction required.
This is what I've tried:
function onLoad(){
admob.cacheInterstitial();
document.addEventListener('deviceready',onDeviceReady, false);
}
function onDeviceReady() {
showInterstitial();
}
<body onload="onLoad();">
However, it doesn't work. I admit Javascript isn't my strong point and have a much easier time with Objective-C and Swift.
Maybe someone better at Javascript than me can point me in the right direction on how to trigger these functions admob.cacheInterstitial(); and showInterstitial(); programmatically.
Here is the full example HTML I am using:
https://github.com/admob-google/admob-phonegap/blob/master/Example/index.html

Consider use this plugin: https://github.com/appfeel/admob-google-cordova
The use is very simple! I actually use in my game and it works perfectly!
You just need to include the follow code:
function onDeviceReady() {
document.removeEventListener('deviceready', onDeviceReady, false);
// Set AdMobAds options:
admob.setOptions({
publisherId: "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB", // Required
interstitialAdId: "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII", // Optional
tappxShare: 0.5, // Optional
autoShowInterstitial: false
});
// Request interstitial (will present automatically when autoShowInterstitial is set to true, that's why we set to false! so we can call when we want!)
admob.requestInterstitialAd();
}
document.addEventListener("deviceready", onDeviceReady, false);
And inside your gameOver function, you just use the follow code to call the interstitial ad
admob.showInterstitialAd();
*UPD: Using your plugin, try to use a bool and show this function, maybe like this:
function onDeviceReady() {
if(boolGameOver){
showInterstitial();
boolGameOver = false;
}
}
And in your gameOverFunction, call onDeviceReady function, after you set boolGameOver to true!

Related

Power Bi Embedded: is there a way to set an onFullscreen event handler?

I’m trying to use React to make a Report Component.
I want to use something similar to the on() function to have an event handler for when the report enters fullscreen mode. This way I could pass a Function through props to have it called when the report goes into fullscreen mode.
Something like:
report.on('fullscreen', () => {
props.onFullscreen();
}
Does this type of functionality exist?
EDIT: here is link to Microsoft Idea: https://ideas.powerbi.com/ideas/idea/?ideaid=3ae8a8bd-bf04-eb11-b5d9-501ac524a3e3
I don't know of how you can do this with the PowerBI Javascript API. This would be a good idea request to submit; https://ideas.powerbi.com/ideas/. That said you do have an option to achieve what you are looking to do: You can add listeners to detect when the PowerBI embedded iframe on the parent page is changed to full screen.
function iFrameFullChangeDetectedFunction(e) {
console.log("screeen changed")
}
<script type="text/javascript">
document.addEventListener("fullscreenchange", iFrameFullChangeDetectedFunction, false);
document.addEventListener("webkitfullscreenchange", iFrameFullChangeDetectedFunction, false);
document.addEventListener("mozfullscreenchange", iFrameFullChangeDetectedFunction, false);
</script>

Why shake event not working in phonegap?

I added shake gesture plugin for my project.
This is my code:
<button onclick="myFunc()" id="round">Gesture Call</buttom>
<script>
function myFunction()
{
window.open("emcall.html");
navigator.vibrate([2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000,2000]);
navigator.notification.beep(10);
}
function myFunc()
{
alert('shake working');
function onShake()
{
alert("shake success");
window.open("emcall.html");
}
function onError()
{
alert("errorq");
}
shake.startWatch(onShake,30,onError);
}
</script>
Some thing wrong in mycode help me to over come this.
Include cordova.js file in your HTML file and register deviceready event in your script. Then, invoke shake plugin related code inside deviceready event listener function. It should work.
Also ensure to test it on device after adding and building platform as i dont see this shake plugin supported in browser.
->Plugin not supporting in phonegap.app,who are all testing the app using you ip address on phonegap app.
->just add platform through cli.
->And build or run it and test .

Getting SoundJS to work with Cordova/Phonegap

I am building an app with extensive audio requirements, so I am using SoundJS for that, and I am compiling the app using phonegap.
I am using the mobile safe approach to build a soundJS app. It seems that there are different audio plugins, including a special Cordova audio plugin. So, I am not able to register any of these plugins on the compiled app. This is because registering any plugin requires to check if this plugin is supported or not. In case of the cordova, the method isSupported checks for the following:
if (s._capabilities != null || !(window.cordova || window.PhoneGap || window.phonegap) || !window.Media) { return;}
This means when the app is compiled, there is no global variable called window.cordova or phonegap and no global variable called window.media (I think this is the media plugin that needs to be installed to get soundjs to work, and I have added it to the config.xml that I'm using for phonegap build.
So the question is, how to investigate what is wrong, how to know if for example the media plugin is not installed properly (all from the javascript variables that we can use, as I am not able to use any other debugging), or is it the case that when I compile using phonegap build there is no variables for cordova or phonegap.. can we list all global variables to see which ones are used?
Edit
Thanks Jesse for drawing my attention to these points about phonegap, so I built a small app just to test the deviceready event, but for some reason it still doesn't work when compiled by phonegap build:
<!DOCTYPE html>
<html>
<head>
<title>Cordova Device Ready Example</title>
<script type="text/javascript" charset="utf-8" src="js/soundjs-NEXT.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordovaaudioplugin-NEXT.min.js"></script>
<script type="text/javascript" charset="utf-8">
// Call onDeviceReady when Cordova is loaded.
//
// At this point, the document has loaded but cordova-2.3.0.js has not.
// When Cordova is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
document.getElementById("doc_loaded").innerHTML="Document Loaded"
document.addEventListener("deviceready", onDeviceReady, false);
}
// Cordova is loaded and it is now safe to make calls Cordova methods
//
function onDeviceReady() {
// Now safe to use the Cordova API\
document.getElementById("device_loaded").innerHTML="Device Loaded"
if (window.cordova || window.PhoneGap || window.phonegap){
document.getElementById("phonegap_loaded").innerHTML="Phonegap Loaded"
}
if (window.Media){
document.getElementById("media_loaded").innerHTML="Media Loaded"
}
}
</script>
</head>
<body onload="onLoad()">
Hello Hello, testing phonegap deviceready
<div id="doc_loaded">Loading Doc</div>
<div id="device_loaded">Loading Device</div>
<div id="phonegap_loaded">Detecting Phonegap</div>
<div id="media_loaded">Detecting Media</div>
</body>
</html>
Can you please help me locate where can the problem be?
EDIT2
I figured out that the deviceready was not working because I didn't add cordova:
<script type="text/javascript" src="cordova.js"></script>
So, when I did, I was able to initialize the cordova audio plugin. However, I am still unable to play sound, despite using mobile safe approach:
(this code is hosted on arbsq.net/h6/)
<!DOCTYPE html>
<html>
<head>
<title>SoundJS: Mobile Safe</title>
<link href="css/shared.css" rel="stylesheet" type="text/css"/>
<link href="css/examples.css" rel="stylesheet" type="text/css"/>
<link href="css/soundjs.css" rel="stylesheet" type="text/css"/>
<script src="js/examples.js"></script>
</head>
<body onload="loading_doc()">
<header class="SoundJS">
<h1>Mobile Safe Play</h1>
<p>This example registers and plays a sound with SoundJS in a way that will
work on mobile devices.</p>
</header>
<div class="content" id="content" style="height: auto">
<p id="status">Hello World.</p>
</div>
<div id="error">
<h2>Sorry!</h2>
<p>SoundJS is not currently supported in your browser.</p>
<p>Please log a bug
with the device and browser you are using. Thank you.</p>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/soundjs-NEXT.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordovaaudioplugin-NEXT.min.js"></script>
<!-- We also provide hosted minified versions of all CreateJS libraries.
http://code.createjs.com -->
<script id="editable">
var displayMessage; // the HTML element we use to display messages to the user
this.myNameSpace = this.myNameSpace || {};
function loading_doc() {
if(( /(ipad|iphone|ipod|android|windows phone)/i.test(navigator.userAgent) )) {
document.addEventListener('deviceready', init, false);
} else {
init();
}
}
function init() {
// store this off because walking the DOM to get the reference is expensive
displayMessage = document.getElementById("status");
// if this is on mobile, sounds need to be played inside of a touch event
if (createjs.BrowserDetect.isIOS || createjs.BrowserDetect.isAndroid || createjs.BrowserDetect.isBlackberry || createjs.BrowserDetect.isWindowPhone) {
//document.addEventListener("click", handleTouch, false); // works on Android, does not work on iOS
displayMessage.addEventListener("click", handleTouch, false); // works on Android and iPad
displayMessage.innerHTML = "Touch to Start";
}
else {
handleTouch(null);
}
}
// launch the app inside of this scope
function handleTouch(event) {
displayMessage.removeEventListener("click", handleTouch, false);
// launch the app by creating it
var thisApp = new myNameSpace.MyApp();
}
// create a namespace for the application
// this is a function closure
(function () {
// the application
function MyApp() {
this.init();
}
MyApp.prototype = {
src: null, // the audio src we are trying to play
soundInstance: null, // the soundInstance returned by Sound when we create or play a src
displayStatus: null, // the HTML element we use to display messages to the user
loadProxy: null,
init: function () {
// store the DOM element so we do repeatedly pay the cost to look it up
this.displayStatus = document.getElementById("status");
// this does two things, it initializes the default plugins, and if that fails the if statement triggers and we display an error
// NOTE that WebAudioPlugin plays an empty sound when initialized, which activates web audio on iOS if played inside of a function with a touch event in its callstack
if (!createjs.Sound.initializeDefaultPlugins()) {
document.getElementById("error").style.display = "block";
document.getElementById("content").style.display = "none";
return;
}
// Create a single item to load.
var assetsPath = "audio/";
this.src = assetsPath + "M-GameBG.ogg";
this.displayStatus.innerHTML = "Waiting for load to complete."; // let the user know what's happening
// NOTE createjs.proxy is used to apply scope so we stay within the touch scope, allowing sound to play on mobile devices
this.loadProxy = createjs.proxy(this.handleLoad, this);
createjs.Sound.alternateExtensions = ["mp3"]; // add other extensions to try loading if the src file extension is not supported
createjs.Sound.addEventListener("fileload", this.loadProxy); // add event listener for when load is completed.
createjs.Sound.registerSound(this.src); // register sound, which preloads by default
return this;
},
// play a sound inside
handleLoad: function (event) {
this.soundInstance = createjs.Sound.play(event.src); // start playback and store the soundInstance we are currently playing
this.displayStatus.innerHTML = "Playing source: " + event.src; // let the user know what we are playing
createjs.Sound.removeEventListener("fileload", this.loadProxy); // we only load 1 sound, so remove the listener
}
}
// add MyApp to myNameSpace
myNameSpace.MyApp = MyApp;
}());
</script>
</body>
</html>
#hmghaly,
the general method for checking for the availability of Phonegap is to use the 'deviceready' event that Cordova/Phonegap provide. In addition, it is required that you wait until this event completes.
You will want to read #4 of this article FAQ:
Top Mistakes by Developers new to Cordova/Phonegap
I will quote the important part from the documentation (which your should read):
This is a very important event that every Cordova application should use.
Cordova consists of two code bases: native and JavaScript. While the native code is loading, a custom loading image is displayed.
However, JavaScript is only loaded once the DOM loads. This means your
web application could, potentially, call a Cordova JavaScript function
before it is loaded.
The Cordova deviceready event fires once Cordova has fully loaded. After the device has fired, you can safely make calls to Cordova function.
The documentation includes code examples that would relevant to your particular mobile device and platform.
Best of Luck
Whilst it is not a complete answer I am currently working through the exact same problem and it was breaking at the exact same point.
if (s._capabilities != null || !(window.cordova || window.PhoneGap ||
window.phonegap) || !window.Media) { return;}
After you have ensured cordova is installed the next big thing is to ensure you actually have the cordova-plugin-media installed. The !window.Media bit in the line above. Sounds easy but if you simply add the plugin and build without reading all the output you can come unstuck.
The media plugin requires cordova version > 5.0 . The problem is that cordova is pinned at version 4.1.1 - at least mine was despite repeated total removal of cordova - several times via npm and manual total deletion of all npm caches.
Cordova is hard wired internally to install a particular version unless you tell it not to.
So make sure you are using
cordova platform add android#5.X.X
as appropriate to your version not just a plain old
cordova platform add android (BAD)
which will install the pinned version
If you do the latter cordova will happily build with version 4.1.1 despite the cli command
cordova -v
reporting you are on later version - in my case 5.4.1
It will then hit the plugin step - decide the environment is not appropriate for your plugin - spits out a warning and merrily continues with the build - minus the media plugin. Everything else will seem to work - the app will run and unless you dig into it you won't notice you are on an old version of cordova.
Note: they have just released a new version which moves the pinned version forward - so if you update to the latest version - you should be fine.
New Cordova Version Released
If you are using SoundJS 0.6.2, then you don't have to include the MobileSafe code. Refer Official Doc
The problem I was facing from quite a long time was the local sound files were not loading successfully in iOS.
What I found:
Latest iOS uses WKWebView. It appears to treat local files as if they came from a remote server, even though they're in the app itself, and such requests are blocked. Reference Source
Finally after lot of debugging and logging,
the following solution worked for me:
Add the Corodova file plugin.
cordova plugin add cordova-plugin-file
Change the local file path to this:
cdvfile://localhost/bundle/www/you_folder_name/file_name.mp3

Plugin not triggered in cordova/phonegap application

The plugin de.appplant.cordova.plugin.background-mode (which can be found on github at: https://github.com/katzer/cordova-plugin-background-mode) is not activating correctly inside of my application. Here is the code I am running in my index.js:
document.addEventListener('deviceready', function () {
// Android customization
cordova.plugins.backgroundMode.setDefaults({ text:'Doing heavy tasks.'});
// Enable background mode
cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function () {
setTimeout(function () {
alert('activated')
// Modify the currently displayed notification
cordova.plugins.backgroundMode.configure({
text:'Running in background for more than 5s now.'
});
}, 5000);
}
}, false);
cordova.plugins.backgroundMode.enable();
However, when I run it, the alert('activated') does not trigger. How can I fix this? I have my code up on github # https://github.com/acquainting/Cordova-Test.
Thanks!
#Rob,
it appears you are new to programming, or phonegap, or both. Your statements in your original message are conflicting. The statements conflict with each other. I suggest, in future, you use a linear time-line for explanation.
I do NOT use Phonegap CLI. However, after looking at your source code, you need to add a phonegap verion.
EXAMPLE:
<preference name="phonegap-version" value="3.5.0" />
Best of Luck,
Jesse

Phonegap when app is loaded completly

I am trying to make a battery app that animates the battery level from 0% to the current level as an animation with Jquery.
It is working, BUT.. when my app is loaded, after the splash screen is done, and cordova has loaded aswell, the animation is almost finished. The only reason that i know this is because i set the animation to 5 seconds.
I want to make it so that, the animtion starts when the app is loaded.
I am not sure if this "state" im refering to has a direct event name or so. So i am sorry if i am unable to describe it with the real words. :-)
Consider the following piece of code:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.addEventListener("batterystatus", onBatteryStatus, false);
}
function onBatteryStatus(info) {
$("div#status").animate({ width: bat + "%" }, 5000);
}
You might want to consider using the PhoneGap Splashscreen functionality :
PhoneGap Splash Screen API Doc
You should call your splash screen on the Java side of things (DroidGap) and let PhoneGap do it's own job in the background while the Splash screen is being displayed. This blogpost which includes relevant code should help you with your problem :
Splash Screens in PhoneGap
What should now happen is PhoneGap will load and then your splash screen will be displayed in full. Hope this fixes your problem!!
It looks like you are going in the right directions from what i can see. Here's how my base Cordova project is uaully setup.
Javascript
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// `load`, `deviceready`, `offline`, and `online`.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of `this` is the event. In order to call the `receivedEvent`
// function, we must explicity call `app.receivedEvent(...);`
onDeviceReady: function() {
// Get battery status HERE
}
};
And then in my "index.html" i initialize my app class like so:
<script type="text/javascript">
app.initialize();
</script>
You could try cordova-jquerymobile-boilerplate. You should start your work with a boilerplate, it will make you go fast and safe.

Categories