I’m using some function with jQuery, for example:
$(window).one('beforeunload', function() {
//my code
});
But I really want to find out all about what has triggered this event and how.
I tried the following code:
$(window).one('beforeunload', function(e) {
alert(JSON.stringify(e));
});
But it raises exception about circular structure. Definitely though there must be some other way of differentiating and debugging through it.
How am I going to apply it?
I want to see what triggered this event, was it a link, a submitted form, a javascript, a page refresh, or a back and forth buttons or whatever, and it’s all fine in that case. BUT if it was triggered by a call to open an external application, I want to discard the event and return null.
Example of external application launch:
<a href="skype:your_skype_name?call" >
Any ideas?
SOLVED
This is how I solved it.
I just make some script link first, to gain more control over the event:
<a href="javascript:void(0)" id="skype_click_ok"
Then I create a global variable to store the state of beforeunload:
var dontunload=0;
Then I manually process the link, but setting location.href, and changing variable state:
$('#skype_click_ok').click(function(){
dontunload=1;
location.href='skype:marilynbrusas?call';
});
Now my actual beforeunload event, note the one() was also changed to bind():
$(window).bind('beforeunload', function() {
if (dontunload==1) dontunload=0; //if triggered from our skype - do nothing, yet cancel state for the next call
else { //Do the actual code
// Fade out, before leaving the page.
$('html#my_html').stop(true,false).css('overflow','hidden').animate({opacity:0},2000);
// Lock content with invalid image hack
$('body#my_body').prepend(
$('<div>').attr({style:'position:fixed;height:100%;width:100%;left:0;top:0;z-index:900100;background-image:url(in-your-face)'})
);
// unbind the event
$(this).unbind('beforeunload');
}
});
EDIT3
Actually it’s not solved. This trick does not work in IE and also the even triggers from javascript:void(0) links…
Using
alertto display objects like events is fairly useless.Why don’t you try sending you event to the console?
This way you can expand you event object and view it in a a tree like structure.
EDIT As per you comments about the location of the event trigger: I haven’t testing this, but this could be a way of stopping your unload event.
aelementsbeforeunloadthat cancels the event immediatelyOtherwise unbind the previous handler
Notice that this example is using something call Event Namespacing. By specifying that we want to listen to the
beforeunloadevent, but we have our own namespace calledoverride, we can add and remove the event handler safely without removing all other listeners for thebeforeunloadevent.