Control window.
Out of curiosity, I can control the window.onbeforeunload event, for example, check if the user decided to leave the page or stay in it, and if I can raise an alert or some function based on his solution, if so please tell me
<script type="text/javascript">
$(window).bind("beforeunload",function(){
if(//stay on page)
alert("i want to stay on the page");
else //leave page
alert("i want to leave the page");
});
</script>
I understand that window.onbeforeunload is an event that gives the user a message to inform him that maybe you forgot to do something before leaving, but this quest is just out of curiosity and thanks.
You cannot get the result onbeforeunload
. Also, even if you somehow managed to find a way to get the result, you would not be able to raise the warning. Perhaps you can run another function.
Now, methods
showModalDialog()
,alert()
,confirm()
andprompt()
allow nothing to do duringpagehide
, and .beforeunload
unload
You can ONLY return a string that displays a dialog confirmation displaying the string you returned (but with additional ok / cancel buttons to confirm the action).
<script type="text/javascript">
$(window).bind("beforeunload",function(){
return 'Are you sure you want to leave this page?';
});
</script>
Set a timer for one second. Clean it when unloading. Should work, but haven't tested it.
window.addEventListener('beforeunload', function (event) {
var timeId = setTimeout(yourFunctionIfTheUserStays, 1000);
window.addEventListener('unload', function (event) {
clearTimeout(timeId);
})
return 'Are you sure you want to leave this page?';
});