2011-08-24 26 views
9

假設你有一個全球性的功能警報2:可能在另一個窗口的上下文中調用Javascript方法?

function alert2(msg) { 
    window.alert(msg); 
} 

而且你還需要第二個窗口對象的引用:

childWindow = window.open(myUrl); 

現在,你想從窗口在childWindow的情況下調用警報2 :

alert2.call(childWindow, "does not work without this.window"); 

該對話框出現在主窗口中,因爲alert2中的「窗口」被綁定到該方法定義的窗口d(父窗口)。

一種解決方案是修改警報2:

function alert2(msg) { 
    this.alert(msg); 
} 

是否有可能做到這一點沒有這種修改?類似這樣的:

alert2.call(childWindow.parent, "no such thing as window.parent"); 

這是一個人爲的例子; childWindow.alert(「」)不是我要找的!

我的來源可以看到和修改上的jsfiddle開始http://jsfiddle.net/hJ7uw/2/

回答

5

注:如果這兩個窗口這隻能屬於同一個域(單域策略)。

你可以做的是在childWindow創建功能:

var func = function() { 
    var parent = window; // pointer to parent window 
    var child = childWindow; 

    return function() { 

     ... anything you like to do ... 
     parent.alert('Attached to main window') 
     child.alert('Attached to child window') 
    } 
}(); 

childWindow.func = func; // pass function to child window 

嵌套功能確保您可以從其中函數創建上下文(注意}();在終止結束訪問引用第一個函數並立即調用它)。

最後一行在子窗口中創建新函數;子窗口中的所有JavaScript代碼也可以作爲window.func訪問它。

這有點令人困惑,但只是想到它是這樣的:你有兩個窗口實例/對象。就像使用任何JavaScript對象一樣,您可以爲它們分配新的屬性。

+1

謝謝...你的代碼說明我對問題的理解。在這種情況下,無法在上面的func()中替換「child」或「parent」的含義。類似地,似乎無法在函數中替換「窗口」的含義,因爲在創建alert2時捕獲「窗口」,正如在定義func時捕獲「父」和「子」一樣。 –

2

您可以使用childWindow.opener來獲取打開子窗口的window對象。

alert2.call(childWindow.opener, "called from child using parent as context"); 

演示:http://jsfiddle.net/hJ7uw/8/

相關問題