Reputation: 473
I tried to implement the back button functionality in my wp8 cordova application , which on pressing the hardware back button on device should navigate to the previous page of the app .
What i have done
function onLoad() {
document.addEventListener("deviceready", init, false);
document.addEventListener("resume", onResume, false);
document.addEventListener("backbutton", onBackKeyDown, false);
}
function init() {
//some code
}
function onResume() {
//some code
}
function onBackKeyDown() {
window.history.back();
return false;
}
I also tried replacing the "window.history.back();" with "navigator.app.backHistory();" which also doesnot seems to work
Then i tried putting the code in try catch block
try
{
navigator.app.backHistory();
//window.history.back();
}
catch (e)
{
console.log("exception: " + e.message);
}
which also seems to fail .Whatever I do the app seems to exit out of the app rather than moving backward and the funny thing is when i try this in the IE console it seems to work perfectly
Please help with this guys
Thanks in advance
Upvotes: 4
Views: 1050
Reputation: 3793
So lets try another way which should work for wp8. This Method requires the WinJS Framework and will work like this:
In the onDeviceReady function you're going to use this code:
if (device.platform == "windows") {
// Get the back button working in WP8.1
WinJS.Application.onbackclick = function () {
onBackKeyDown();
return true; // This line is important, without it the app closes.
}
}
else {
document.addEventListener("backbutton", onBackKeyDown, false);
}
Now just add a function to handle the onBackKeyDown event and that's it:
function onBackKeyDown() {
// Back key pressed, do something here
}
The standard method of Cordova to hook into the BackButton-Event would look like this:
<!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>
Important here is to call the BackButton-Event inside the DeviceReady function!
Upvotes: 6