javascript popstate 事件处理程序似乎不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14112341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:44:41  来源:igfitidea点击:

popstate event handler seems not to work

javascript

提问by petwho

I'm having a problem with a 'popstate' event handler, this is my code:

我的“popstate”事件处理程序有问题,这是我的代码:

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

// The data object is arbitrary and is passed with the popstate event.
var dataObject = {
    createdAt: '2011-10-10',
    author: 'donnamoss'
};

var url = '/posts/new-url';
history.pushState(dataObject, document.title, url);

I expected this code will pop up an alert box when it's executed but, nothing happens.

我希望这段代码在执行时会弹出一个警告框,但没有任何反应。

Is there anything wrong here?

这里有什么问题吗?

Thank you.

谢谢你。

回答by otakustay

pushStatedo not trigger the popstateevent, only clicking back / forward button (or use backspace) or invoking history.back()/ history.go(n)would trigger this event.

pushState不触发popstate事件,只有单击后退/前进按钮(或使用退格键)或调用history.back()/history.go(n)才会触发此事件。

Also, in webkit browsers, a popstateevent would be triggered after page's onloadevent, but Firefox and IE do not have this behavior.

另外,在 webkit 浏览器中,popstate会在页面onload事件之后触发一个事件,但 Firefox 和 IE 没有这种行为。

回答by Arun P Johny

No it will not,

不,不会,

As per MDN documentation

根据MDN 文档

Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).

请注意,仅调用 history.pushState() 或 history.replaceState() 不会触发 popstate 事件。popstate 事件仅通过执行浏览器操作触发,例如单击后退按钮(或在 JavaScript 中调用 history.back())。

Again as per this questionthe popstateevent is not triggered in Chromewhen you call pushState().

同样按照这一问题popstate事件不会在触发Chrome时调用pushState()

回答by u283863

history.pushState()will not trigger the popstateevent by definition.

history.pushState()popstate根据定义不会触发事件。

The popstate event is fired in certain cases when navigating to a session history entry.

在导航到会话历史记录条目时,在某些情况下会触发 popstate 事件。

This event is intended to be only triggered when navigating to a history entry, either by pressing the back/forward button, or history.go/back.

此事件仅在导航到历史条目时触发,通过按后退/前进按钮或history.go/back