Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect which close button the user has pressed with multiple tabs

I have found many code to detect the close button of the browsers but I got event when calling close tab. I just want to get the main close button event to alert the user to stay in this page or not. I found this code.

<script type="text/javascript"> 
window.onbeforeunload = function (evt){
    var message = 'Are you sure you want to leave?'; 
    if (typeof evt == 'undefined') { 
        evt = window.event; 
    } 
    if (evt) { 
        evt.returnValue = message; 
    } return message;  
   } 
</script>

It alerts users to close or to stay while clicking the tab close.

Now, I want to detect the main browser close event. As found close event is used for tab close too.

Can anyone help me in this problem?

like image 366
Subhod30 Avatar asked Oct 21 '25 20:10

Subhod30


1 Answers

Browsers vs. pages:

Browser level events are not available directly to the page level JavaScript. Some events have equivalents from the browser to the page and some don't. This is due to security concerns.

Closing the tab of a browser is a browser level event. The page is notified that an unload event is taking place. The page doesn't know if we're experiencing a "refresh", or a "navigate to another link" or if the tab has been closed, or if the entire browser has been closed or if some browser plugin has crashed.

Also the page unload event doesn't know if there are any more open windows / tabs at the moment of unload. Some browsers might not even have the notion of tabs (or windows for that matter). So browser level events are the concern of browser developers and plugin developers. Page level events are your concern.

Page events:

Click events can be caught and the default (page navigation) behavior can be suppressed and replaced with something entirely different.

Most unload events howerver are restricted they don't allow you to replace the default behavior, they only allow you to ask the user if he wants to leave or stay via a confirmation dialog (with some configurable title/text but no html in it). If the user refuses you no-longer have control over that page -- done, finitto, the tab is closed.

If you want to make sure the user isn't going anywhere via navigation links or submitting forms then you need to catch each of those respective events. Closing tabs and windows is not your problem.

like image 66
Mihai Stancu Avatar answered Oct 24 '25 10:10

Mihai Stancu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!