Let’s say you have a webapp that needs a popup window to hold something (a media player for example) and you want just one for the lifetime of your app. You want to be able to communicate with it (i.e. run javascript functions in it). How?! Read below!
Impatient? View the demo 🙂
Basic idea
The tricks this solution uses:
window.location = "javascript:alert('hi!');";
- This means we can run javascript on a window object
var winref = window.open("", "somepopupname");
- This basically opens a blank popup, or gets an existing popup by name (i.e. sends it to where it already is). At least in Chrome, this doesn’t cause a page refresh of the popup
- Keeps the winref around so we can then use the above trick (
winref.location = "javascript:..."
) to run javascript in the existing popup
- The popup can access its opener (the window that opened it) with
window.opener
Using these, we can send messages to and from the popup – create a function in both the app page and the popup, then “call it” with the window.location trick above.
One thing to note – window.open
is asynchronous – so flow continues potentially before the window is ready. To get around this, I make the popup send a message back to its parent window (window.opener
) that notifies the app that the popup is ready to use; then we can send the message.
As I mentioned at the beginning, you can see a demo of all of this in action here!
Leave a Reply