RegisterStartupScript not working in C#

时间:2017-04-13 14:53:43

标签: javascript c#

I have two methods in my c# code. One is to open a error window and another is to close the error window. The Problem is in the first method new window opened correctly, For the next method call(to close the window) sometimes window is not getting closed.

Here my first method code to open the window

ClientScriptManager cs = Page.ClientScript;
Type cstype = this.GetType();
string script = "window['myWindow'] = window.open('Error.aspx', 'myWindow', 'width=400,height=200');";
cs.RegisterStartupScript(cstype, "OpenScript", script, true);

My second method to close the window

ClientScriptManager cs = Page.ClientScript;
Type cstype = this.GetType();
string script = "var myWindow=window['myWindow']; if(myWindow == null){";
script += "myWindow = window.open('', 'myWindow');}";
script += "myWindow.close();";
cs.RegisterStartupScript(cstype, "CloseScript", script, true);

1 个答案:

答案 0 :(得分:0)

您应该先在第二种方法的javascript中检查if (myWindow != null) {,然后使用myWindow.close();关闭窗口,而不是相反。你为什么还在第二种方法中使用window.open('','myWindow');

第二种方法应如下所示:

ClientScriptManager cs = Page.ClientScript;
Type cstype = this.GetType();
string script = "var myWindow=window['myWindow']; if(myWindow != null)";
script += "myWindow.close();";
cs.RegisterStartupScript(cstype, "CloseScript", script, true);