window bind POPSTATE

前端 未结 8 1954
一整个雨季
一整个雨季 2020-12-07 21:25

Given the following:

$(window).bind(\"popstate\", function() {
    alert(\'popstate\');
});

On first load, the alert fires with FireFox and

相关标签:
8条回答
  • 2020-12-07 22:11

    An easy way to avoid this issue is to set the first argument on pushState to true then check against onpopstate. Similar to the pjax example but a bit more straightforward. The below example will run doSomething() for every popstate event except for the first page load.

    function setupPopState() {
      if (history.popState) {
        # immediately replace state to ensure popstate works for inital page
        history.replaceState(true, null, window.location.pathname);
    
        $(window).bind('popstate', function(event) {
          if (event.originalEvent.state) {
            doSomething();
          }
        });
      }
    }
    
    0 讨论(0)
  • This answer to a similar question suggests to check for boolean truth of event.state in the popstate event handler:

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

    You can also tie your callback function to popstate event like this:

    window.onpopstate = callback();
    

    Check here for more information on that solution

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