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);
}
related: call e. stopImmediatePropagation() to prevent subsequently-added popstate handlers from firing too. For instance, if a router listens to popstate and replaces content accordingly, you can prevent it from replacing content. The text you insist on re-adding isn't appropriate; stop rolling back.
The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.
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 a
if(event.state === null) {
event.preventDefault();
return false;
}
To 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.
I have a solution!
window.pop_old = document.location.pathname;
window.pop_new = '';
window.onpopstate = function (event) {
window.pop_new = document.location.pathname;
if(pop_new != pop_old){
//diferent path: not just the hash has changed
} else {
//same path: just diferent hash
}
window.pop_old = pop_new; //save for the next interaction
};
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