开发者

how to identify onbeforeunload was caused by clicking close button

How do I determine 开发者_JAVA技巧if onbeforeunload was caused by clicking the close button or a page refresh or generally what event caused onbeforeunload?

here is a snippet:

window.onbeforeunload = function( e ){
    if( !e ) e = window.event;

    // insert code to determine which is the source of the event
}

Please help me.


Referring to various articles and doing some trial and errors, finally developed this idea which works perfectly for me just the way i wanted it to happen. The logic was quiet simpler it implement as well The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the Close('X') button.

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));


$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));

function ConfirmLeave() {
    return "";
}

The ConfirmLeave function will give the pop up default message, it case there is any need to customize the message, return the text to be displayed instead of empty string

See if this helps, :)


As far as I know, there is no way of determining what caused the onbeforeunload. The event is triggered when window is about to close whether closing the browser or some other way.


If the close button was pressed the value of e.clientY is negative. For the other possible sources i doubt there is a solution.

window.onbeforeunload = function() {
   var e = window.event;
   alert(e.clientX + " / " + e.clientY);
}


I searched for something similar but ended up empty handed. So I tried doing the opposit

We can identify all the events but browser events. Refer below (Untested) snippet.

var target = $( e.target );
if(!target.is("a, :button, :submit, :input, .btn, .bulkFormButton")){
//Your code for browser events)
}
   $("form").submit(function () {
             //Your code for browser events)
   });

This worked for me but there are still some events that are not handled. I am in search of those. If anyone have idea about them please share.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