1

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;
            }
            );
        })
  • Does this answer your question? [Detect browser or tab closing](https://stackoverflow.com/questions/3888902/detect-browser-or-tab-closing) – Izzy Oct 05 '21 at 09:27

1 Answers1

2

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

Phantom Watson
  • 2,667
  • 4
  • 25
  • 39
aadi
  • 59
  • 5