[英]BackButton event affects other pages in PhoneGap
In my PhoneGap android app, in my Index.html page in OnDeviceReady() method I have added the following function for backbutton event listener. 在我的PhoneGap android应用中,在OnDeviceReady()方法的Index.html页面中,我为backbutton事件侦听器添加了以下功能。
document.addEventListener("backbutton", function(e) {
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if(sPage == "index.html"){
e.preventDefault();
// My action
return false;
} else {
return true;
}
}, false);
Problem Facing: 面对问题:
In my HomePage(Index.html) its working fine. 在我的HomePage(Index.html)中,它的工作正常。 If i press back button it gets closed.
如果我按下后退按钮,它将关闭。
But in all other pages (Page1.html,Page2.html,Page3.html,Page4.html) i havn't created backbutton event listener but nothing happens when i press back key. 但是在所有其他页面(Page1.html,Page2.html,Page3.html,Page4.html)中,我没有创建后退按钮事件侦听器,但是当我按下后退键时没有任何反应。
You can try by adding the following javascript code: 您可以尝试添加以下JavaScript代码:
document.addEventListener("backbutton", function(e) {
var sPath=window.location.pathname;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if(sPage == "index.html"){
e.preventDefault();
// Method to close Phonegap application
navigator.app.exitApp();
} else {
// Method to go back to previous page
navigator.app.backHistory();
}
}, false);
Alternate approach which definitely works but uses two JavaScript files... 替代方法肯定有效,但使用两个JavaScript文件...
I have used the following code for pages other than index.html : 除了index.html之外,我还使用了以下代码:
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is ready
function onDeviceReady() {
document.addEventListener("backbutton", function(e){
e.preventDefault();
navigator.app.backHistory();
return false;
}, true);
}
And on Home page you can add navigator.app.exitApp(); 在首页上,您可以添加navigator.app.exitApp(); and remove navigator.app.backHistory();
并删除navigator.app.backHistory();
Already answered here: PhoneGap - android exit on backbutton 已经在这里回答: PhoneGap-后退按钮上的android退出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.