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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With