JavaScript: Persisting a child window relation accross parents’ reloads.
I came across a fun issue with my pop-up flash mp3 player to be used on our new Vital website (coming soon.) I've designed a 'listen' button on the main shop website for each audio file preview. When this listen button is clicked on, a pop-up window is opened (if not already) and the flash player loads the respective audio file and begins playing. If a second listen button is clicked, the new track will be added to the existing play list and that track will begin playing. I discovered this method only worked when clicking listen links on the same parent page view. If the parent page is refreshed or a new page of the site is loaded, the reference to the pop-up window is lost. What then happens is any new listen link clicked will cause the pop-up page to reload from scratch and loose the play list. Whatever audio was playing stops, whatever tracks were in the play list are gone. Following, is my solution.
I've discovered that by saving an instance of the pop-up window object to the pop up itself, I can re-initialize the pop-up window object back on the parent window after a new page is loaded on the parent. Here's an example of the execution.
- Parent window begins reloading/browsing to a new page.
- Parent window sends a reference of the pop-up window to the pop-up.
- Pop-up window begins to continually check the parent window for a successful page load.
- Pop-up window sends the temporary instance of itself back to the parent window
Here's the code required to accomplish this:
Firstly, "wimpyWindow" is the name of the pop-up window. Here's the JavaScript that opens that window:
-
<script type="text/javascript">
-
var wimpyWindow;
-
var winOpen=0;
-
function wimpyPopPlayer() {
-
wimpyWindow = window.open('<ww :url page="/wimpy/wimpy.html"/>','wimpyMP3player','width='+windowWidth+',height='+windowHeight);
-
winOpen=1;
-
}
-
</script>
Inside the parent window's <head> tag, create the following JavaScript. This function saves a copy (tempWindow) of the pop-up window object to the pop-up window, starts a function on the pop-up that continually checks the state of the parent window, and sets an indicator (parentRefreshed) that declares the parent page is refreshing.
-
<script type="text/javascript">
-
var pageLoaded = false;
-
-
function window_onunload() {
-
pageLoaded = false;
-
if (winOpen==1) {
-
wimpyWindow.tempWindow = wimpyWindow;
-
wimpyWindow.checkParent();
-
wimpyWindow.parentRefreshed = true;
-
}
-
return true;
-
}
-
</script>
In the parent window's <body> tag, add the following which will execute the above function whenever the parent window is reloaded or browses to a new page.
-
<body onunload="window_onunload();">