Chrome onpopstate / pushState bug?

前端 未结 2 1367
你的背包
你的背包 2021-01-05 09:18

First of all I\'m not entirely sure what I\'m doing or expecting is right. There doesn\'t seem to be much documentation about this, but what I\'ve read suggests that this sh

相关标签:
2条回答
  • 2021-01-05 09:35

    Chrome's console.log cannot handle things nicely when you're going to other pages. You can confirm this because it logs several things at once with other timestamps (which cannot be possible). You'd better use $("body").append to log here (or appending to some other element).

    Secondly, when you push a state, then obviously it is not popped, so the popstate event is not triggered. If you want to trigger the onpopstate handler when you're pushing a state as well, you can create a simple wrapper like this: http://jsfiddle.net/vsb23/2/.

    function load(url, state) { // logging function; normally load AJAX stuff here
        $("pre").append(new Date
                        + "\n" + url
                        + "\n" + JSON.stringify(state) // to log object as string
                        + "\n\n");
    }
    
    function pushState(data, title, url) {
        history.pushState(data, title, url);
        load(location.href, data); // call load function when pushing as well
    }
    
    window.onpopstate = function(e) {
        load(location.href, e.state);
    };
    
    $("button").click(function() {
        pushState({foo: "bar"}, "test", "/test?a=b"); // sample push
    });
    

    Edit: This is already a bug on the Chromium bug tracker.

    0 讨论(0)
  • 2021-01-05 09:53
    if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1 !== true) {
        runpopState();
    }
    
    function runpopState() {
        alert("POP STATE");
    }
    
    window.onpopstate = function () {
        runpopState();
    };
    

    Until they fix the bug, a solution like this will suffice.

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