16

I want to disallow the visitor go back in browser, I tried the code here (How to disable back button in browser using javascript) and works well, but I want to make somenthing more useful for my application. I want to change the back url.

So, if the back URL is mywebsite.com/admin/add_new_article.php I want to change the back URL to mywebsite.com/admin/index.php

Thank you all!

Community
  • 1
  • 1
MM PP
  • 4,050
  • 9
  • 35
  • 61
  • 3
    Why? And I'm fairly certain that this isn't possible either, and shouldn't be. Let's consider this, a user visits the site, unsuspecting and innocent, he sees that the site he visited is "bad" and wants to go back to his google search, WHAM, the user is now on a infected site and so is his computer now. – Epodax May 29 '15 at 10:10
  • Ok, I understand. Thank you for your response. – MM PP May 29 '15 at 10:17
  • I think that this would be very useful for PWAs: please [vote this feature request on WICG](https://discourse.wicg.io/t/set-back-button-url-in-pwas/4112). Despite the comments, it can also be developed in a secure way to prevent abuses. This feature is needed to align PWA capabilities to native apps! – collimarco May 31 '20 at 18:34
  • @Epodax scenario: if a mobile viewer visits page A, he gets redirected to the mobile version of page A. So if he presses back he will be going back to page A desktop version instead of the actual page he came from and be directed again to page A mobile. Endless loop. Viewer cannot go back to where he came from. – larry909 Jan 26 '22 at 10:20

1 Answers1

18
<script type="text/javascript">
history.pushState(null, null, '<?php echo $_SERVER["REQUEST_URI"]; ?>');
window.addEventListener('popstate', function(event) {
    window.location.assign("http://www.yoururl.com/");
});
</script>

Hope it helps!

  • 1
    It doesn't seem to work on chrome for iPhone, anything I can try to fix this ? works ok in mozilla and chrome on desktop, safari on iphone too. – adrianTNT Feb 15 '17 at 11:09
  • 2
    `assign` is not working so used `window.location.href="http://www.yoururl.com/";` – Moumit Apr 25 '17 at 10:35
  • Well this seems to work after testing. I saw huffpost actually do this on one of their webpages making the backbutton lead to their home page and wanted to know how they did it. So ty. – Michael d May 30 '19 at 16:53
  • 1
    NOTE: This will also react on `href="#page-fragment"` URLs, which are in general only supposed to jump somewhere on the page. So make an exception here if needed – Hrvoje Golcic May 20 '21 at 09:30