popstate - Web API 接口参考 编辑
当活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。
需要注意的是调用history.pushState()
或history.replaceState()
不会触发popstate
事件。只有在做出浏览器动作时,才会触发该事件,如用户点击浏览器的回退按钮(或者在Javascript代码中调用history.back()
或者history.forward()
方法)
不同的浏览器在加载页面时处理popstate
事件的形式存在差异。页面加载时Chrome和Safari通常会触发(emit )popstate
事件,但Firefox则不会。
常规信息
- Specification
- HTML5
- Interface
- PopStateEvent
- Bubbles
- 是
- Cancelable
- 否
- Target
- defaultView
- Default Action
- 无
属性
Property | Type | Description |
---|---|---|
target 只读 | EventTarget | The browsing context (window ). |
type 只读 | DOMString | The type of event. |
bubbles 只读 | Boolean | Whether the event normally bubbles or not. |
cancelable 只读 | Boolean | Whether the event is cancellable or not. |
state 只读 | any | The current history entry's state object (if any). |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!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 |
示例
打开http://example.com/example.html页面运行以下代码,
会按预期那样打出log提示。
window.addEventListener('popstate', (event) => {
console.log("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(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
使用onpopstate
事件处理程序属性的相同示例:
window.onpopstate = function(event) {
console.log("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(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}
注意,虽然原始的历史项( http://example.com/example.html所对应的
)没有关联的状态对象(state object),但稍后调用history.back()激活该历史项时,仍会触发popstate事件。
相关事件
也可以看看
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论