Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Javascript objects across separate windows in IE

I need to open a new browser window from another browser window and access an object from the parent window in the child window. So when the child window loads I use the opener property to access the object from the parent. Works fine in Firefox however in IE the array properties are converted to objects.

e.g.

function openChild() {
    window.open(window.document.location, '_blank');
}

var data = {
    myArray: []
};

$(document).ready(function() {
    alert('data is array: ' + (data.myArray instanceof Array));
    alert('prototype: ' + (Object.prototype.toString.call(data.myArray)));

    if (window.opener) {
        var parentData = window.opener.data;
        alert('parent data is array: ' + (parentData.myArray instanceof Array));
        alert('parent prototype: ' + (Object.prototype.toString.call(parentData.myArray)));
    }
});

When the child window is opened in IE the result will be

data is array: true
prototype: [object Array]
parent data is array: false
parent prototype: [object Object]

and the result in Firefox is

data is array: true
prototype: [object Array]
parent data is array: false
parent prototype: [object Array]

One work around is too serialize the object to JSON, pass the string and then deserialize. However any methods on the object are lost.

What else can I do other than sit around talking about how IE is the bane of web development?

like image 473
Chris Herring Avatar asked Dec 06 '25 05:12

Chris Herring


1 Answers

One workaround is to convert the object to JSON in the parent window and pass the string to the child which then parses the JSON back into an object.

e.g. In parent window:

function getData() {
    return JSON.stringify(data);
}

and in child window:

var parentData = JSON.parse(window.opener.getData());

However this will lose any methods on any objects.

like image 194
Chris Herring Avatar answered Dec 08 '25 17:12

Chris Herring



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!