Link to home
Start Free TrialLog in
Avatar of mrcoulson
mrcoulsonFlag for United States of America

asked on

WHy doesn't my window.close work in VB.Net?

The script below grabs an email username from a LinkButton and redirects to another page with a form that does stuff with that username.  Then I want this window to close.  I've declared my JavaScript as a string and call it with Response.Write, but the window doesn't close.  The redirecting works fine, but the window closing doesn't happen at all.  What am I missing?
<script runat="server" language="vb">
Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
	Dim closeWindowScript As String
	closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"
	Response.Write(closeWindowScript)
End Sub
</script>

Open in new window

Avatar of Christian de Bellefeuille
Christian de Bellefeuille
Flag of Canada image

How do you call this script?  Which event?

You also forgot to use the PageRegisterScript or something like that
Avatar of mrcoulson

ASKER

Forgetting would presuppose that I knew about it to begin with ;)

See below for simplified code that only has the form tag and the LinkButton.
<form id="supervisorForm" runat="server" target="_new">
<asp:LinkButton ID="LinkButton1" runat="server" Text="Email Gary" CommandArgument="gary@garylofton.org" CommandName="SetSessionVariable" OnCommand="SetSessionVariable" />
</form>

Open in new window

Or the whole stinkin' page if it helps!
<%@ Page Language="VB" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
 
<script runat="server" language="vb">
Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
	Dim closeWindowScript As String
	closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"
	Response.Write(closeWindowScript)
