使用JavaScript按下浏览器后退按钮时重定向到URL

问题描述 投票:0回答:4

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

我有一个Landingpage.html。我想在用户按浏览器中的“后退”按钮时将其重定向到anotherpage.html。

所以我尝试了这段代码:

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

它的工作效果与预期不符:按下后退按钮时,浏览器地址栏将显示anotherpage.html页面,但是未发生实际的重定向。

javascript redirect back-button
4个回答
1
投票

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

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

0
投票

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

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

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

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

0
投票

您是否尝试过location.href='<url>'您也可以在这里查看w3schools


0
投票

虽然不确定是否会允许每个浏览器使用

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

history.back = hackBackButton();
© www.soinside.com 2019 - 2024. All rights reserved.