1

Is there a way to redirect the window or tab when a user closes it? This does not work (in jQuery):

$(window).bind('beforeunload', function() { window.location = 'anotherpage.html' } 

Is it even possible? I just want to redirect a user to another page when they close it.

2
  • If they've closed the tab/window, why do you want to redirect? The window is about to be gone. Commented Jul 31, 2011 at 4:54
  • i just want to make sure they finish some actions on the site, but some people will not want to and close the window improperly. i want to redirect them instead. i suppose it may not be possible and i'll just have to thrown an alert instead for them to finish their actions. Commented Jul 31, 2011 at 4:56

2 Answers 2

5

No, the only thing you can do is alert the user they are about to close your page and ask them if they would like to remain or confirm to leave.

This is very common on pages which require you to save before exiting, like an online exam or survey for example.

 window.onbeforeunload = confirmExit; function confirmExit() { return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?"; } 
Sign up to request clarification or add additional context in comments.

Comments

0

You can't go to a new web page, but if what needs doing is some housecleaning (such as issuing an ajax call to your server, clearing some cookies, whatever), you can just do that on the onbeforeunload handler directly without prompting the user, without redirecting.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.