[c#] Programmatically close aspx page from code behind

What is the best way to close an ASPX page from the code-behind?

I have a button event handler that I want to close the page after the user has clicked an ASP.NET button on the page. I have tried to programmatically add a JavaScript method that contains a window.close() command to the OnClientClick event to close the page but it does not work. The button is also a asp:AsyncPostBoskTrigger for an AJAX Update Panel.

The application uses .NET Framework 3.5.

This question is related to c# asp.net

The answer is


 protected void btnOK_Click(object sender, EventArgs e)
        {

          // Your code goes here.
          if(isSuccess)
          {
                  string  close =    @"<script type='text/javascript'>
                                window.returnValue = true;
                                window.close();
                                </script>";
            base.Response.Write(close);
            }

        }

You can close a window by simply pasting the window closing code in the button's OnClientClick event in the markup


You should inject a startup script that will close the page after the postback has finished.

ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>"); 

  protected void Button1_Click(object sender, EventArgs e)
  {
    Button1.Attributes.Add("onclick"," CloseWindow();");
  }

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

For anyone wondering why they cannot get the provided answers to work it's because the page must have been opened by javascript in order to be closed by javascript.

Since most people finding this asp question are likely using an asp:hyperlink or an asp redirect of some sort to navigate to the page that needs to be closed. These methods of redirection don't use javascript and therefore will not close by javascript.

I found a simple solution for my application and that's eliminating the NavigateUrl and using the asp:Hyperlink.Attributes to add an onclick to the hyperlink which uses java script to open the window that needs to be closed by javascript.

aspHyperlink.NavigateUrl = "https://www.google.com";

The above NavigateUrl is removed and instead we attach our click event.

aspHyperlink.Attributes.Add("onclick", "javascript:openInNewTab('https://www.google.com');");

And in the code behind of the page containing our aspHyperlink we have the javascript for opening the url provided by Rinto

function openInNewTab(url) {
         var win = window.open(url, '_blank');
         win.focus();
     } 

Now all pages opened with openInNewTab can be closed with the provided answers.

window.close();

If you using RadAjaxManager then here is the code which helps:

RadAjaxManager1.ResponseScripts.Add("window.opener.location.href = '../CaseManagement/LCCase.aspx?" + caseId + "'; 
window.close();");

You can close a window by simply pasting the window closing code in the button's OnClientClick event in the markup


You can just simply use this.. short and easy.

Response.Write("<script>window.close();</script>");

Hope this helps.


For closing a asp.net windows application,

  • Just drag a button into the design page
  • Then write the below given code inside its click event

           "   this.close();  "
    

ie:

 private void button2_Click(object sender, EventArgs e)  
 {
        this.Close();
 }

You should inject a startup script that will close the page after the postback has finished.

ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>"); 

if you are opening page on JavaScript popup then

 Response.Write("<script>javascript:window.close();</script>");

will do the job


You just need to add this property in your asp:Button element (for example):

OnClientClick="javascript:window.close();"

It works perfectly.


For anyone wondering why they cannot get the provided answers to work it's because the page must have been opened by javascript in order to be closed by javascript.

Since most people finding this asp question are likely using an asp:hyperlink or an asp redirect of some sort to navigate to the page that needs to be closed. These methods of redirection don't use javascript and therefore will not close by javascript.

I found a simple solution for my application and that's eliminating the NavigateUrl and using the asp:Hyperlink.Attributes to add an onclick to the hyperlink which uses java script to open the window that needs to be closed by javascript.

aspHyperlink.NavigateUrl = "https://www.google.com";

The above NavigateUrl is removed and instead we attach our click event.

aspHyperlink.Attributes.Add("onclick", "javascript:openInNewTab('https://www.google.com');");

And in the code behind of the page containing our aspHyperlink we have the javascript for opening the url provided by Rinto

function openInNewTab(url) {
         var win = window.open(url, '_blank');
         win.focus();
     } 

Now all pages opened with openInNewTab can be closed with the provided answers.

window.close();

If you using RadAjaxManager then here is the code which helps:

RadAjaxManager1.ResponseScripts.Add("window.opener.location.href = '../CaseManagement/LCCase.aspx?" + caseId + "'; 
window.close();");

  protected void Button1_Click(object sender, EventArgs e)
  {
    Button1.Attributes.Add("onclick"," CloseWindow();");
  }

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

You would typically do something like:

protected void btnClose_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}

However, keep in mind that different things will happen in different scenerios. Firefox won't let you close a window that wasn't opened by you (opened with window.open()).

IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.

In any case, you should be prepared to deal with the window not always closing!

One fix for the 2 above issues is to use:

protected void btnClose_Click(object sender, EventArgs e) {
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}

And create a close.html:

<html><head>
 <title></title>
 <script language="javascript" type="text/javascript">
     var redirectTimerId = 0;
     function closeWindow()
     {
         window.opener = top;
         redirectTimerId = window.setTimeout('redirect()', 2000);
         window.close(); 
     }

     function stopRedirect()
     {
         window.clearTimeout(redirectTimerId);
     }

     function redirect()
     {
         window.location = 'default.aspx';
     }
 </script>
 </head>
 <body onload="closeWindow()" onunload="stopRedirect()" style="">
     <center><h1>Please Wait...</h1></center>
 </body></html>

Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.


if you are opening page on JavaScript popup then

 Response.Write("<script>javascript:window.close();</script>");

will do the job


You can close a window by simply pasting the window closing code in the button's OnClientClick event in the markup


You should inject a startup script that will close the page after the postback has finished.

ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>"); 

You would typically do something like:

protected void btnClose_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}

However, keep in mind that different things will happen in different scenerios. Firefox won't let you close a window that wasn't opened by you (opened with window.open()).

IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.

In any case, you should be prepared to deal with the window not always closing!

One fix for the 2 above issues is to use:

protected void btnClose_Click(object sender, EventArgs e) {
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}

And create a close.html:

<html><head>
 <title></title>
 <script language="javascript" type="text/javascript">
     var redirectTimerId = 0;
     function closeWindow()
     {
         window.opener = top;
         redirectTimerId = window.setTimeout('redirect()', 2000);
         window.close(); 
     }

     function stopRedirect()
     {
         window.clearTimeout(redirectTimerId);
     }

     function redirect()
     {
         window.location = 'default.aspx';
     }
 </script>
 </head>
 <body onload="closeWindow()" onunload="stopRedirect()" style="">
     <center><h1>Please Wait...</h1></center>
 </body></html>

Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.


A postback is the process of re-loading a page, so if you want the page to close after the postback then you need to set your window.close() javascript to run with the browser's onload event during that postback, normally done using the ClientScript.RegisterStartupScript() function.

But are you sure this is what you want to do? Closing pages tends to piss off users.


You would typically do something like:

protected void btnClose_Click(object sender, EventArgs e)
{
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}

However, keep in mind that different things will happen in different scenerios. Firefox won't let you close a window that wasn't opened by you (opened with window.open()).

IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.

In any case, you should be prepared to deal with the window not always closing!

One fix for the 2 above issues is to use:

protected void btnClose_Click(object sender, EventArgs e) {
    ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}

And create a close.html:

<html><head>
 <title></title>
 <script language="javascript" type="text/javascript">
     var redirectTimerId = 0;
     function closeWindow()
     {
         window.opener = top;
         redirectTimerId = window.setTimeout('redirect()', 2000);
         window.close(); 
     }

     function stopRedirect()
     {
         window.clearTimeout(redirectTimerId);
     }

     function redirect()
     {
         window.location = 'default.aspx';
     }
 </script>
 </head>
 <body onload="closeWindow()" onunload="stopRedirect()" style="">
     <center><h1>Please Wait...</h1></center>
 </body></html>

Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.


A postback is the process of re-loading a page, so if you want the page to close after the postback then you need to set your window.close() javascript to run with the browser's onload event during that postback, normally done using the ClientScript.RegisterStartupScript() function.

But are you sure this is what you want to do? Closing pages tends to piss off users.


 protected void btnOK_Click(object sender, EventArgs e)
        {

          // Your code goes here.
          if(isSuccess)
          {
                  string  close =    @"<script type='text/javascript'>
                                window.returnValue = true;
                                window.close();
                                </script>";
            base.Response.Write(close);
            }

        }

You can close a window by simply pasting the window closing code in the button's OnClientClick event in the markup


You just need to add this property in your asp:Button element (for example):

OnClientClick="javascript:window.close();"

It works perfectly.


A postback is the process of re-loading a page, so if you want the page to close after the postback then you need to set your window.close() javascript to run with the browser's onload event during that postback, normally done using the ClientScript.RegisterStartupScript() function.

But are you sure this is what you want to do? Closing pages tends to piss off users.


For closing a asp.net windows application,

  • Just drag a button into the design page
  • Then write the below given code inside its click event

           "   this.close();  "
    

ie:

 private void button2_Click(object sender, EventArgs e)  
 {
        this.Close();
 }

You should inject a startup script that will close the page after the postback has finished.

ClientScript.RegisterStartupScript(typeof(Page), "closePage", "<script type='text/JavaScript'>window.close();</script>"); 

You can just simply use this.. short and easy.

Response.Write("<script>window.close();</script>");

Hope this helps.