Reputation: 2551
From out of curiosity can i Control window.onbeforeunload event like check if the user decided to leave the page or stay in it and can I raise an alert or some function based on his decision if yes 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 give the user a message to tell him that maybe you forget to do something before you leave but this quest is just out of curiosity and thank you
Upvotes: 1
Views: 2909
Reputation: 101
Put a timer of one second. Clear it on unload. Should work, but didn't test 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?';
});
Upvotes: 0
Reputation: 1722
You can ONLY return a string which will show 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>
Upvotes: 1
Reputation: 16190
You cannot get the result of onbeforeunload
. Also, even if you somehow managed to figure out a way to get the result, you wouldn't be able to raise an alert. You could probably run another function.
Upvotes: 0