Learn ASP.NET Core 2 and Angular 6 in October 2018. Instructor-led online courses by Bipin Joshi. Read more...
Instructor-led Online Courses by Bipin Joshi : ASP.NET Core | Angular | Design Patterns
Registration open for October 2018 batches. Read more 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 spiritual yoga mentor having 23+ years of experience in software development. He teaches private online courses in ASP.NET Core and Angular to 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.

He will be teaching ASP.NET Core 2.1 and Angular 6.1 in October 2018. Click here for his online course schedule and more details.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 26 April 2002


Tags : ASP.NET Web Forms JavaScript