简体   繁体   中英

Redirect to a URL when browser back button is pressed using JavaScript

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.

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()})

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";
});

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

not sure if it will allow on every browser though

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

history.back = hackBackButton();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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