Reputation: 25260
What is the best way to close a browser window of an AJAX ASP.NET application after the server-side has been executed.
I found this solution, but it seems a little complex for what I want to accomplish. Or is this the best way to accomplish my task.
UPDATE: I have to close the window after the button is pressed
UPDATE 1: I tried the solution from the other SO question, and it did not work for me.
<asp:Button ID="btnMyButton" runat="server" onClick="btnMyButton_Click" />
protected void btnMyButton_Click(object sender, EventArgs e)
{
}
I used the following code in my page, but the "The webpage you are viewing is trying to close the windows" module window pops up.
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
ScriptManager.RegisterStartupScript(upApproveRequest, typeof(string), "closeWindow", "window.close();", true);
Any way to prevent this?
Upvotes: 1
Views: 11273
Reputation: 51451
That's pretty much it. You can just use ScriptManager.RegisterStartupScript(...)
Upvotes: -2
Reputation: 1325
To avoid the script warning, you can use this:
window.open('', '_self', '');window.close();
So:
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
ScriptManager.RegisterStartupScript(upApproveRequest, typeof(string), "closeWindow", "window.open('', '_self', '');window.close();", true);
Upvotes: 1
Reputation: 1810
Actually you can do this by placing the following code in your button click event.
protected void btnMyButton_Click(object sender, ImageClickEventArgs e)
{
// Update database
bool success = Presenter.DoDatabaseStuff();
if (success)
{
// Close window after success
const string javaScript = "<script language=javascript>window.top.close();</script>";
if (!ClientScript.IsStartupScriptRegistered("CloseMyWindow"))
{
ClientScript.RegisterStartupScript(GetType(),"CloseMyWindow", javaScript);
}
}
else
{
// Display failure result
result_msg_area.Visible = true;
lblError.Text = "An error occurred!";
}
}
Upvotes: 2
Reputation: 57877
No, there is no way to close a browser window without the user's consent. You can log them out of their application, but you can't forcibly close the browser window.
Upvotes: 1