Load page unload event only when tab / window is closed

I want to show alert only on closed tab / window.

Right now I have done something like below, but it fires even on the "F5" button, back in the browser ... but I want it to be closed in the tab / windows.

I tried so much on this and also checked so many stackoverflow links but didn't get any solution

window.onbeforeunload = function(e) {
                return confirmExit()
            }
            function confirmExit() {
                //my logic
                return false;
            }

      

also added the following code to prevent onbeforeunload when clicking any link on my site

$(document).ready(function() {
                $('a[rel!=ext]').click(function() {
                    window.onbeforeunload = null;
                });
                $('form').submit(function() {
                    window.onbeforeunload = null;
                });
            });

      

please help me.

+3


source to share


1 answer


For security reasons this is not the case or should not be possible. To deterministically know when and how the user interacts with the User Agent (browser), you (must) have access to the higher security context of the browser. Page scripts are expected to be blocked using this access.

You will know when the page is unloaded (events onbeforeunload

and onunload

), but not an explicit reason for the page unloading.



Note that you can and should handle this event through window.addEventListener()

and event beforeunload

. Using window.onbeforeunload

and window.onunload

instead is window.addEventListener()

much more restrictive and prevents you from exchanging events with other scripts that might be loaded, and not just deleting your own event handler. You should be in the habit of using a window.addEventListener()

named function as well to play well in an environment where you are not limited to only script running on your site.

+1


source







All Articles