JavaScript before leaving the page
javascript, jquery
Solution
`onunload` (or `onbeforeunload`) cannot redirect the user to another page. This is for security reasons.
If you want to show a prompt before the user leaves the page, use `onbeforeunload`:
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.
You can use `onunload` to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside `onunload`):
window.onunload = function() {
alert('Bye.');
}
Or with jQuery:
$(window).unload(function(){
alert('Bye.');
});
Problem
I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload ``` <script type="text/javascript"> function con() { var answer = confirm("do you want to check our other products") if (answer){ alert("bye"); } else{ window.location = "http://www.example.com"; } } </script> </head> <body onunload="con();"> <h1 style="text-align:center">main page</h1> </body> </html> ``` But it confirm after page already closed? How to do it properly? It would be even better if someone shows how to do it with jQuery?