End Sub
</script>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 
<head runat="server">
<title>Back Creek Supervisor</title>
<link rel="shortcut icon" href="/FAVICON.ICO" type="image/x-icon" />
<style>
body {background-color: #ffffff;}
h2 {font-family: sans-serif;}
p {margin-right: 5%;}
.image {float: left; padding: 10px;}
.style1 {font-size: 18px}
</style>
<script type="text/javascript" src="/js/offsiteAlerter.js"></script>
</head>
<body>
<form id="supervisorForm" runat="server" target="_new">
<h2>Back Creek  Magisterial District</h2>
<div class="image"><img src="images/lofton.gif" /></div>
<p><span class="style171 style1"><strong>Gary A. Lofton</strong></span><br>
711 Buffalo Marsh Road<br />Middletown, VA 22645
<br>
(540) 869-1972<br />fax (540) 869-1972<br />
<asp:LinkButton ID="LinkButton1" runat="server" Text="Email Gary" CommandArgument="gary@garylofton.org" CommandName="SetSessionVariable" OnCommand="SetSessionVariable" /><br>
<br>
<span class="blurb">Gary Lofton was elected to the Board on January 1, 2008. </span></p>
<p><span class="blurb">Mr. Lofton represents the Board as a member of the Human Resources Committee Chairman; Code &amp; Ordinance Committee; Social Services Board;  Planning Commission liaison; Agricultural District Advisory; and Extension Leadership Council.</span></p>
<p><span class="blurb">Prior to his election to the Board, Mr. Lofton worked with VDOT for seven years and worked for the City of Winchester for 36+ years as Public Works Director and Director of Transportation. Mr. Lofton retired in 2006 and works as the Area Director for BNI-Shenandoah Valley.</span></p>
<p><span class="blurb">He is a graduate of James Wood High School and attended Lord Fairfax Community College. </span></p>
<center><p><input type=button value="Close Window" onClick="javascript:window.close();"></p></center>
</div>
</form>
</body>
</html>

Open in new window

  1. You cannot close a window that was not opened by window.open (in some browsers like Firefox).
  2. Which page do you want to close? The current page or email_form_2.aspx? Response.write might not work after redirect.
Try this

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
        dim url as string"/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString())
Server.Execute(url)
        Dim closeWindowScript As String
        closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"
        Response.Write(closeWindowScript)
End Sub

Open in new window

Its ok.  Its normal that we don't know everything.  
First, i'm not even sure that your closeWindowScript get written because of the redirect.
Second, when you set a javascript to run on an html element, often you have to call the Page.RegisterStartupScript (my bad in my last comment).

There,s many ways to close a window...

in your example, you might want to add in your aspx file:  OnClientClick="window.close();"
Here's a method that i use sometime to close a window...

Let's say that i have a popup named "ScheduleEvent.aspx".
You need to name your body like this:
<body id="BodyTag" runat="server>

Then when you are ready to close your window (in your SetSessionVariable), you just call the CloseWindow function.

How it work?  easy... on call of CloseWindow, the page redirect to itself.  So the PreInit is called and since it see that you have set action=close, it assign some javascript code to the onload event of the body.  Then... just after the preinit, the body load and close the form.  This way you don't need any RegisterStartupScript.
--- this in your "Code Behind" ---
    Private Sub CloseWindow()
        Response.Redirect("ScheduleEvent.aspx?action=close")
    End Sub
 
    Private Sub ScheduleEvent_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        If Request.QueryString.Get("action") = "close" Then
            BodyTag.Attributes.Add("onload", "javascript:(window.close())")
        End If
    End Sub

Open in new window

Okay, taking these in turn.

baiju_nagori: Your idea gave me an error about the codebehind on the subsequent page.

cdebel: Your first idea: the window closed perfectly -- but before the redirect had a chance to happen.  I'll have to try your second idea later this evening.  I have to go home and tag-team my wife for watching the kids while she goes to work.

Jeremy


MrCoulson:  No problem.  I'm sure you won't have too much problem.  But may i ask why you do not just use:   Session("MyVariable") = e.CommandArgument.ToString()?

Is this line intended to close the aspx page that you have just shown us?
closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"

If so, then i don't understand why you close a window just after redirecting to another page.  The user will never get to see the page email_form_2.aspx.
Okay, I'm still struggling here.  I've adapted your idea.  If the CommandArgument is not empty, then perform the redirect and run a closing script.  I don't think I can use "BodyTag.Attributes.Add("onload", "javascript:(window.close())")" because this window is already loaded.  Correct?

This window is a pop-up window.  When a user clicks the email link, I want the pop-up window to close and the email form to open in a new window.  Actually, I'd really prefer it to open in the window that launched the pop-up, but I believe I remember learning that it can't be done.

Also, I used to have this running with a session, but the email form is not in the same application as all the other pages.
<script runat="server" language="vb">
Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
	If e.CommandArgument.ToString() <> String.Empty Then
		Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
		Dim closeWindowScript As String
        closeWindowScript = "<script language='javascript'> { window.close(); }<" & "/script>"
        Response.Write(closeWindowScript)
	End If
End Sub
</script>

Open in new window

Hi,

Why dont you use closeWindowScript in page load of email_form_2.aspx? On this page, you can just redirect.

Baiju
Can email_form_2.aspx close popBackCreek.aspx?

The pages in real life: http://www.co.frederick.va.us/board_of_supervisors/.  Click on the guy who's second from left in that photo.
Hi mrcoulson,

Add a literal control to popBackCreek.aspx and write closeWindowScript to the text property of that literal.

example

lit.text = "<script type='text/javascript'> { window.close(); }<" & "/script>"

Do this in SetSessionVariable
Do I need to add the control first?

What is below also does not work.
<script runat="server" language="vb">
Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
	Me.Controls.Add(New LiteralControl("<script type='text/javascript'> { window.close(); }<" & "/script>"))
End Sub
</script>

Open in new window

Just add a literal control to your ASPX file.
<asp:Literal runat="server" id="lit"></asp:Literal>

and then use it

Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
       lit.Text = "<script type='text/javascript'> { window.close(); }<" & "/script>"
End Sub
Ah.  Trying now...
No joy here.


' Function
 
<script runat="server" language="vb">
Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
	lit.text = "<script type='text/javascript'> { window.close(); }<" & "/script>"
End Sub
</script>
 
' Control in ASPX
 
<asp:Literal runat="server" id="lit"></asp:Literal>

Open in new window

Don't we need an event to trigger the script?
Mr Coulson, have you tried my solution?

>>I don't think I can use "BodyTag.Attributes.Add("onload", "javascript:(window.close())")"
>>because this window is already loaded.  Correct?

This is the beauty of PreInit.  In this method, the objects exists, but the no other events have been triggered yet.  So you can assign an event, and you will be sure that it will be triggered.

I use this method all the time.  Why reinventing the wheel?
cdebel: I don't know how to implement your solution.  I already have a Response.Redirect.  Below is my attempt that did not work.  The redirect happens, but the close never does.  I guess I don't really understand how adding an action to onload of a window after it's already loaded will work -- maybe if it's somehow testing if the email form window is loaded...?


<script runat="server" language="vb">
Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
End Sub
 
    Private Sub ScheduleEvent_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        If Request.QueryString.Get("user") <> String.Empty Then
            BodyTag.Attributes.Add("onload", "javascript:(window.close())")
        End If
    End Sub
 
</script>

Open in new window

ok, give me a second, i'll implement it and send you a complete file...
Okay, this is the last solution that I can offer:

On page load,

DIm URL as string = "/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString())
           
LinkButton1.Attributes.Add("onclick","opener.location.location=" & URL & "; window.close(); return false;")



This will change the parent window's location and close existing window.
baiju_nagori:  'CommandArgument' is not a member of 'System.EventArgs'  Sure wish you could stick around!

Jeremy
<script runat="server" language="vb">
 
Public Sub page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
	Dim URL As String
	URL = "/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString())
   	LinkButton1.Attributes.Add("onclick","opener.location.location=" & URL & "; window.close(); return false;")
End Sub
 
Protected Sub SetSessionVariable(ByVal sender As Object, ByVal e As CommandEventArgs)
	Response.Redirect("/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode(e.CommandArgument.ToString()))
End Sub
 
</script>

Open in new window

Sorry man, my bad with previous code You need to use the email address instead of commandargument

Public Sub page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim URL As String
        URL = "/apps/email_form/email_form_2.aspx?user=" & Server.HtmlEncode("gary@garylofton.org")
        LinkButton1.Attributes.Add("onclick","opener.location.location=" & URL & "; window.close(); return false;")
End Sub

Okay, man.  Here's where that is.

If I plug your function in and leave SetSessionVariable, the page just redirects with no close.

If I take the SetSessionVariable function away, the page throws an exception because that function is still referenced in the LinkButton.

If I removed OnCommand from the LinkButton, the link then just opens popBackCreek.aspx in another window without ever redirecting.

Jeremy
ASKER CERTIFIED SOLUTION
Avatar of Christian de Bellefeuille
Christian de Bellefeuille
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
And about my last solution here are my comments:
- You need to open the first popup with the CallerForm.aspx.
- In the Popup2.apsx, i've removed an image because i didn't had it (lofton.gif)... you can place it back
- In Popup2.aspx, you have to make sure that you point to your own path.
so instead of having this:
s = "opener.location='email_form_2.aspx?user=" & Request.QueryString.Get("email") & "';"

you would have something like this:

s = "opener.location='/apps/email_form/email_form_2.aspx?user=" & Request.QueryString.Get("email") & "';"
cdebel: Okay, let me try that out.  I need to put it all in the right place and get back to you.

Jeremy
If you tell me that this doesn`t work, please, download the whole solution here.  Its probably because you have made a mistake in copy&paste.
Download Solution
(This solution was made with Visual Studio 2005 Std)
Still haven't had a chance to try this out.  In a meeting right now!  I'll get back to this as soon as I can!

Jeremy
good.  Just to save you some time, just download the solution.   Then if you want to apply it differently or need explanations on how it work, feel free to ask.  I'll be here...
it has been a month.   Did you had time to try it Jeremy?
Cleaning up old questions.  Thanks!  Sorry about the delay.