views:

1097

answers:

4

Is it possible to redirect to another page when userclose browser?

Attempts:

  1. I tried onunload, does not work

    window.onunload = function redirect(){...}
    
  2. I also tried another method, it does not work as well:

    window.onbeforeunload = redirect(){...}
    
  3. <body onbeforeunload="return false; redirecty()">

The 3rd method, i want to cancel the onbeforeunload (means delay closing the browser), the I call the redirect function, window.confirm, if yes redirect, if no then close the browser. But it does not work as well.

Is there any other way?? Run out of ideas...

-- Prompt to let user select whether to redirect to new page when he/she close the browser --

This is the first time, I could not get best answer in stackoverflow :(

+1  A: 

If the user is trying to close the browser, then his intentions are pretty clear; he expects that the browser will close. Preventing that from happening, or causing anything else to happen in between the user clicking on 'close' and the browser closing is just a bad idea IMO. Is there a special reason for this? I mean, when I click on the 'close' button I expect that the browser will close, and should anything else happen, I would find that extremely annoying. I think I'm being reasonable enough. Am I? Who knows such things.

Why don't you try to entice the user to visit the other page in a less intrusive way? Like with a link or a banner?

karim79
A: 

The simple answer is no. If browsers allowed you to do more with the onbeforeunload/onunload events, this could be used pretty maliciously by anybody.

jimyi
The answer is yes. it just we donnu how to do.
+1  A: 

Your onbeforeunload event needs to return a string (that doesn't equate to false), the browser will include this string in its own message displayed to the user.

window.onbeforeunload = function(){
     location.assign('http://www.google.com');
     return "go to google instead?";
    }

However, it's going to be really tricky to word your message in a way that the user would be able to understand what to do. And I'm not sure this is robust in every browser, I just tried it in Chrome, it worked, but I ended up with a tab I could not close! I managed to kill it via the Chrome task manager thankfully.

Lee Kowalkowski
A: 
window.onbeforeunload = confirmExit; function confirmExit() { location.assign('http://www.google.com'); return " ***************************************\n\nWAIT!!! \n\n DONT GO AWAT I HAVE A SPECIAL GIFT FOR YOU \n\n ***************************************"; }

ITS my code, the \n\n is intro and you can replace * with ----

I have a question if I need to redirect 2 times how can I do?

Frank