'Phonegap - navigator.app.backHistory() not working on HTML back button
In my app i am using phonegap 2.6.For back button, I am using the following function
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown() {
alert("hello");
navigator.app.backHistory();
}
document.addEventListener('deviceready', onDeviceReady, true);
The above function works fine when I click on the device's hardware back button. But when I click on the back button it is not working.
I have designed my back button as below:
<a class="ui-link" href="#" rel="external" onclick="onBackKeyDown()">
<img src="images/icon-back.png" alt="Phone" border="0">
</a>
But this button is working fine for this navigator.app.exitApp(); (application exit).
//Working Fine
function onBackKeyDown() {
navigator.app.exitApp();
}
//Not Working
function onBackKeyDown() {
navigator.app.backHistory();
}
but not working for navigator.app.backHistory();.
Solution 1:[1]
If you use the attribute data-rel="back" on an anchor, any clicks on that anchor will mimic the back button, going back one history entry and ignoring the anchor's default href.
Solution 2:[2]
it depends where you are: on my windowsphone 8.1 lumia 925, it works history.go(-1);, while navigator.app.backHistory(); causes an exception before crashing.
On my Android (I believe the majority), navigator.app.backHistory(); works properly.
Solution 3:[3]
This might help some people, as it helped me fix the history.go(-1) not working in google chrome browser.
// Doesn't work in Chrome browser
function onBackKeyDown() {
history.go(-1);
navigator.app.backHistory();
}
// Does work in Chrome browser
function onBackKeyDown() {
history.go(-1);
return false; //needed in chrome to prevent about:blank page.
navigator.app.backHistory();
return false; //needed in chrome to prevent about:blank page.
}
Im no expert at all in jQuery, but thought it might help someone, as I was looking for this answer but couldn't find it at first.
Solution 4:[4]
Solved! Stop getting "TypeError: navigator.app is undefined"
A function I created that will first check what device you're on and then apply the relevant script:
function onBackKeyDown() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (userAgent.match(/iPad/i) || userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
// IOS DEVICE
history.go(-1);
} else if (userAgent.match(/Android/i)) {
// ANDROID DEVICE
navigator.app.backHistory();
} else {
// EVERY OTHER DEVICE
history.go(-1);
}
}
Call function by adding this to your back link/button:
onclick="onBackKeyDown()"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mehmet |
| Solution 2 | eeadev |
| Solution 3 | Mathijs |
| Solution 4 |
