views:

670

answers:

1

Setup:

I'm opening a new window via js that is a classic asp page with one form (yes, classic asp, I know). That form posts to a processing page where I Response.Write() some inline js to manipulate form elements on the parent page like so.

.Write ("<script language=""javascript"">" & vbcrlf)    
.Write ("var stopButton = opener.document.getElementById(""timerStop"");" & vbcrlf)
.Write ("stopButton.style.display = ""inline"";" & vbcrlf)
.Write ("window.close();" & vbcrlf)
.Write ("</script>" & vbcrlf)

Problem:

All of the above works fine, when I try to change the onclick value of the stopButton element:

.Write ("<script language=""javascript"">" & vbcrlf)
.Write ("var stopButton = opener.document.getElementById(""timerStop"");" & vbcrlf)
.Write ("stopButton.style.display = ""inline"";" & vbcrlf)
**.Write ("stopButton.onclick = function () {alert(""test"");};" & vbcrlf)**
.Write ("window.close();" & vbcrlf)
.Write ("</script>" & vbcrlf)

And then click on the button after the window closes I get an error in FF and nothing happens in IE:

uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMWindowInternal.alert]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: /timer/activity_proc.asp?a=start :: anonymous :: line 8" data: no]

Is this because the child window no longer exists? I should note that the button does have an onclick value prior to me attempting to change its value.

+1  A: 

Hi, I think this is because the child window no longer exists.

There is a way of creating functions in javascript that's called closures. Essentially, a function "belongs" or "is stored" in the content where it's declared. In this case, on the child window.

If you have a function that does the work on your parent window and call that instead of assigning directly, it should work. ie:

on the parent document:

assignStopButtonListener = function(){
    var stopButton = document.getElementById(""timerStop"");
    stopButton.style.display = "inline";
    stopButton.onclick = function () {alert("test");};
}

on your popup document

.Write ("<script language=""javascript"">" & vbcrlf)
.Write ("opener.assignStopButtonListener();" & vbcrlf)
.Write ("</script>" & vbcrlf)
Joshua
Thank you Sir, works perfectly.
Dzejms