63

When the user loads the page, I immediately do a window redirect to another location.

The problem is, when the user clicks back, it'll go back to the page which does the redirect.

Can I "cancel" the history of the previous page? So that when the user clicks back, it goes back TWO pages instead?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

3 Answers3

112

Instead of using window.location = url; to redirect,

try:

window.location.replace(url);

after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

john-jones
  • 7,490
  • 18
  • 53
  • 86
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • This works for pages I have control over loading, but how about for instances where you want to clear all previous browsing (different sites)? I'm lazy and don't want handle exiting web app intentionally or on purpose using back button. – Roy Hinkley Oct 30 '14 at 15:19
  • Is there a way to do this without loading the defined new page? – user1063287 Aug 22 '18 at 10:05
  • Worked like charm for me – Ashish_B Mar 15 '19 at 09:27
9

You can use location.replace to replace the current location entry (the redirect page) with the new one (the target). That requires that you do the redirection via JavaScript rather than with meta tags or a 302. E.g.:

// In the redirecting page
location.replace("path/to/target/page");

Live example | Live example source

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
4

For anyone coming across this page and looking for an AngularJS way to accomplish this (rather than javascript), use the $location service's replace() method (documentation) :

Use $location.url('/newpath'); or $location.path('/newpath'); as you normally would to do the redirection in angular. And then just add $location.replace(); right after it. Or you can chain the commands like this:

$location.url('/newpath').replace();
Rebecca
  • 1,064
  • 13
  • 12