2011-11-02 28 views
3

我需要從另一個瀏覽器窗口打開一個新的瀏覽器窗口,並從子窗口的父窗口訪問一個對象。所以,當加載子窗口時,我使用opener屬性來訪問父對象。在Firefox中工作正常,但在IE中,數組屬性被轉換爲對象。在IE中的單獨窗口中使用Javascript對象

例如

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))); 
    } 
}); 

當在IE中打開的子窗口中的結果將是

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

,結果在Firefox大約是

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

一個工作對象過於序列化到JSON,傳遞字符串,然後反序列化。但是,對象上的任何方法都會丟失。

除了圍坐在談論IE如何成爲Web開發的禍根外,我還能做些什麼?

回答

2

一種解決方法是將對象轉換爲父窗口中的JSON,並將該字符串傳遞給子代,然後將該JSON解析爲對象。

例如 在父窗口:

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

並在子窗口:

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

然而,這將失去任何對象的任何方法。

0

我遇到過類似的問題,今天,發現使用underscore.js以下解決方案行之有效:

var parentData = _.toArray(window.opener.data);