jbkkd
jbkkd

Reputation: 1550

JSON Object returned from a second page does not stringify in IE 8

Consider the following scenario:

FooPage is page which, on clicking "Add", opens BarPage.

BarPage has a "Return" button. Upon clicking on it, it does the following:

function Add() {
    var selectedResources = [{ 
        "ResourceID": "10", 
        "ResourceName": "Foo", 
        "ResourceTypeName": "Bar"
    }];
    if (window.opener != null 
        && typeof window.opener.AddResources != "undefined") {
        window.opener.AddResources(selectedResources);
        window.close();
    }
}

FooPage, as you may see, has a function called AddResources. It does the following:

function AddResourcesCallback(selectedResources) {
    var result = JSON.stringify(selectedResources);
}

In Chrome, this works great - the string is created from the JSON in JSON.stringify and everyone is happy.

In IE8, however, this does not work. The JSON does not get created into a string - instead, JSON.stringify returns undefined.

I tried changing the scenario to this, as a test:

function AddResourcesCallback(selectedResources) {
    var selectedResources = [{ 
        "ResourceID": "10", 
        "ResourceName": "Foo", 
        "ResourceTypeName": "Bar"
    }];
    var result = JSON.stringify(selectedResources);
}

In this scenario, JSON.stringify in IE8 returns the correct value, just like Chrome. Meaning, that in IE8, when passing an array from page to page, you can't parse the array to JSON.

Is there a way to pass the Array without stringifying it first?

Upvotes: 2

Views: 730

Answers (1)

Bergi
Bergi

Reputation: 664444

Seems to be a cross-window scope problem - the two objects have different Object.prototype prototype objects which might confuse IE (especially if one of them is garbage collected due to window closing). Try stringifying with the other window's JSON function like this:

// BarPage
if (window.opener != null && typeof window.opener.AddResources != "undefined") {
    window.opener.AddResources(selectedResources, JSON);
    window.close();
}

// FooPage
function AddResourcesCallback(selectedResources, json) {
    var result = json.stringify(selectedResources));
}

However, I think stringifying in one window, passing the string and parsing it back in the other window will be the safest approach.

Upvotes: 1

Related Questions