admin管理员组

文章数量:1405345

I've done some research but couldn't find a solution.

I have a landingpage.html. I want to redirect a user to anotherpage.html when he/she presses the back button in the browser.

So I've tried this code:

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

It works not quite as expected: when the back button is pressed the browser address bar displays anotherpage.html page, however no actual redirection happens.

I've done some research but couldn't find a solution.

I have a landingpage.html. I want to redirect a user to anotherpage.html when he/she presses the back button in the browser.

So I've tried this code:

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

It works not quite as expected: when the back button is pressed the browser address bar displays anotherpage.html page, however no actual redirection happens.

Share Improve this question asked May 25, 2020 at 15:45 MergerMerger 531 gold badge1 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

You could add an event listener for popstate so when the user presses back it fires and you can load in that page.

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

Have you tried doing location.href='<url>' You can check here as well w3schools

You can use the main object window to do navigations stuff.

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

And to trigger to your button, subscribe the keyboard key

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

not sure if it will allow on every browser though

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

history.back = hackBackButton();

本文标签: Redirect to a URL when browser back button is pressed using JavaScriptStack Overflow