Chrome onpopstate / pushState bug?

China☆狼群 提交于 2019-11-30 20:14:30

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!