Online courses in ASP.NET MVC, ASP.NET Core, and Design Patterns conducted by Bipin Joshi. Read more...
Learn ASP.NET MVC, ASP.NET Core, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

<%@ 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, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 26 Apr 2002



Tags : ASP.NET Web Forms JavaScript