开发者

Javascript object accessible from all browser windows?

开发者 https://www.devze.com 2023-02-14 16:02 出处:网络
is it possible to access a javascript object f开发者_如何学JAVArom all browser windows? is there a global object to store data in?

is it possible to access a javascript object f开发者_如何学JAVArom all browser windows? is there a global object to store data in?

for example: we want to put information in one window from multiple opened or later opened windows.

Thank you


As long as one window is opened from another, and they open pages in the same domain, they can access each other. If you use the window.open method, you get a reference to the window object of the new window, and the window.opener property in the new window points to the window from where it was opened.

If you open a new instance of the browser, then the windows are completely separate and there is no way for the client scripts to communicate directly. Even if you open the page in a new window in the same instance, they can't communicate because they are not aware of each other.


You can pass the information to the target window via window.open , „javascript:“ using target and even initialize it, if it do not exists.

For example: You have a page “mypage.html” and there a javascript object myObject, and want to pass from any window in the browser the information foo = 'hello'.

mypage.html :

....
var myObject = {
        qs = {},
        init:  function()
            var b = window.location.href.split("?");
            if(b.length > 1){
                var p = b[1].split("&");
                for(var i = 0; i < p.length; i++){
                    var c = p[i].split("=");
                    qs[c[0]] = c[1];
                }
            }
            this.doFoo();
        },
        doFoo: function(){
            var foo = this.qs.foo;
            ....
        }
        ...
};
myObject.init();
...

the calling html's:

window.open(
    'javascript:if(typeof(myObject) == "undefined"){'
    + 'setTimeout(\'window.location.href = "mypage.html?foo=hello"\', 10);}'
    + 'else{myObject.qs={}; myObject.qs.foo="hello"; myObject.doFoo();}'
    , "mypage"
);

the setTimeout is only needed for chrom, because he got the "window.location.href" property not at startup.


If you are targeting modern browsers, you can use HTML 5 storage. http://www.quirksmode.org/blog/archives/2009/06/html5_storage_t.html

and as @Guffa said, you can have communication between parent window and child window easily even without storage.

0

精彩评论

暂无评论...
验证码 换一张
取 消