Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect back button click in browser [duplicate]

I have to detect if a user has clicked back button or not. For this I am using

window.onbeforeunload = function (e) { } 

It works if a user clicks back button. But this event is also fired if a user click F5 or reload button of browser. How do I fix this?

like image 426
facebook Avatar asked Jun 15 '11 14:06

facebook


People also ask

What is window history?

history. The Window. history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in). See Manipulating the browser history for examples and details.

What is the use of back button?

Back button (web browser), a common web browser feature that retrieves the previous resource. Backspace key, the computer keyboard key that deletes the character(s) to the left of the cursor.


1 Answers

So as far as AJAX is concerned...

Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:

window.onload = function () {     if (typeof history.pushState === "function") {         history.pushState("jibberish", null, null);         window.onpopstate = function () {             history.pushState('newjibberish', null, null);             // Handle the back (or forward) buttons here             // Will NOT handle refresh, use onbeforeunload for this.         };     }     else {         var ignoreHashChange = true;         window.onhashchange = function () {             if (!ignoreHashChange) {                 ignoreHashChange = true;                 window.location.hash = Math.random();                 // Detect and redirect change here                 // Works in older FF and IE9                 // * it does mess with your hash symbol (anchor?) pound sign                 // delimiter on the end of the URL             }             else {                 ignoreHashChange = false;                }         };     } } 

As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

like image 187
Gus Crawford Avatar answered Sep 20 '22 21:09

Gus Crawford