简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM