Catching a tab close event in web browser?

前端 未结 7 2343
我寻月下人不归
我寻月下人不归 2020-12-18 08:45

Is there any way of knowing if the user closes a tab in a web browser? Specifically IE7, but also FireFox and others as well. I would like to be able to handle this situatio

相关标签:
7条回答
  • 2020-12-18 09:40

    Santosh is right, this event will be triggered on many more actions than just clicking the close button of your tab/browser. I've created a little hack to prevent the onbeforeunload action to be triggered by adding the following function on document ready.

           $(function () {     
            window.onbeforeunload = OnBeforeUnload;
                $(window).data('beforeunload', window.onbeforeunload);
                $('body').delegate('a', 'hover', function (event) {
                    if (event.type === 'mouseenter' || event.type === "mouseover")
                        window.onbeforeunload = null;
                    else
                        window.onbeforeunload = $(window).data('beforeunload');
                });
            });
    

    Also, before you trigger any of the events mentioned by Santosh, you need to run this line:

    window.onbeforeunload = null;
    

    If you do not want the event to be triggered.

    And here's the final code piece:

        function OnBeforeUnload(oEvent) {   
                // return a string to show the warning message (not every browser will use this string in the dialog)
                // or run the code you need when the user closes your page  
            return "Are you sure you want to close this window?";       
        }
    
    0 讨论(0)
提交回复
热议问题