I am working with the History API and using push and pop state. I want to stop the popstate event from firing in some scenario where I am only appending the hash to URL. for example in some cases on click of anchor it appends #
to the URL and popstate is immediately fired) I want to avoid all the scenarios where #
or #somehasvalue
is appended to the URL and stop popstate from firing. I am mainitaing the URL's with query parameters and I do not have any scenario where I need the popstate event to fire with #
in the URL.
Here is my code.
if (supportsHistoryApi()) {
window.onpopstate = function (event) {
var d = event.state || {state_param1: param1, state_param2: param2};
var pathName = window.location.pathname,
params = window.location.search;
loadData(event, pathName + params, d.state_param1, d.state_param2);
}
As far as I found you cannot stop the popstate from firing unfortunately.
What you can do is check for the
event.state
object. That will be null on a hash change. So I'd suggest adding aTo your popstate event handler at the very beginning. I think that's the best way to prevent firing of the popstate handling code on your side when the hash changes, but i'd be interested to know if there are other solutions.
In case someone still need this:
This is pretty simple.
To prevent the
popstate
event to fire after you click a link with hash you have to eliminate the concequence of clicking the link - which is the addition of the hash to the browser address bar.Basically you have to create the handler for
click
event, check if the click is on the element you whant to prevent a hash to appear in the URL and prevent hash to appear by callingevent.preventDefault();
in the handler.Here is the code example:
Here is the matching HTML markup:
This all does what is described above: prevents the default behaviour for a special hash link. As a side effect it makes no
popstate
event to fire as no hash is added to URL for the special case of clicking the#the-link-i-want-make-discernable
hash link.