January 2018 : Instructor-led Online Course in ASP.NET Core 2.0. Conducted by Bipin Joshi. Read more...
Registration for January 2018 batch of ASP.NET Core 2.0 instructor-led online course has already started. Conducted by Bipin Joshi. Register today ! Click here for more details.

<%@ Page %>

HOW TO: Close Browser Window From Button Web Control

Introduction

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
   Response.Write("<script>window.close();</script>")
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 a software consultant, an author and a yoga mentor having 22+ years of experience in software development. He also conducts online courses in ASP.NET MVC / Core and Design Patterns. 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 Meditation and Mindfulness to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 26 April 2002


Tags : ASP.NET Web Forms JavaScript