Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

popstate

当前活动历史项(history entry)改变会触发popstate事件。调用history.pushState()创建新的历史项(history entry),或调用history.replaceState()替换新的历史项(history entry),那么popstate事件的state属性会包含历史项(history entry)状态对象(state object)的拷贝。

需要注意的是调用history.pushState()history.replaceState()不会触发popstate事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()

不同的浏览器在加载页面时处理popstate事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate事件,但Firefox则不会。

常规信息

Specification
HTML5
Interface
PopStateEvent
Bubbles
Cancelable
Target
defaultView
Default Action

属性

Property Type Description
target 只读 EventTarget 浏览上下文 (<code>window</code>).
type 只读 DOMString The type of event.
bubbles 只读 boolean Does the event normally bubble?
cancelable 只读 boolean Is it possible to cancel the event?
state 只读 any The current history entry's state object (if any).

浏览器兼容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support Yes 4.0 (2) 10.0 Yes limited
Feature Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support 3.0 (buggy in 2.2 and 2.3) 4.0 (2) 10.0 Yes limited

示例

 打开https://example.com/example.html页面运行以下代码, 会按预期那样弹出alert提示。

window.onpopstate = function(event) {
  alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // alerts "location: https://example.com/example.html?page=1, state: {"page":1}"
history.back(); // alerts "location: https://example.com/example.html, state: null
history.go(2);  // alerts "location: https://example.com/example.html?page=3, state: {"page":3}

注意,虽然原始的历史项( https://example.com/example.html所对应的)没有关联的状态对象(state object),但稍后调用history.back()激活该历史项时,仍会触发popstate事件。

相关事件

文档标签和贡献者

 此页面的贡献者: HuarenYu, saviroyu, manjun.han, ziyunfei
 最后编辑者: HuarenYu,