how to identify onbeforeunload was caused by clicking close button

后端 未结 4 1317
囚心锁ツ
囚心锁ツ 2020-12-07 03:08

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:

4条回答
  •  离开以前
    2020-12-07 03:31

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

提交回复
热议问题