75

I have a page which spawns a popup browser window. I have a JavaScript variable in the parent browser window and I would like to pass it to the popped-up browser window.

Is there a way to do this? I know this can be done across frames in the same browser window but I'm not sure if it can be done across browser windows.

Tom Kidd
  • 12,830
  • 19
  • 89
  • 128

14 Answers14

113

Putting code to the matter, you can do this from the parent window:

var thisIsAnObject = {foo:'bar'};
var w = window.open("http://example.com");
w.myVariable = thisIsAnObject;

or this from the new window:

var myVariable = window.opener.thisIsAnObject;

I prefer the latter, because you will probably need to wait for the new page to load anyway, so that you can access its elements, or whatever you want.

Victor
  • 9,210
  • 3
  • 26
  • 39
  • i don't understand {foo:'bar'}. could you please help me on this? – Masoud Sahabi Sep 10 '13 at 07:49
  • 1
    @MasoudSahabi, `var x = {foo: 'bar'}` is just a compact literal syntax for creating an object. It's the same as `var x = new Object(); x.foo = 'bar';` – sergiopereira Sep 19 '13 at 19:27
  • I am using the first one and it works fine in Chrome but IE seems to complain. And it's very hard to get a breakpoint to hit. – styfle Nov 06 '13 at 22:51
  • 1
    This would be great, but now IE10 complains about it, this is not the best way for a cross browser compatibility at the moment. – 7dr3am7 Nov 28 '13 at 17:36
  • 1
    @7dr3am7, I see, I get "Permission denied". But if I use the second method, from the new window, it works fine. – Victor Nov 30 '13 at 12:11
  • @Victor can you please answer this question http://stackoverflow.com/questions/25762872/execute-function-in-new-window-and-change-variable-in-new-window-after-complete – user3637224 Sep 10 '14 at 11:37
  • I struggled for hours using this solution before realizing that `var myVariable = window.opener.thisIsAnObject;` doesn't work, but `var myVariable = thisIsAnObject;` does. Does anyone know why this is so? Is there an error in the answer above or is it something with new browsers or versions? – Krøllebølle Oct 16 '15 at 13:47
  • in the new window, the custom argument can be serialized to string using - `(new XMLSerializer()).serializeToString(myVariable)`. it works fine in Chrome. But not working in Edge, getting Parser error. Any one has solution for Edge browser? – Apparao Jan 21 '16 at 11:09
  • How to received data new window? – Kamrul Hasan Oct 03 '19 at 06:04
  • thisIsAnObject should be a global variable – peschanko Dec 05 '20 at 20:32
46

Provided the windows are from the same security domain, and you have a reference to the other window, yes.

Javascript's open() method returns a reference to the window created (or existing window if it reuses an existing one). Each window created in such a way gets a property applied to it "window.opener" pointing to the window which created it.

Either can then use the DOM (security depending) to access properties of the other one, or its documents,frames etc.

