【问题标题】:Redirect to a URL when browser back button is pressed using JavaScript使用 JavaScript 按下浏览器后退按钮时重定向到 URL
【发布时间】:2020-09-12 07:17:13
【问题描述】:

我做了一些研究,但找不到解决方案。

我有一个landingpage.html。当用户按下浏览器中的后退按钮时,我想将用户重定向到 anotherpage.html。

所以我试过这段代码:

let currentUrl = location.href;
history.replaceState('', '', 'anotherpage.html');
history.pushState('', '', currentUrl);

它的工作方式并不像预期的那样:当按下后退按钮时,浏览器地址栏会显示 anotherpage.html 页面,但不会发生实际的重定向。

【问题讨论】:

    标签: javascript redirect back-button


    【解决方案1】:

    您可以为popstate 添加一个事件侦听器,这样当用户按下它时它就会触发并且您可以在该页面中加载。

    addEventListener('popstate',()=>{location.reload()})
    

    【讨论】:

    【解决方案2】:

    您可以使用主对象窗口进行导航。

    window.location.href = "html page path";

    要触发您的按钮,请订阅键盘键

    document.addEventListener('keypress', (e) => {
      if (e.key === 'your key name') window.location.href = "html page path";
    });
    

    【讨论】:

    • 没有使用浏览器后退按钮触发按键...它不在窗口或document 上下文中
    • 更改浏览器返回按钮没有意义,浏览器已经返回上一页。修改它会使用户感到困惑。
    • 我同意,但这就是问题所在
    【解决方案3】:

    你试过location.href='<url>' 你也可以在这里查看w3schools

    【讨论】:

      【解决方案4】:

      不确定是否允许在每个浏览器上使用

      function hackBackButton(){
      location.href = "anotherpage.html";
      }
      
      history.back = hackBackButton();
      

      【讨论】:

      • 另一个简单的事情可能是拦截页面的卸载。
      猜你喜欢
      • 2012-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-17
      • 2017-06-29
      • 2012-12-19
      • 2023-03-08
      • 2012-10-14
      • 2017-05-23
      相关资源
      最近更新 更多