Vue:禁用浏览器的前进后退

一.禁用前进后退功能

在开发 vue 应用中,如何禁用浏览器的前进后退功能呢?

网上搜到的答案基本如下:

history.pushState(null, null, document.URL)
window.addEventListener('popstate', function() {
  history.pushState(null, null, document.URL)
})

但应该放在哪儿?

经过尝试,我是如此写的:

main.js 中,增加 popstate 监听

window.addEventListener('popstate', function() {
  history.pushState(null, null, document.URL)
})

router 的 index.js 中:

const router = new Router({
  mode: 'hash',
  routes,
  scrollBehavior: () => {
    history.pushState(null, null, document.URL)
  }
})

这里我将 pushState 放在了 scrollBehavior 中。当然,你也可以尝试放在 router 的 beforeEach/afterEach 中

router.afterEach((to, from) => {
  history.pushState(null, null, location.protocol + '//' + location.host + '/#' + to.path)
})

不过这里的 URL 就不能使用 document.URL 了,因为此时的 document.URL 指向的是上一页面的 URL,这会导致第一次页面回退禁用无效

二.history

history 对象包含浏览器历史。

常见属性/方法:

  • history.length - 属性保存着历史记录的 URL 数量;
  • history.back() - 等同于在浏览器点击后退按钮;
  • history.forward() - 等同于在浏览器中点击前进按钮;
  • history.go() - 加载 history 列表中的某个具体页面。

 H5新增了属性/方法/事件:

  • history.state - 属性用来保存记录对象;
  • history.pushState() - 向浏览器的历史记录中添加一个状态;
  • history.replaceState() - 修改当前历史记录实体;
  • popstate事件 - 当活动历史记录条目更改时,将触发

1.history.state

返回当前页面的 state 对象

2.history.pushState(state, title, url)

state: 状态对象可以是任何可以序列化的对象。

title: 当前大多数浏览器都忽略此参数,尽管将来可能会使用它。

url: 新历史记录条目的 URL 由此参数指定。如果未指定此参数,则将其设置为文档的当前 URL。

3.history.replaceState(state, title, url)

修改当前历史记录实体,如果你想更新当前的 state 对象或者当前历史实体的 URL 来响应用户的的动作的话这个方法将会非常有用。

参数与 pushState 类似。

4.popstate事件

当活动历史记录条目更改时,将触发 popstate 事件。

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

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

更多 history 的介绍参考:MDN(history)

相关文章:javascript History 对象详解

猜你喜欢

转载自blog.csdn.net/qq_39025670/article/details/108020287