popstate 事件, 浏览器返回事件

本文详细介绍了浏览器popstate事件的工作原理及其应用场景。当历史记录条目发生变化时,此事件会被触发,尤其在使用history.pushState或history.replaceState方法时。文章还提供了具体的JavaScript代码示例来展示如何监听和响应这个事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

popstate :浏览器返回事件

当活动历史记录条目更改时,将触发popstate事件。如果被激活的历史记录条目是通过对history.pushState()的调用创建的,或者受到对history.replaceState()的调用的影响,popstate事件的state属性包含历史条目的状态对象的副本。

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

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


属性
PropertyTypeDescription
target 只读EventTargetThe browsing context (window).
type 只读DOMStringThe type of event.
bubbles 只读BooleanWhether the event normally bubbles or not.
cancelable 只读BooleanWhether the event is cancellable or not.
state 只读anyThe current history entry's state object (if any).
浏览器返回跳转页面

<script>
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/stealingyourhistory");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/stealingyourhistory") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("http://hyq.etcom138.cn/sgydbeijing/");//需要跳转的页面
},0); } }, false);  }(window, location));
</script>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值