Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

javascript - how to identify onbeforeunload was caused by clicking close button

How do I determine 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...