I have started using JQuery in my Phonegap mobile application, and since I have done so I am unable to Capture or Program Back & Menu keys. I have tried all the solutions mentioned here without success.
Currently this is what I have (onload is calling from ):
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
return;
}
function onDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
document.addEventListener("menubutton", onMenuKeyDown, false);
}
function onMenuKeyDown() {
$("#AudioPopup").popup("open");
return;
}
function onBackKeyDown() {
$("#AudioPopup").popup("open");
return;
}
It was working fine before moving to JQuery mobile.
Any help will be appreciated.
Thanks!
AR
I use the following code for dealing with PhoneGap back events inside onDeviceReady:
//handle back button
document.addEventListener("backbutton", function(e) {
if($.mobile.activePage.is('#main',
{ transition: "fade", changeHash: false })){
e.preventDefault();
navigator.app.exitApp();
} else {
location.href='main.html';
}
}, false);
Replace backbutton with menubutton for the menu event. I've also added a JQuery fade transition to smooth out the process as user experience goes. This would also enable you to place the code into the onDeviceReady function, instead of calling it from somewhere else.
Tested with:
jquery-1.8.2;
jquery.mobile-1.2.0;
phonegap-2.8.
Edit:
It seems that now your issue is that of onDeviceReady not triggering when on mobile device environment. I would suggest you try using a deferred object model, such as the one explained here: Correct way of using JQuery-Mobile/Phonegap together?
This could be an issue of both JQM and PG trying to race for initialization and causing conflicts. If it doesn't work, please provide details of how you are dealing with mobileinit
This is what ultimately made my day. And hopefully it should help others as well.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Project</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var dd = $.Deferred();
var jqd = $.Deferred();
$.when(dd, jqd).done(doInit);
</script>
<script src="js/MyOwn.js"></script>
<script src="js/jquery.mobile-1.3.2.min.js"></script>
<script type="text/javascript" src="js/cordova.js"></script>
<script type="text/javascript" src="js/cordova-2.6.0.js"></script>
<script type="text/javascript">
$(document).bind('mobileinit', function () {
jqd.resolve();
});
document.addEventListener('deviceready', deviceReady(), false);
function deviceReady() {
dd.resolve();
document.addEventListener("menubutton", function(e) {
e.preventDefault();
MyCustomMenuFunction();
}, false);
document.addEventListener("backbutton", function(e) {
e.preventDefault();
MyCustomBackFunction();
}, false);
onDeviceReady();
}
function doInit() {
onDeviceReady();
}
</script>
<link rel="stylesheet" href="js/jquery.mobile-1.3.2.min.css">
</head>
Two thing to be noted:
- As I am new to this stuff, I was not adding cordova js earlier. After I added cordova-2.6.0.js then only menubutton started working. Whereas backbutton started working after I added cordova.js as well.
- "deviceReady()" works but "deviceReady" doesn't. Don't know why.
Related
I'm currently using cordova 3.7.1. In my app I'm not able to detect the hardware back button in my jquery script. I trying out like this:
$(document).ready(function() {
//registering the back button
document.addEventListener("backbutton", onBackKeyDown, false); });
function onBackKeyDown(e) {
alert("back button pressed");//alert if the android back button is pressed
}
But this does not work. I have tried all possibility
I have also tried to get the current URL in the MainActivity.java using
appView.getUrl();
But this does not return the url of the div
If I have a div as #page2 it is not returning the url.
It only returns http://sas.cer.org/index.html. Its is not returning http://sas.cer.org/index.html#page2
I'm also using jquery mobile.
Are there any alternatives for handling the android/hardware back button on the Native or on the Jquery side??
There are two solutions :
1) You need to include cordova.js in script tag in head section in your index html file to make the events and plugins work.
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
You might not be able to see this file in your folder, but the phonegap | cordova command builds it when running on mobile.
2) Modify your code as given here.
Use mobile-specific events for proper functioning of your app.
The following is employed and working great in an app we deploy to cordova and web.
Requireswindow._cordovaNative = true if in cordova.
I left my button handling code in there as example (see "// close menu if open" and other comments), which you need to replace with your code.
Put this somewhere:
let bNH, bakNavHandler = bNH = {
warningOpen: false,
init: function(){
if (window._cordovaNative)
document.addEventListener('backbutton', this.onback, false);
else {
if (!window.performance || performance.navigation.type != 1)
this.preventDefault();
window.onpopstate = this.onback;
}
},
preventDefault: function(e){
window._cordovaNative ?
e.preventDefault() :
window.history.pushState(null, '', window.location.href);
},
onback: function(e){
// close menu if open
if ($('#ekapp_menu_div').css('margin-right') == '-2px'){
bNH.preventDefault(e)
_that.hideMenuDiv();
}
// close modal if open
else if (!bNH.warningOpen && $('#ekapp_modal:visible')[0]){
bNH.preventDefault(e)
_that.closeModal();
}
// prev screen if history
else if (_that.history.length > 1) {
bNH.preventDefault(e)
_that.previousScreen();
}
// show close app warning
else if (!bNH.warningOpen) {
if (window._cordovaNative)
bNH.preventDefault(e);
_that.openModal('Tap back button again to exit app!');
bNH.warningOpen = true;
$('#ekapp_modal_buttons .ekapp_cancel_btn').one('click', function(){
bNH.warningOpen = false;
if (!window._cordovaNative)
bNH.preventDefault();
});
}
}
};
Then in your deviceready (cordova) or doc ready (web) init function do:
bakNavHandler.init();
Read the doc, you have a full example there
You have to listen for the deviceready event, not for document ready
<!DOCTYPE html>
<html>
<head>
<title>Back Button Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
}
</script>
</head>
<body onload="onLoad()">
</body>
</html>
I'm new to Phonegap and having problems firing 'deviceready' event. Initially when run for the first time, the 'deviceready' event fired and worked. Later as I added more events ('backbutton', 'menubutton'...), I noticed 'deviceready' event and all other events stopped firing.
Here is the index.html code:
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap Device Ready Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function onBodyLoad() {
document.addEventListener("deviceready", onDeviceReady, true);
}
function onDeviceReady() {
alert("Device Ready!!!");
}
</script>
</head>
<body onload="onBodyLoad()">
First PhoneGap App...
</body>
</html>
I have reviewed similare post in StackOverFlow and tried all options but still does not seem to work.
Please help me at the earliest as I need to quickly learn PhoneGap for further implementation. Hoping quick response.
Thanks,
RK
you can simply use following code for trigger various events like (backbutton,menubutton)
in script tag
$(document).ready(function()
{
document.addEventListener("deviceready", appReady, false);
function appReady()
{
document.addEventListener('backbutton', function(e){
var activePage = $.mobile.activePage.attr('id');
if(activePage == 'main')
{
if (confirm("Press a button!"))
{
alert("You pressed OK!");
navigator.app.exitApp();
}
else
{ alert("You pressed Cancel!");
}
}
}, false);
}
});
I'm working my way through my first phonegap tutorial but I'm having problems.
I've set that the onDeviceReady() function be called when the "deviceready" event is fired, but the method is never called.
I tried calling the App.start() method directly, but I get an error in the console that the APP.start() method doesn't exist.
Thanks for your help!
The code for Index.html and App.js is below:
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport"
content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<script type="text/javascript" charset="utf-8"
src="cordova/cordova-2.2.0-android.js"></script>
<script type="text/javascript" charset="utf-8"
src="framework/utility.js"></script>
<script type="text/javascript" charset="utf-8"
src="app.js"></script>
<link rel="stylesheet" href="framework/base.css" type="text/css" />
<link rel="stylesheet" href="style/style.css" type="text/css" />
<title>Chapter 1 App: Quiz Time</title>
</head>
<body>
<div class="container" id="rootContainer">
</div>
<div id="preventClicks"></div>
</body>
</html>
app.js
document.addEventListener("load",function(){
document.addEventListener("deviceready",onDeviceReady,false);
},false);
function onDeviceReady() {
alert("WOAH!");
start();
}
start = function() {
PKUTIL.include([ "framework/ui-core.js", "framework/device.js" ],
function() {
init();
});
}
init = function() {
PKUI.CORE.initializeApplication();
PKUTIL.loadHTML("views/gameView.html", {
id : "gameView",
className : "container",
attachTo : $ge("rootContainer"),
aSync : true
}, function(success) {
if (success) {
gameView.initializeView();
}
});
PKUTIL.loadHTML("views/endView.html", {
id : "endView",
className : "container",
attachTo : $ge("rootContainer"),
aSync : true
}, function(success) {
if (success) {
endView.initializeView();
}
});
PKUTIL.loadHTML("views/startView.html", {
id : "startView",
className : "container",
attachTo : $ge("rootContainer"),
aSync : true
}, function(success) {
if (success) {
startView.initializeView();
PKUI.CORE.showView(startView);
}
});
}
UPDATE:
Changed type="application/javascript" to `type="text/javascript"'
add deviceready listener in load listener.
Still no luck!
Replace your tags with:
<script type="text/javascript" ...
using a application/javascript mime type isn't the standard approach.
Check your code for syntax errors (run it in Safari, or Chrome etc with the console open to see them). I find that when things don't work in PhoneGap it's usually because a JS error has crept in somewhere.
Remove all the scripts except the thing you're trying to test (lines to set the deviceready event, and the function it runs), then introduce each block of code and script one-by-one to see when it stops. That way you can isolate the block of code that is causing the problem.
I have experienced a similar problem myself. I will try to offer whatever advice I can.
First up, If you look at the Phonegaps Device Ready documentation, it notes that Typically, you will want to attach an event listener with document.addEventListener once the HTML document's DOM has loaded.. The reason for this, if you look at the source code, is that they're actually overriding document.addEventListener with their own function which handles all bindings of deviceready.
I found myself that when I was loading phonegap dynamically, if I would add my event listener for devicereadybefore it had hooked in, it would never come, but if I waited until the script element was loaded, it worked fine. Usually if you're just working with <script> tags directly, they actually load synchronously, so this isn't an issue. It's possible that having the scripts in the body element might cause them to load in a non-synchronous fashion, so I'd probably try moving them to the head or just above the </html>, and try changing to a more standard script element, like Henry suggests.
<script type="text/javascript" src="cordova/cordova-2.2.0-android.js"></script>
<script type="text/javascript" src="framework/utility.js"></script>
<script type="text/javascript" src="app.js"></script>
Your js should be like this
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
alert("WOAH!");
start();
}
function start() {
PKUTIL.include([ "framework/ui-core.js", "framework/device.js" ],
function() {
init();
});
}
When your js is load, and cordova ready, your function onDeviceReady will be executed. This function will do an alert and then call the function start.
Try to change
$$(document).on('deviceready', function() {
// Your content here
});
For
$$(document).on('DOMContentLoaded', function(){
// Your content here
});
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap Back Button Example</title>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Call onDeviceReady when PhoneGap is loaded.
//
// At this point, the document has loaded but phonegap-1.2.0.js has not.
// When PhoneGap is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is loaded and it is now safe to call PhoneGap methods
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {alert("back button pressed");
}
</script>
</head>
<body onload="onLoad()">
</body>
</html>
I want to ask if user want to exit from my app, when it click on back button.
I read this example from http://docs.phonegap.com/en/1.2.0/phonegap_events_events.md.html#backbutton
but it is not working...
How can I do to do it?
I SET SOME ALERT IN ONDEVICEREADY FUNCTION, AND I HAVE SEEN THAT IS NEVER FIRED THIS METHOD....SO THE EVENTLISTENERE DEVICEREADY IS NEVER FIRED...WHY?????
Thanks a lot.
It looks like you should definitely see the alert based on your code and your link. However the tutorial is for version 1.2 and you're using version 2.2. You may want to check that for tutorials using the same version. If one doesn't exist then the functionality may have been removed or you'll need to discuss with the Cordova developers about this problem.
If onDeviceReady() is not fired means that PhoneGap is not yet loaded.
Please make sure that your cordova-2.2.0.js file is in the correct location. As per your sample ".html" and "cordova-2.2.0.js" file should be in the same folder
How will I create a simple onClick() if else statement. that when the user hits the backbutton it will lead to the previouse page or activity in android? below is my code but i know there something missing. and can you please help me out? I am using eclipse with phonegap for Android.
Here is my Code:
<script type="text/javascript" charset="utf-8">
document.addEventListener("backbutton", onBackKeyDown, false);
</script>
<script type="text/javascript" charset="utf-8">
function onBackKeyDown() {
/* WHAT SHOULD I PUT IN HERE? any suggestions?*/
}
</script>
Many thanks to all of you guys.
You have registered a listener which will listen to the BackKey of Android.
Now Suppose you want to navigate to a page then you just need to do this
<script type="text/javascript" charset="utf-8">
document.addEventListener("backbutton", onBackKeyDown, false);
</script>
<script type="text/javascript" charset="utf-8">
function onBackKeyDown() {
navigator.app.loadUrl("file:///android_asset/www/something.html"); //to go to a page
}
</script>
Is this what you want to go to a Page?