Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

dom events - 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 window.unload and window.onbeforeunload. 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?

What actually I want to do is to ask confirmation of the user, when he is filling in the form and by mistake clicks on tab close. If yes, I allow him to navigate away else he stays on the page & continues to fill his form.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...