简体   繁体   中英

Alert on exit the browser and closing the tab

I tried onbeforeunload as it requires once user-interaction to call, is there any way to call an event without user-interaction as the user exit the browser after it opens the application tab. Or Any other solution without using onbeforeunload that prevents the user to exit the browser.

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

        $(document).ready(function(){ 
            $(".label").click(function(){
            alert('label');
            window.onbeforeunload = null;
            }
            ); 
             $(".new_cont").click(function(){
            alert('new_cont');
            window.onbeforeunload = null;
            }
            );
        })

In both FireFox and Chrome you need at least one interaction with the page. Since this feature is to avoid losing data which was entered by the user, if no action happened on the page, then the user did not enter any data.

This is because the onbeforeunload is attached to the 's window object, and when you unload the main page, this event won't fire unless you had focus on this iframe.

 <script type="text/javascript">
 window.onbeforeunload = function () {
     return "Did you save your stuff?"
 }

For reference https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

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