将 URL 添加到浏览器后退按钮

Add a URL to browser back button

本文关键字:按钮 浏览器 URL 添加      更新时间:2023-09-26

我正在尝试在浏览器后退按钮上设置URL。 我看了几个例子,发现这段代码可以工作。 问题是当我单击锚按钮时,它的作用与单击浏览器后退按钮时相同。这不好。我相信问题出在这一行代码上 - 我可能是错的 -

window.addEventListener('popstate', function(event){ ... })

这是代码 -

history.pushState(null, null, '<?php echo $_SERVER["REQUEST_URI"]; ?>');
window.addEventListener('popstate', function(event) {
        window.location.assign("http://newurl.com");
});

我整天都在研究这个问题,但找不到解决方案。 有人可以帮忙吗?

这个答案已经给出了,但我会尝试用pushState来解释我的理解。

考虑您的网址是" google.com/gmail "

  1. 将当前URL设置为临时URL,以便您的浏览器将显示此URL。在此步骤中,堆栈中将有一个URL,即google.com/gmail#!/tempURL

    history.replaceState(null, document.title, location.pathname+"#!/tempURL");

  2. 将上一个URL
  3. 推送为新状态,所以现在您的浏览器将显示上一个URL,即google.com/gmail

    history.pushState(null, document.title, location.pathname);

    堆栈的当前状态:

    1. 第一个元素 : google.com/gmail
    2. 最后一个元素 : google.com/gmail#!/tempURL
  4. 现在将侦听器添加到侦听事件

    window.addEventListener("popstate", function() {
        if(location.hash === "#!/tempURL") {
            history.replaceState(null, document.title, location.pathname);
            //replaces first element of last element of stack with google.com/gmail so can be used further
            setTimeout(function(){
                location.replace("http://www.yahoo.com/");
            },0);
        }
    }, false);
    

如何更改网址并检测后退按钮