Display a warning when leaving the site, not just the page

前端 未结 7 821
旧时难觅i
旧时难觅i 2020-12-05 20:55

This sounded like something almost impossible to do when it was presented to me. I know you can display a dialog box to confirm when leaving a web page. But is it possible t

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 21:24

    Your best bet is listening on the non-standard beforeunload event. This is supported by almost all browsers, expect of Opera which is known to adhere the W3C standards extremely strictly.

    Kickoff example:

    window.onbeforeunload = function() {
        return "You're leaving the site.";
    };
    

    This message will show up in kind of a confirmation dialogue.

    In your specific case you need to turn it off (just set to null) whenever a navigational link is clicked or an internal form is submitted. You can do that by listening on the click event of the desired links and the submit event of the desired forms. jQuery may be of great help here:

    window.onbeforeunload = function() {
        return "You're leaving the site.";
    };
    $(document).ready(function() {
        $('a[rel!=ext]').click(function() { window.onbeforeunload = null; });
        $('form').submit(function() { window.onbeforeunload = null; });
    });
    

    You only need to give all external links the defacto standard attribute rel="ext" to denote that those are external links.

    Google
    

提交回复
热议问题