如何检测history.pushState和history.replaceState何时使用? [英] How to detect when history.pushState and history.replaceState are used?

查看:156
本文介绍了如何检测history.pushState和history.replaceState何时使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改历史状态时是否可以订阅某些事件?怎么样?

Is there some event I can subscribe to when the history state is modified? How?

推荐答案

onpopstate事件应该在历史更改时触发,您可以像下面这样在代码中绑定on

The onpopstate event should be fired when the history changes, you can bind to it in your code like this:

window.onpopstate = function (event) {
  // do stuff here
}

当页面加载时,您可以触发此事件,您可以确定事件是从页面加载中触发的,还是通过使用pushState / replaceState通过检查事件对象的状态属性,如果事件是由页面加载引起的,它将是未定义的

This event may also be fired when the page loads, you can determine whether the event was fired from a page load, or by using pushState/replaceState by checking the event object for a state property, it will be undefined if the event was caused by a page load

window.onpopstate = function (event) {
  if (event.state) {
    // history changed because of pushState/replaceState
  } else {
    // history changed because of a page load
  }
}

目前没有onpushstate事件不幸的是,为了解决这个问题,你需要包装pushState和replaceState方法来实现你自己的onpushstate事件。

There currently is no onpushstate event unfortunately, to get around this you need to wrap both the pushState and replaceState methods to implement your own onpushstate event.

我有一个使pushState工作更轻松的库,可能值得检查一下,名为 Davis.js ,它提供了一个简单的API来处理基于pushState的路由。

I have a library that makes working with pushState a bit easier, it might be worth checking it out called Davis.js, it provides a simple api for working with routing based on pushState.

这篇关于如何检测history.pushState和history.replaceState何时使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