Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a requirement that I have to detect browser close as well as browser tab close.

If a user will click on browser close button or trying to close the tab then I should display a dialog box(has 2 button exit and cancel) that " do you really want to exit " if user clicks on exit then the save its worked data and close the browser.

Thanks

Prafulla
Posted
Comments
Volynsky Alex 22-May-13 7:48am    
If you want to detect when a tab/window is geting closed. You can do it ,for example on Javascript ,i.e. to detect that kind of stuff are onunload and onbeforeunload events.

Here :
http://eureka.ykyuen.info/2011/02/22/jquery-javascript-capture-the-browser-or-tab-closed-event/
you can see a simple example....
Volynsky Alex 22-May-13 7:53am    
See also this example:
http://www.codeproject.com/Tips/41771/How-to-detect-browser-close-when-browser-X-is-clic

Regards,
Alex.

Check the following link

Browser/tab close detection using javascript (or any other language)[^]

Here this should be either a javascript or an jquery. It's difficult(but I think there are some possible solutions) to detect on the server side. Bcoz while the time your request is processed , the user might already closed the tab. So to avoid that it is better to use javascript as it could detect the user activity easily.
 
Share this answer
 
v3
Follow the article - Save Changes on Close of Browser or When Exiting the Page[^].

You need to use window.onbeforeunload[^] event.

JavaScript
window.onbeforeunload = check;

function check() {
    var response = confirm("Are you sure you want to exit this page?";
    
    if(response == true)
    {
        // Do what ever you want to do. Call function to save data.
    }
}


Refer - Asp.net session on browser close[^] to know how it stores data on browser close by calling a web service.
 
Share this answer
 
Comments
Mahesh Bailwal 22-May-13 2:37am    
window.onbeforeunload event get fired every time page get unloaded. So if user will refresh the page or navigate to some other page this event will get fired, so must also handle these scenarios.
Oh nice information. And I believe there is no way to detect the particular browser close button click, isn't it ?

So, how to handle the scenario then ? Is there a way ?
Mahesh Bailwal 22-May-13 3:23am    
As per my knowledge you can detect it only by checking the mouse location where user clicked, whether its matching the close button location or not.
Moreover there is no full-proof way of detecting it.
Yes. That may be one way to do this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900