Android Back Button - Prevent Default Behavior Not Working

  • 5
  • Question
  • Updated 5 years ago
  • Doesn't Need an Answer
I'm trying to prevent the default behavior when someone presses the 'Back' button on an Android device. I have successfully bound to the event, and it is firing correctly, but I cannot prevent the default behavior. I have searched online through countless posts and according to all previous posts, my current solution should work, but it does not.

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
document.addEventListener("backbutton", onBackKeyDown, false);
}

function onBackKeyDown(e) {
alert('back button triggered');
console.log(e);
e.preventDefault();
return false;
}

When the back button is clicked, I will get the alert, but it will not prevent the behavior. I have an Angular SPA application running in PhoneGap, so it usually mimics a browser's back behavior and changes the URL, therefore going to the previous page within the app.
Photo of crisp330

crisp330

  • 1 Post
  • 0 Reply Likes
  • frustrated

Posted 6 years ago

  • 5
Photo of Hristo Hristov

Hristo Hristov

  • 1 Post
  • 0 Reply Likes
Did you find a solution? I have the same problem.
Photo of Petra V.

Petra V., Champion

  • 7794 Posts
  • 1391 Reply Likes
You could check whether or not the event is cancelable at all, first:
http://help.dottoro.com/ljwolcsp.php
Photo of John Weidner

John Weidner, Champion

  • 435 Posts
  • 80 Reply Likes
I usually try calling both preventDefault and stopPropogation to kill an event.


if (e.preventDefault){
e.preventDefault();
}
if (e.stopPropagation) {
e.stopPropagation();
}
Photo of David Dykstra

David Dykstra

  • 4 Posts
  • 0 Reply Likes
I have the same issue as well, anyone find a solution? stopPropagation didn't work either.
Photo of Max Felipe Alvarado Obando

Max Felipe Alvarado Obando

  • 2 Posts
  • 0 Reply Likes
Did you guys find a solution for this?
Photo of JesseMonroy650 (Volunteer)

JesseMonroy650 (Volunteer), Champion

  • 3325 Posts
  • 122 Reply Likes
@Max, it is not good to add message to old threads, especially when they have been marked *Doesn't need an answer*.

On the backbutton issue, it does NOT need a e.preventDefault(); or e.stopPropagation();, you simply need to trap the event. The backbutton event is NON-standard so it behaves differently.

A full test of many of the phonegap events is here:
https://github.com/jessemonroy650/Pho...

An example for backbutton is at:
https://github.com/jessemonroy650/Pho...

Best of Luck,
Jesse
Photo of Max Felipe Alvarado Obando

Max Felipe Alvarado Obando

  • 2 Posts
  • 0 Reply Likes
Thanks for the feedback on both my question and the usage of the forum, Jesse. I think I just found out what was wrong. I was using the "onsen" library, and that one was also trapping the back button event.