-1

I want to capture the page reload event using JavaScript and then redirect to a different URL (i.e. load the different page in the same browser tab) instead of the letting the existing page reload. My code is here -

<script type="text/javascript">
    window.onbeforeunload = function(e) {
        window.location = "https://www.google.com";
        e.preventDefault();
    };
</script>

The code gets executed when I right click in Chrome and then click reload but www.google.com does not load in the tab - instead the page reloads in the same tab.

What should be changed here?

lenniekid
  • 531
  • 1
  • 7
  • 16
  • _"What should be changed here?"_ - the idea. Why would you want to interfere with me reloading a page in my browser when I see fit? – CBroe May 17 '17 at 19:46
  • You can't redirect a page unload. This is something that adware used to do, to prevent you from getting rid of the popup ads. Browsers don't allow it any more. – Barmar May 17 '17 at 19:49
  • @CBroe, I am redirecting the user to the same page as in the tab but trying to append a token copied from a hidden tag on the page to the URL for security – lenniekid May 17 '17 at 19:49
  • @lenniekid This event happens when the user is trying to leave the page or close the window. Why do you want to redirect them back to the same page if they're trying to leave? – Barmar May 17 '17 at 19:50
  • @Barmar, I do not want to do this when the user wants to leave the page or close the window - I want to do this only when the user tries to reload the same page. This is part of a security mechanism to prevent CSRF attacks - where I generate a token from the server for each HTTP request and the next request sends it back to server. Alternatively, is there a way I can tell the server that this was just a page reload and it does not need to bother about tokens? – lenniekid May 17 '17 at 19:52
  • http://stackoverflow.com/questions/5004978/check-if-page-gets-reloaded-or-refreshed-in-javascript – Barmar May 17 '17 at 19:55
  • 1
    don't use a secret token in the URL, for security – Walle Cyril May 17 '17 at 20:12

1 Answers1

1

You can only do certain, things inside this event handler, mostly ask for confirmation, redirection is too late.

However you can redirect after the user confirms. Use .returnValue https://html.spec.whatwg.org/#the-beforeunloadevent-interface

Walle Cyril
  • 2,691
  • 2
  • 16
  • 46