简体   繁体   中英

Browser/tab close detection using javascript (or any other language)

I searched for this question in various places, but all that they mention is the use of javascript & . Also it doesn't work in chrome most of the times as it gets blocked.
Then how does google manage to do it. If we are composing a mail and by mistake close the tab, google prompts us by a "Are you sure?" box.
Can somebody help me out?

I tested and the example posted on MDN works clearly in Chrome.

<script>
    window.onbeforeunload = function (e) {
        e = e || window.event;

        // For IE and Firefox prior to version 4
        if (e) {
            e.returnValue = 'Any string';
        }

        // For Safari
        return 'Any string';
    };

    function formSubmit() {
      window.onbeforeunload = null; 
   }
</script>

...

   <form onsubmit="formSubmit()">...</form>

This way a dialog opens that will not be blocked by a popup blocker as it is originated from a user click.

If you only want to ask a user if they want to leave the page when they've changed anything in the forms on the page, have a look at PageHasFormChanges . Keep in mind that I developed it for use it on very simple pages, with only one or two forms.

PageHasFormChanges : A jQuery plugin to check if anything has changed in any form on a page, and warn the user before leaving the page.

You don't need to do anything, but load the script on your page. You can change the defaults though:

JoelPurra.PageHasFormChanges.setOptions({
    leavingPageWarningMessage: "Are you sure?"
});

If you're using ajax to submit your forms, you could consider setting resetWarningOnPreventedSubmit to true .

you can use the jquery unload function:

$(window).unload(function() {
  alert('Handler for .unload() called.');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM