How can I ignore [removed] on page load?

前端 未结 4 1057
一个人的身影
一个人的身影 2020-12-04 23:52

I\'m playing with window.onpopstate, and there is a thing that annoys me a little bit:

Browsers tend to handle the popstate event differe

相关标签:
4条回答
  • 2020-12-05 00:29

    I had a similar problem and i had to validate to make sure if page was loaded completely.

    I used something like this :

    var page_loaded = false;    
    window.onpopstate = function(event){
        if(!page_loaded){
           page_loaded = true;
           return false;
         }
        //Continue With Your Code
    }
    
    0 讨论(0)
  • 2020-12-05 00:39

    To react on popstate event, you need to push some state onto the session history.

    For example add this line to the document ready section:

    history.pushState(null, null, window.location.pathname);
    

    Not ideal, but it works in Chrome, Firefox and other browsers as well.

    Then the event is fired correctly when user clicks on Back or Forward button, also when history.back(), history.forward(), history.go() methods are called manually. Each time when popstate has been invoked, you have to push another state again to make it working.

    See also:

    • Single-Page Apps and HTML5 pushState
    • How to Detect Browser Back Button event - Cross Browser
    0 讨论(0)
  • 2020-12-05 00:40

    It seems none of the browsers are emitting the event on page load any more as of today:

    Browsers used to handle the popstate event differently on page load, but now they behave the same. Firefox never emitted a popstate event on page load. Chrome did until version 34, while Safari did until version 10.0.

    Source: https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent

    0 讨论(0)
  • 2020-12-05 00:41

    Check for boolean truth of event.state in popstate event handler:

    window.addEventListener('popstate', function(event) {
        if (event.state) {
            alert('!');
        }
    }, false);
    

    To ensure this will work, always specify a non-null state argument when calling history.pushState() or history.replaceState(). Also, consider using a wrapper library like History.js that provides consistent behavior across browsers.

    0 讨论(0)
提交回复
热议问题