How to detect page closure using ASP.NET

I have an ASP.NET web application with a MasterPage page and content from MasterPage when I press MenuItem to open a new aspx page. if I want to close the browser tab of a new page, I want to show a pop-up window or dialog warning the user that he is closing the browser tab. I do not know how to define the close browserTab button. I used the following code on a new aspx page:

 <script type="text/javascript"> function CloseWindow() { alert('closing'); window.close(); } </script> 

new page code:

 protected void Page_Load(object sender, EventArgs e) { Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();"); } 

Thanx in Advantage.

+7
source share
5 answers

This works great.

javascript detect browser close tab / close browser

 <body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()"> var myclose = false; function ConfirmClose() { if (event.clientY < 0) { event.returnValue = 'You have closed the browser. Do you want to logout from your application?'; setTimeout('myclose=false',10); myclose=true; } } function HandleOnClose() { if (myclose==true) { //the url of your logout page which invalidate session on logout location.replace('/contextpath/j_spring_security_logout') ; } } 
+3
source

I had a lot of problems with this, and the only thing that works: the "window.onbeforeunload" event from javascripts, but the problem is that it runs much more than what you expect. So if you are working with the main page, etc., I do not think that this can be done.

I think it’s best to try to approach this differently, because otherwise your closing message will often appear.

+1
source

You can handle this with javascript on your page.
First create a function:

 function closeMessage() { return "Are you sure you want to leave this page"; } 

After that, assign this method:

 window.onbeforeunload = closeMessage; 

Please let me know if it was helpful.

0
source

You need to catch the event to close the browser and use it to do whatever you want. Here is the code that worked for me.

  <script type="text/javascript"> window.onbeforeunload = function (e) { var e = e || window.event; if (e) e.returnValue = 'Browser is being closed, is it okay?';//for IE & Firefox return 'Browser is being closed, is it okay?';// for Safari and Chrome }; </script> 

Hope this helps.

0
source

If you understand correctly, you want to know when the tab / window closes effectively. Well, afaik is your only way in Javascript to detect things like onunload and onbeforeunload events. These events are also triggered when you leave the site using the link or browser button. So this is the best answer I can give, I don’t think you can detect a clean closure in Javascript. Correct me if I am wrong here. You can go through browser-tab-close-detection-using-javascript-or-any-other-language

0
source

All Articles