禁止浏览器后退

禁止浏览器后退

需求为用户在当前页面不可以返回上一页面,怎么实现功能呢?利用history api pushState 与 popstate事件。

popstate

每当处于激活状态的历史记录条目发生变化时,popstate事件就会在对应window对象上触发. 如果当前处于激活状态的历史记录条目是由history.pushState()方法创建,或者由history.replaceState()方法修改过的, 则popstate事件对象的state属性包含了这个历史记录条目的state对象的一个拷贝. 调用history.pushState()或者history.replaceState()不会触发popstate事件.

pushState

可以添加历史记录,可以理解为,页面的url发生变化,但是页面没有刷新。

    /**
     * state 为一个对象,在用户导航到新的状态出触发popstate事件,作为事件的state属性
     * title 标题
     * url  新的页面url 可以为绝对路径也可以为相对路径
     */
    window.history.pushState(state, title, url);

如何实现

    let time = 0;
    // 添加历史记录
    window.onload(() => {
        window.history.pushState(null, null, `?times=${time}`);
    });
    window.addEventListener('popstate', () => {
        time += 1;
        window.history.pushState(null, null, `?times=${time}`);
    });
posted @ 2019-11-08 17:49  Pomm  阅读(976)  评论(0编辑  收藏  举报