-1

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.

Merger
  • 33
  • 1
  • 4

4 Answers4

1

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()})
lusc
  • 1,206
  • 1
  • 10
  • 19
  • @Merger If you still need an explanation as to _why_ your code does not work as you expect, this may help: https://stackoverflow.com/a/12917772/746736 – Turnip May 25 '20 at 15:56
0

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";
});
Vitor Piovezam
  • 445
  • 3
  • 10
0

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

Anupam Jagatdeo
  • 121
  • 1
  • 5
0

not sure if it will allow on every browser though

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

history.back = hackBackButton();
legrandmawak
  • 11
  • 1
  • 4