Can I pass a JavaScript variable to another browse

2019-01-02 17:28发布

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.

13条回答
高级女魔头
2楼-- · 2019-01-02 17:58

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".

查看更多
爱死公子算了
3楼-- · 2019-01-02 17:59

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/

查看更多
步步皆殇っ
4楼-- · 2019-01-02 17:59

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

查看更多
春风洒进眼中
5楼-- · 2019-01-02 18:01

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);
查看更多
心情的温度
6楼-- · 2019-01-02 18:03

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.

查看更多
与风俱净
7楼-- · 2019-01-02 18:04

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.

查看更多
登录 后发表回答