MarkR
  • 62,604
  • 14
  • 116
  • 151
  • 20
    Things have changed since this question was asked. It is now also possible, on [newer browsers](http://caniuse.com/#feat=x-doc-messaging), to pass messages between windows on a *different* security domain, via calls to `window.postMessage`. – Brian Mar 31 '13 at 20:25
8

Yes, scripts can access properties of other windows in the same domain that they have a handle on (typically gained through window.open/opener and window.frames/parent). It is usually more manageable to call functions defined on the other window rather than fiddle with variables directly.

However, windows can die or move on, and browsers deal with it differently when they do. Check that a window (a) is still open (!window.closed) and (b) has the function you expect available, before you try to call it.

Simple values like strings are fine, but generally it isn't a good idea to pass complex objects such as functions, DOM elements and closures between windows. If a child window stores an object from its opener, then the opener closes, that object can become 'dead' (in some browsers such as IE), or cause a memory leak. Weird errors can ensue.

bobince
  • 528,062
  • 107
  • 651
  • 834
6

Passing variables between the windows (if your windows are on the same domain) can be easily done via:

  1. Cookies
  2. localStorage. Just make sure your browser supports localStorage, and do the variable maintenance right (add/delete/remove) to keep localStorage clean.
Roman M
  • 67
  • 1
  • 3
4

One can pass a message from the 'parent' window to the 'child' window:

in the 'parent window' open the child

    var win = window.open(<window.location.href>, '_blank');    
       setTimeout(function(){
                    win.postMessage(SRFBfromEBNF,"*")
                  },1000);
    win.focus();

the to be replaced according to the context

In the 'child'

    window.addEventListener('message', function(event) {
        if(event.srcElement.location.href==window.location.href){
        /* do what you want with event.data */
        }
    }); 

The if test must be changed according to the context

3

In your parent window:

var yourValue = 'something';
window.open('/childwindow.html?yourKey=' + yourValue);

Then in childwindow.html:

var query = location.search.substring(1);
var parameters = {};
var keyValues = query.split(/&/);
for (var keyValue in keyValues) {
    var keyValuePairs = keyValue.split(/=/);
    var key = keyValuePairs[0];
    var value = keyValuePairs[1];
    parameters[key] = value;
}

alert(parameters['yourKey']);

There is potentially a lot of error checking you should be doing in the parsing of your key/value pairs but I'm not including it here. Maybe someone can provide a more inclusive Javascript query string parsing routine in a later answer.

Grant Wagner
  • 25,263
  • 7
  • 54
  • 64
2

You can pass variables, and reference to things in the parent window quite easily:

// open an empty sample window:
var win = open("");
win.document.write("<html><body><head></head><input value='Trigger handler in other window!' type='button' id='button'></input></body></html>");

// attach to button in target window, and use a handler in this one:
var button = win.document.getElementById('button');

button.onclick = function() {
     alert("I'm in the first frame!");   
}
knut
  • 689
  • 5
  • 13
  • As written this won't work in the real world where people are running adblock etc. By adding parameters to the open to get it to open in a separate window (instead of tab, as I have FF configured to do) I was able to get this working in firefox. But the pop-up was blocked in Chrome. So it's simple and sort of works, but it's a bit far from a workable solution. – Nick Rice May 03 '16 at 06:00
1

For me the following doesn't work

var A = {foo:'bar'};
var w = window.open("http://example.com");
w.B = A;

// in new window
var B = window.opener.B;

But this works(note the variable name)

var B = {foo:'bar'};
var w = window.open("http://example.com");
w.B = B;

// in new window
var B = window.opener.B;

Also var B should be global.

Haris
  • 13,645
  • 12
  • 90
  • 121
1

Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".

Jordan Mack
  • 8,223
  • 7
  • 30
  • 29
0

I have struggled to successfully pass arguments to the newly opened window.
Here is what I came up with :

function openWindow(path, callback /* , arg1 , arg2, ... */){
    var args = Array.prototype.slice.call(arguments, 2); // retrieve the arguments
    var w = window.open(path); // open the new window
    w.addEventListener('load', afterLoadWindow.bind(w, args), false); // listen to the new window's load event
    function afterLoadWindow(/* [arg1,arg2,...], loadEvent */){
        callback.apply(this, arguments[0]); // execute the callbacks, passing the initial arguments (arguments[1] contains the load event)
    }
}

Example call:

openWindow("/contact",function(firstname, lastname){
    this.alert("Hello "+firstname+" "+lastname);
}, "John", "Doe");

Live example

http://jsfiddle.net/rj6o0jzw/1/

singe3
  • 2,065
  • 4
  • 30
  • 48
0

You can use window.name as a data transport between windows - and it works cross domain as well. Not officially supported, but from my understanding, actually works very well cross browser.

More info here on this Stackoverflow Post

Community
  • 1
  • 1
Brad Parks
  • 66,836
  • 64
  • 257
  • 336
0

Alternatively, you can add it to the URL and let the scripting language (PHP, Perl, ASP, Python, Ruby, whatever) handle it on the other side. Something like:

var x = 10;
window.open('mypage.php?x='+x);
Milan Babuškov
  • 59,775
  • 49
  • 126
  • 179
-1

Yes browsers clear all ref. for a window. So you have to search a ClassName of something on the main window or use cookies as Javascript homemade ref.

I have a radio on my project page. And then you turn on for the radio it´s starts in a popup window and i controlling the main window links on the main page and show status of playing and in FF it´s easy but in MSIE not so Easy at all. But it can be done.

LAT
  • 1
-2

The window.open() function will also allow this if you have a reference to the window created, provided it is on the same domain. If the variable is used server side you should be using a $_SESSION variable (assuming you are using PHP).

HappySmileMan
  • 1,015
  • 8
  • 9