How can I control the back button event in jQuery Mobile?

I tried to control back button, but I can’t. In here;

Take control of the hardware back button using jQuery Mobile

  event.keyCode == 27 // That’s for escape
  event.keyCode == 8 // That’s for backspace...it's also working on browser, but it doesn’t work on my tablet.

How can I do it?


Recommended method pagecontainerbeforechange: https://jqmtricks.wordpress.com/2014/12/01/detect-back-navigation/


You need to listen to the navigation event and state.direction.

$(window).on("navigate", function (event, data) {
  var direction = data.state.direction;
  if (direction == 'back') {
    // Do something
  }
  if (direction == 'forward') {
    // Do something else
  }
});

jQuery Mobile API: Navigation event

Demo


You can do this without jQuery Mobile

window.addEventListener("hashchange", function(e) {
    if(e.oldURL.length > e.newURL.length)
        alert("back")
});
<a href="#p2">goto page 2</a> and then use browser's navigation.</div>

And also Demo in CodePen.