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.
+1
source to share
3 answers
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>
+1
source to share
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?';
});
0
source to share