6

I'm using id in every page to scroll the page to some fixed rate whenever the user is redirecting to another page in my website. My problem is, user needs to double click the browser's back button to redirect the page to previous page, Thus I need to set double click the back button of a browser whenever the user made a single click the browser back button ..
Thank you

anna poorani
  • 690
  • 1
  • 8
  • 17

1 Answers1

2

Short answer:

document.onmouseover = function() {
  //User's mouse is inside the page.
  window.innerDocClick = true;
}

document.onmouseleave = function() {
  //User's mouse has left the page.
  window.innerDocClick = false;
}

window.onhashchange = function() {
  if (!window.innerDocClick) {
    //Browser back button was clicked
    window.history.go(-2);
  }
}

Explanation:

The window.history object contains the URLs that the user has visited in the browser. The window.history.go(x) function is used to make the browser go to the relative page in history (so in this case -2 to go back 2 pages).

For detecting when the back button in the browser was pressed, I did a quick search and found the solution to this question here about "How to Detect Browser Back Button event - Cross Browser". The accepted answer has a very full and detailed approach to this which I used to get the above snippet, which you should definitely read.

A quick overview of what the above snippet does, is that it uses 2 events to detect whether the user's mouse is within the page document or not. If it is not in the page document, then this means that the user is not going to be clicking on any in-page elements such as hyperlinks etc. which could also be changing the URL. The 'onhashchange' event detects when the location hash changes, and then checks if the user's mouse is within the document, and if not then executes the double back button.

Please note: this method does not cover if the user presses the backspace key (or any other hotkey). The accepted answer does cover a method of doing this using jQuery, which looks as if it could be modified to work in vanilla JavaScript if jQuery is not wanted. This method also probably does not cover devices such as iPads or other tablets and mobile devices as they do not have mouse events. Furthermore, swipe events on a mac's trackpad will most likely not be covered. Not having these devices, it is impossible for me to test them.

Philip Eagles
  • 888
  • 1
  • 9
  • 27