Home > database >  Alert on exit the browser and closing the tab
Alert on exit the browser and closing the tab

Time:10-07

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;
            }
            );
        })

CodePudding user response:

In both FireFox and Chrome you need at least one interaction with the page. Since this feature is to avoid loosing data which entered by user, if no action happened on the page means ,user does 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

  • Related