3

My requirement is to change the URL of the current page on clicking refresh icon or ctrl+R. That is on refresh, reload another page(different URL). And it should support all browsers. I have tried the below snippet. But its not working.

window.onbeforeunload = function(e) {
  window.location.href = 'www.google.com';
};

where 'google.com' should be the URL of my page on refreshing the current page. But it's nothappening with the window.onbeforeunload().

das
  • 669
  • 2
  • 12
  • 22

2 Answers2

3

OnBeforeUnload needs a return value to work, but actually, it will only display a message asking the user if he's sure that he wants to leave the page (just like Facebook does when you try to leave a page with some pending changes).

As far as I know, web browsers don't want to give you control over that, mainly due to websites redirecting users when they try to leave and stuff like that, so there's nothing like a "standard way" to do it and even if you find a workaround, I'm pretty sure that it will not work on all browsers. But why do your customer wants that behaviour on his website? At least in my opinion, the only thing that he will get with that is a horrible user experience for his end users.

1

As @Babydead states, this seems to be a duplicated:

Modify the URL without reloading the page

But, if you're looking for a quick solution, just try:

window.location.replace("http://www.google.com");

Don't forget to declare the protocol "http".

Community
  • 1
  • 1
parismiguel
  • 586
  • 6
  • 16
  • I tried this and it doesn't work. Not sure how this relates to the provided duplicate either as OP wants this to work on refresh. – adam-beck Sep 12 '16 at 19:12
  • My apologies I'd got you all wrong... Now I realize that what you really want to do is to overwrite the usual behavior of refresh, back and forward buttons.... I'm afraid that's not possible as it suppose a security breach for the user... However, we can hack our own development somehow... Here's an idea for a workaround: 1. Use of before unload is to perform some actions and then unload... So, what we can do is either set a global parameter or do nothing. 2. Use window.onload event to redirect to whenever you want using some conditional either reading a global parameter preset with window.bef – parismiguel Sep 13 '16 at 04:29