dagblog.
← Archive

JavaScript and sharing variables between windows


I sometimes deal with very odd problems. I needed
 to share a value (an identifier needed to submit the parent form with settings from the child window) between the parent 
 and child windows. There are basically three known methods people use.

  • Pass the value as a parameter and process it on the server
  • Pass it in the URL (GET) and extract it by parsing the URL on the client
  • Read the value from the parent window through its form using the opener

Now back to that opening sentence. Why an odd problem? I like trying new approaches, and 
 because I’m lazy and didn’t feel like fiddling with any of the previous methods, I looked 
 for another solution. It occurred to me that on the parent window, or more precisely on its window object,
 we could register a variable and populate it when the page loads or at some other time. The variable
 can then be accessed through the opener object.

The advantage over the other solutions is that it takes less client-side 
 script, requires no work on the server, and needs no 
 input element with a hidden attribute for us to read. 
 The solution also points to another advantage. Instead of a variable we could 
 register an event handler (a function of our own) that would be accessible,
 meaning callable, from the child window.

A working code example

Rodičovské okno:

//registrace globalni proměnné objektu window
window.foo = "acme";
Dceřiné okno:

//načtení proměnné rodičovského okna
var parentValueFoo = opener.window.foo;
As you can see, the solution is very simple and perfectly
adequate. There’s strength in simplicity.

Medium version

Related articles

Related CZ Podcast episodes