kanayaki
kanayaki

Reputation:

Can I "redirect" user in onbeforeunload? If can't, how to?

Is it possible to redirect to another page when the user closes the browser?

Attempts:

  1. I tried onunload, does not work

    window.onunload = function redirect(){...}
    
  2. I also tried another method, it doesn't work either:

    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?? Maybe prompt to let user select whether to redirect to new page when he/she close the browser? I'm running out of ideas...

Upvotes: 11

Views: 23494

Answers (4)

kamui
kamui

Reputation: 3419

It's not without it's faults but it works

window.onbeforeunload = function(){
        window.open("http://www.google.com","newwindow");
        return "go to google instead?";
}

This will open a new window as a popup to the address you selected when the user closes the page, though it is limited by any popup blockers the browser may implement.

Upvotes: 3

Lee Kowalkowski
Lee Kowalkowski

Reputation: 11751

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.

Upvotes: 4

jimyi
jimyi

Reputation: 31201

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.

Upvotes: 0

karim79
karim79

Reputation: 342665

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?

Upvotes: 2

Related Questions