Using Javascript to Refresh Parent

First let me say that I’m not a huge fan of Javascript. I understand the need for Javascript, but generally I prefer to program for a server environment instead of worrying about the client. However I ran into an issue this week that required Javascript, so here is what I learned about refreshing a parent window.

I had a web page that would list a bunch of items. Users needed to be able to click the “add” button and open a pop-up window that would let them choose an item to add to the list. The pop-up window displayed a hierarchy of choices so users had to click on it several times in order to make their selection.

When the user made their selection I needed the pop-up window to close and then refresh the original window. I found several things that worked on some browsers but not others. In the end I found something that seems to work on most browsers.

First the pop-up window must be triggered by Javascript. It appears that if you don’t trigger it with Javascript then some browsers won’t let you refer back to the original window in order to refresh it.

The code to close the current window is straightforward:
Once again this only seems to work reliably if you are dealing with a window that was opened with Javascript.

The code to refresh the parent is:
There are several other things that should work, but this seems to be the best way to make it compatible with different browsers.

The next problem I ran into was the fact that I needed the user to click on a “select” button which was a hyper-link in order to actually select the item. At first I just added the javascript to the onClick attribute of the hyperlink. This worked fine in some browsers where the hyperlink was evaluated before the javascript. However some browsers evaluate the onClick before the hyperlink. This caused the window to close before triggering the hyperlink which means the event tied to the hyperlink never fired.

In the end I created a variable called closeWindowString and bound it to the onLoad attribute of the body tag of the pop-up page. The string is normally blank. When the users clicks the select button the hyperlink is triggered. This causes the server to do it’s job and sets the closeWindowString to:
When the page starts to reload (the hyperlink just triggers some server methods and reloads the same page), it hits the Javascript in the onLoad attribute, closes the page and refreshes the page that opened it.

As far as I can tell this seems to work in most of the major browsers without any problem. It doesn’t rely on a certain order in the way attributes are evaluated so it should work the same regardless of what browser is working as long as the browser supports Javascript.


3 Replies to “Using Javascript to Refresh Parent”

Leave a Reply

Your email address will not be published. Required fields are marked *