Is there a way to catch the back button event in javascript?

Is there a way to respond to clicking a button back (or pressing backspace) in javascript when only the location hash changes? That is, when the browser does not interact with the server or does not reload the page.

+50
javascript
Sep 25 '08 at 23:45
source share
6 answers

Use the hashchange event:

 window.addEventListener("hashchange", function(e) { // ... }) 

If you need to support older browsers, check out the hashchange section> on the Polyphills wiki page in the Modernizr HTML5 browser.

+25
Sep 25 '08 at 23:50
source share

I created a solution that may be useful for some people. Just add the code to your page, and you can write your own function that will be called when you click the "Back" button.

I tested in IE, FF, Chrome, and Safari, and they all work. However, an iframe-based solution, without the need for constant polling, in IE and FF, due to limitations in other browsers, Safari uses a location hash.

+12
Feb 27 '10 at 16:38
source share

I made a funny hack to solve this problem to my satisfaction. I have an AJAX site that dynamically loads content and then modifies window.location.hash, and I had code to work with $ (document) .ready () to parse the hash and load the corresponding section. The fact is that I was completely satisfied with the loading code for the navigation section, but I wanted to add a way to intercept the browser buttons back and forth, which change the location of the window, but do not interfere with my current page loading routines, where I manipulate window.location, and poll the window . A cell with constant intervals is out of the question.

As a result, I created an object as such:

 var pageload = { ignorehashchange: false, loadUrl: function(){ if (pageload.ignorehashchange == false){ //code to parse window.location.hash and load content }; } }; 

Then I added a line to my website script to run the pageload.loadUrl function on hashchange as such:

 window.addEventListener("hashchange", pageload.loadUrl, false); 

Then, anytime I want to change window.location.hash without starting this procedure to load this page, I simply add the following line before each line of window.location.hash = :

 pageload.ignorehashchange = true; 

and then the following line after each line of the hash modification:

 setTimeout(function(){pageload.ignorehashchange = false;}, 100); 

So, now my partition loading procedures usually start, but if the user presses the back or forward buttons, the new location is analyzed and the corresponding section is loaded.

+6
Feb 23 2018-12-12T00:
source share

Check out history.js . There is an html 5 state change event and you can listen to it.

+3
Jul 17 '12 at 19:33
source share
+2
Sep 25 '08 at 23:52
source share

onLocationChange may also be useful. Not sure if it's just Mozilla, but it seems like it could be.

+1
Sep 25 '08 at 23:48
source share



All Articles