Why shake event not working in phonegap? - javascript

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 .

Related

Vaadin flow 23 onload event on javascript not working

I am using Vaadin flow 23 (spring boot). I loaded a Javascript file into browser successfully but onload event on JS does not trigger. With Vaadin flow 14, it works fine.
clientLocation.js:
window.addEventListener('load', function () {
console.log("load js file ==================== ok");
window.scrollTo(0, 0);
//do something here but it never triggers when page is loaded
startTimer();
})
This is how I load JS file:
File mainview.java
======== Updated: ===============
Tried with #JsModule, #JavaScript but still does not work!
client Log:
workaround solution is to add JS file into index.html.
https://github.com/vaadin/flow/issues/14211

Load Admob interstitial programmatically in Phonegap

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!

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

Android/ Phonegap - onClick() not working

I am using phonegap and am trying to detect the onClick, however Android seems to completely ignore it, below is what I am trying:
<select name="func" onclick="StartButtons();" data-native-menu="true">
I have tried several variations of the onClick include javascript, jQuery etc. however none of these seem to work.
I have noticed that onChange works, however this is not of much use to me as I need to use a prompt asking the user to confirm the change, if it is no then do nothing. However, using onchange still changes the item within the dropdown.
Can someone please help with this?
I had the same problem with jQuery, Android seems to ignore the click event in javascript. Originally, my code with jQuery looks like this:
$("#element").click(function () { alert("message"); });
I had to change it to:
$("#element").on("touchend", function () { alert("message"); });
Not sure if you're using jQuery at all, but hope this helps.
Add click event listener to your object with javascript. First add an id to object:
<select id="obj_id" name="func" data-native-menu="true">
And then call addEventListener() :
document.getElementById("obj_id").addEventListener("click", StartButtons, false);
Phonegap documentation recomends to run all your javascript code in "deviceready" event. So your code should look like this:
main.js:
function StartButtons() { ... }
function onDeviceReady() {
...
document.getElementById("obj_id")
.addEventListener("click", StartButtons, false);
...
}
function init() {
document.addEventListener("deviceready", onDeviceReady, false);
}
index.html:
...
<script type="text/javascript" charset="utf-8" src="main.js"></script>
</head>
<body onload="init();">
...
<select id="obj_id" name="func" data-native-menu="true">
...
</body>
https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
delete this code from index.html
user1183085´s answer is the right one. Android does not recognize click events as web apps do, this makes sence since mobile apps are not web when native, so that is why phonegap was made but since it works with jquery and not native java android libraries directly. I put my code this way:
The web buttons or elements onclick to handle all web interfaces, and special buttons or elements ontouchend to handle the mobile interfaces. Here´s a part of my code:
//this handles the login button events for the mobile touch of the user
$("button.login-button").on("touchend", function () {alert('hello touch ! =o' )});
//this handles the login button events for web clicks
$("button.login-button").on("click", function () {alert('hello click ! =o' )});
thanks user user1183085, that solved my life forever =()
Watch out, bind an onclick on an input in Cordova 3.4, doesn't work. But it works great with a div element. Considering, input elements are part of form element, like select element, it may be your problem.
Have you tried setting your method to be called to "method" instead of "method();"? So maybe you could try your line as:
<select name="func" onclick="StartButtons" data-native-menu="true">
Then hopefully your method will be called.

Categories