So I am using the onbeforeunload event to close any child windows (images) that have been opened from my parent window. The code I am working with is old and the parent window does many post-backs for different operations so I am keeping track of the images server-side and adding the onbeforeunload attribute to the body when I need it.
When the window is to be closed the server-side code writes a script that simply calls a Javascript function with a string parameter. The Javascript works fine, the problem is that it does not always get hit.
My server-side code looks like this:
private void CloseAllChildren()
{
// some code to retrieve image window names...
string script = "closeAllChildren('imagewindowname1,imagewindowname2,etc');";
_body.Attributes.Add("onbeforeunload", script);
}
And the close method that is called when a close event is triggered:
private void Close()
{
// A bunch of code...
// close the window after all folders have been routed
CloseAllChildren();
this.Response.Write(FolderView.WindowClose);
}
I know nothing with computers is random, but my results do not seem to follow any sort of pattern. Sometimes it hits the Javascript and works perfectly, sometimes it never hits the Javascript under the same test conditions. I am assuming there is some kind of race condition but I am not sure how to detect or fix it. Does anyone have any experience with this or a better way of doing it? Like I said, the code is old and this was a small addition to functionality, so I do not want to change any of the current framework.
Thanks in advance.
After trying the suggestions above and a few of my own ideas it seems the problem was that the javacript would end up executing the window.top.close()
command before the onbeforeunload attribute was added (since it was being written dynamically), which is similar to what I expected. I added a timeout of half a second by changing window.top.close()
to setTimeout(function() {window.top.close();}, 100)
and it seems to have fixed the "randomness" I was experiencing.
I appreciate the help, while I didn't end up using the other solutions they helped me find the real problem.