<%@ Page %>

HOW TO: Close Browser Window From Button Web Control


Generally we want to perform tasks like closing browser window from client side JavaScript itself. However, there might be cases when we should perform some another processing - may be logging or usage tracking - when user explicitly closes the application. This How To will tell you how to code server side Button click event that also closes browser window.

Creating web form

There will not be anything special in the way to design your web form. For this example I assume that you have a web form called WebForm1.aspx. Put a button web control on the form with ID as button1.

Code that closes the window

In the click event handler of button1 write following code:
Private Sub Button1_Click
(ByVal sender As System.Object, ByVal e As System.EventArgs) 
Handles Button1.Click
   ' perform other server side tasks here
End Sub
Here, we have emitted the familiar JavaScript script block that closes the window. When you run this page and click on button1, the browser window will be closed.

Why not use Attributes collection?

Many of you might be thinking that instead of emitting such 'raw' script why not use Attributes of button control to add client side JavaScript code (see below).
Private Sub Page_Load
(ByVal sender As System.Object, ByVal e As System.EventArgs) 
Handles MyBase.Load
        Button1.Attributes.Add("OnClick", "window.close();")
End Sub
This will not work in our case because JavaScript code added via Attributes collection runs first and then server side processing starts. So, in our case first the browser window will be closed and server side event will be not fire. Our solution do not have this problem because first the server side event will be handled and then the JavaScript is emitted.

Bipin Joshi is an independent software consultant, trainer, author, and meditation teacher. He has been programming, meditating, and teaching for 25+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 26 April 2002

Tags : ASP.NET Web Forms JavaScript