I want to execute an action method when the user is abandoning a particular page using jQuery.
The page has the following code:
as bhelm said
beforeunload
works for me as well.
return false on this event will invoke the browser default
are you sure you want to leave this page?
$(window).on('beforeunload', function ()
{
return false;
});
In many projects of mine, the mentioned methods here are instable. The only thing that works for me is to bind the event as original attribute on the body element.
<body onunload="my_function_unload()">
jQuery method:
$('body').attr('onunload', 'my_function_unload()');
From an iframe:
<body onunload="window.parent.my_function_unload()">
jQuery method:
$('<iframe />').load(function(){
$body = $(this).contents().find('body');
$body.attr('onunload', 'window.parent.my_function_unload()');
}
Also, important, no arguments in the attribute, and the function must be in the global window scope, otherwise nothing happens.
For example, common mistake If your my_function_unload()
are wrapped inside a ;( function( $ ) {...
OR $(document).ready(function(){...
AS my_function_unload()
must be outside that private scope. And dont forget to use jQuery
instead of $
prefix then.
jquery .on('unload',..); was not reliable working for me. i switched over to use beforeunload. just make sure you are not returning anything, or the user will get a "are you sure to leave the page"-popup.
<script type='text/javascript'>
$(window).on('beforeunload', function(){
console.log("beforeUnload event!");
});
</script>
Actually some browsers such as Google Chrome might block if you attempt to alert
in a window unload
. As a user I like this feature. Alerting everytime you try to navigate away from a page sucks:
Replace the alert with a console.log
or something else less intrusive to the user and the event will be happily called.
You might also want to checkout the onbeforeunload event.
if you want to alert user that you leaving this page then if this
/* $(window).unload(function()
{
//alert("you leaving this page");
console.log("you leaving this page");
}); */
function not work for you then replace your code with on("beforeunload",function) like this
$(window).on("beforeunload", function()
{
alert("you leaving this page");
console.log("you leaving this page");
});
this work for me ! you can see the output in console log you leaving this page
window.onbeforeunload=navigationError;
var dont_confirm_leave = 0; var leave_message = 'You sure you want to leave?';
function navigationError(e)
{
if(dont_confirm_leave!==1)
{
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = leave_message;
//e.stopPropagation works in Firefox.
if (e.stopPropagation)
{
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
return leave_message;
}
}