Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop firing popstate on hashchange

Tags:

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);

}
like image 716
Kalish Avatar asked Sep 03 '14 00:09

Kalish


People also ask

How do I stop Popstate?

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.

What triggers Popstate?

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.


2 Answers

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.

like image 66
Tschallacka Avatar answered Sep 19 '22 12:09

Tschallacka


I have a solution!

  • When popstate event calls, check the pathname if it has changed, or just the hash changed. Watch below how it works for me:
        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

        };
like image 32
Rodrigo Bedin Pereira Avatar answered Sep 20 '22 12:09

Rodrigo Bedin Pereira