popstate

94 阅读1分钟

如何使用

popState

window.addEventListener('popstate', (event) => {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});
或者
window.onpopstate = function(event) {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

pushState

history.pushState(state, title[, url])

参数namemeaning
state每当用户导航到新状态时,popstate 就会触发一个事件,并且state 该事件的 属性包含历史记录条目的状态对象的副本
title当前大多数浏览器都忽略此参数,尽管将来可能会使用它。在此处传递空字符串应该可以防止将来对方法的更改.
url新历史记录条目的URL由此参数指定

自定义浏览器返回到特定页面

mounted() {
  this.onpopstate();
}
onpopstate() {
    history.pushState({}, "");
    window.onpopstate = event => {
        if (this.something) {
            this.redirectUrl();
        } else {
            location.href = `/bookings/`;
        }
    };
},

页面点击浮层等模拟为二级页面

click() {
  this.showModal = true
  window.history.pushState(
    { page: 'mockPage' },
    '',
    window.location.href
  )
  window.addEventListener('popstate', this.onPopstate)
}
// 用户反击看浏览器返回时候,正好触发改事件,关闭掉模拟的耳机页面
onPopstate(e) {
    // 这里的就是页面返回时候的null, 或者是页面前进时候的state{ page: 'mockPage' }, 可以严格区分
    this.showModal = false
    window.removeEventListener('popstate', this.onPopstate)
}

没有触发

popstate事件在浏览器历史记录栈发生改变时触发,如果不触发,可能是因为以下原因:

  1. 浏览器安全策略,如果用户没有做任何操作,直接点击浏览器返回也不会触发
  2. 浏览器历史记录没有被改变。
  3. 使用的是hashchange事件而不是popstate事件。hashchange事件只会在URL哈希值改变时触发
  4. 调用 history.pushState() 或者 history.replaceState() 不会触发 popstate 事件。popstate 事件只会在浏览器某些行为下触发,比如点击浏览器后退前进按钮(或者在 JavaScript 中调用 istory.back() 、history.forward()、history.go() 方法)。