How to cancel popState in a specific state

The popState event will popState when the URL has changed (either backward or forward). And recently, I noticed that, for example, at http://www.example.com/ :

 <a href="#anchor">Top</a> 

also calls popState , causing the page to reload.
How can I find out if this is the same url and only the # part has changed?

 $(window).bind("popstate",function(){ swap(location.href); }) 

In this example, when you click the "Up" link (see above), the page will go to #anchor , but it will also call popState and cause a reload, which I do not expect.

+7
source share
3 answers

I could not find any of this event to determine if it was just a change in binding, so I had to track it myself using code, for example:

 function getLocation() { return location.pathname + location.search; } var currentLocation = getLocation(); $(function() { $(window).on("popstate", function() { var newLocation = getLocation(); if(newLocation != currentLocation) { // DO STUFF } currentLocation = newLocation; }); }) 

The place is stored without a hash, so when popstate is triggered by clicking the link to the binding, the getLocation method returns the same result as before, and there will be no code to replace the page.

To make sure that you are tracking the current location correctly, you also need to update the variable when you change state using pushState () or replaceState ()

+4
source

You can check window.location.hash to see what type of binding # added to it and take appropriate action.

Also, by checking window.onhashchange , you can distinguish between complete URL changes in window.location.href or just hash changes.

Example:

 window.onhashchange = function() { console.log('Hash change:' + window.location.hash); } 
0
source

This is all pretty simple. You need to make sure that the hash is not added to the address bar of the browser.

To do this, basically you need to add a click event handler, there to check if the link is the one you want to avoid, to start popstate when the hash changes, and, if so, to prevent the default behavior using event.preventDefault() .

I just wrote an answer with sample code and detailed explanations on a similar question here .

0
source

Source: https://habr.com/ru/post/910869/


All Articles