2

How do I detect the browsers back button is clicked in IE 11 browser. In IE <10 browsers we can achieve this functionality using the following:

(window.event.clientX < 40 && window.event.clientY < 0).

Please share your thoughts.

Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
  • 1
    you might want to check this [answer](http://stackoverflow.com/questions/21274085/internet-explorer-11-back-button-javascript-behavior) – Amit.rk3 Jun 12 '15 at 14:09

1 Answers1

0

The code below will detect the back button's click. The /* Your code here! */ is whatever you want to do when the back button is clicked.

window.addEventListener("popstate", function (event) {
    /* Your code here! */
}, false);
window.history.pushState({}, "", window.location.toString());

By default, clicking the back button will make it go back. To stop it, use event.preventDefault(). If you want to make it go back manually, just use window.history.back().

This will only work in IE11. IE10 or older doesn't support the history API.

clickbait
  • 2,818
  • 1
  • 25
  • 61
  • Is there a way to detect browser close (X) event. I tried to use the popstate but it works only when the history changes. I did not find a solution to detect closing of a browser. Any help please. – user1148896 Jun 15 '15 at 15:16
  • You can't detect closing a browser. You CAN detect when your page is exited, though. – clickbait Jun 15 '15 at 18:17