How to get, and communicate with, persistent popup windows in Javascript

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:

  1. window.location = "javascript:alert('hi!');";
    • This means we can run javascript on a window object
  2. 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
  3. 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!


Posted

in

,

by

Tags:

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.