das
das

Reputation: 679

change URL of current page on reloading using javascript

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().

Upvotes: 3

Views: 4454

Answers (2)

Esteban Cervantes
Esteban Cervantes

Reputation: 313

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.

Upvotes: 3

parismiguel
parismiguel

Reputation: 616

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".

Upvotes: 1

Related Questions