Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...