The webpage you are viewing is trying to close the window


For my first tutorial, here is a tip I found while working with pop-ups.

I was developing a custom page with a closing button when I was confronted to this error when I tried to use this closing button.

The context was to have a WebPart with a link opening my custom page as a pop-up, link defined as a basic a href.

 
protected override void CreateChildControls() 
{ 
string urlPage = string.Format("{0}/_layouts/TutoPopUp.aspx",SPContext.Current.Web.Url); 
Controls.Add(new LiteralControl(string.Format(@"<a href='{0}' target='_blank' >Mon lien </a>", urlPage))); 
} 

This link opened my pop-up perfectly. This pop-up was use to confirm an item deletion.

Clicking on « oui », the item was deleted and the « non » button event was called, event used to close the current page.

 
public void btnCancel_Click(object sender, EventArgs e) 
{ 
Page.Response.Write(@"<script language='javascript'> window.close();</script>"); 
} 

And then the error appeared.

This error come from a JavaScript rule : You can close a windows with JavaScript only if this windows was opened with JavaScript

To fix this error, we need to open the pop-up like this.

 
protected override void CreateChildControls() 
{ 
string urlPage = string.Format("{0}/_layouts/TutoPopUp.aspx",SPContext.Current.Web.Url); 
Controls.Add(new LiteralControl(string.Format(@"<a onclick='javascript:window.open (""{0}"");'>Mon lien </a>", urlPage))); 
} 

Christopher.

Article published for the first time the 22nd of April 2010 on Areaprog