繁体   English   中英

如何不使用pushstate捕获浏览器的后退按钮?

[英]How to capture back button of the browser without using pushstate?

我尝试使用pushstate和popstate在浏览器上捕获后退按钮动作,但是问题是pushstate更改了历史记录,从而影响了后退按钮的正常功能。

大多数人建议使用:

window.onhashchange = function() {
    if (window.innerDocClick) {
        window.innerDocClick = false;
    } else {
        if (window.location.hash != '#undefined') {
            goBack();
        } else {
            history.pushState("", document.title, window.location.pathname);
            location.reload();
        }
    }
}
function goBack() {
    window.location.hash = window.location.lasthash[window.location.lasthash.length-1];
    //blah blah blah
    window.location.lasthash.pop();
}

创建一个数组,该数组收集对window.location.lasthash所做的所有更改的用户window.location.hash。

const updateHistory = (curr) => {
    window.location.lasthash.push(window.location.hash);
    window.location.hash = curr;
}

不幸的是,单击浏览器的后退按钮不会触发任何本机事件。 但是,有一种很好的方法可以结合使用其他本机事件侦听器来伪造它。

首先,设置一个布尔值,每次通过呈现onmouseover事件来呈现文档时都会切换该布尔值。

const onDocRenderHandler = (bool) => {
    window.innerDocClick = bool;
}

document.onmouseover = onDocRenderHandler(true)

用户单击“后退”按钮后,文档再次呈现,因此将布尔标志设置为再次切换; 只是这一次监听onmouseleave事件。

document.onmouseleave = onDocRenderHandler(false)

最后,侦听在文档渲染之间触发的onhashchange事件。 这模拟了一个伪后退按钮事件,让我们可以监听并采取行动。

const onHashChangeHandler = () => {
    if(!window.innerDocClick) {
        history.pushState("", document.title, window.location.pathname);
        location.reload();
    }
}
window.onhashchange = onHashChangeHandler()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM