2012-11-27 78 views
2

下面是一個例子有沒有辦法找出哪個iframe呼籲父母的JavaScript函數

parent.html

<script> 
function printWhoCalledMe() { 
    console.log(???); // what goes here that will identify the caller? 
} 
<iframe src="iframe1.html"></iframe> 
<iframe src="iframe2.html"></iframe> 

iframe1.html

<script> 
window.parent.printWhoCalledMe(); 
</script> 

iframe2.html

<script> 
window.parent.printWhoCalledMe(); 
</script> 

T他更大的問題是,I have a test harness that runs a bunch of tests, one at a time, in an iframe。每個測試呼叫window.parent.reportOnTest(success)

我尋找到在超過1個iframe中運行它們並行測試,但我必須要經過各項測試,目前1000周的測試,並從window.parent.reportOnTest(success)改變他們的呼籲像window.parent.reportOnTest(success, window.location.href)或類似的東西。

我想知道是否有一種方式沒有修改測試,找出哪些測試調用到父項。

注:我試過

function printWhoCalledMe() { 
    console.log(window.location.href); 
} 

但這打印父的href。

+0

可能值得通過'arguments.callee.caller'調查某些東西,但我不確定如果該函數的窗口對象可用於該路由,那麼我不確定關閉我的頭頂部。 –

回答

0

我很擔心,你可能需要使用字符串值這樣的..

function printWhoCalledMe(callerPage) { 
    console.log(callerPage); // what goes here that will identify the caller? 
} 

你可以叫你的孩子這個函數就是那樣的參數框架..

iframe1.html

<script> 
window.parent.printWhoCalledMe("iframe1"); 
</script> 

iframe2.html

<script> 
window.parent.printWhoCalledMe("iframe2"); 
</script> 
0

如果調用使用apply父功能,您可以在上下文更改框架window

window.parent.printWhoCalledMe.apply(this); 

function printWhoCalledMe() { 
    console.log(this); // this now refers to the frame window 
} 
0

所以哈克,但你可以使用這樣的事情:

  1. 使用caller去參考這個函數叫你想要的功能。
  2. 繼續使用Object.getPrototypeOf,直到達到該領域的Object.prototype
  3. 迭代所有框架窗口,並比較Object.prototype
  4. 一旦找到匹配項,請使用frameElement來獲取iframe。

這需要sameorigin,沒有沙箱和馬虎模式。例如:

window.func = function func() { 
    var proto, nextProto = func.caller; 
    while (nextProto) { 
    proto = nextProto; 
    nextProto = Object.getPrototypeOf(proto); 
    } 
    var win = [].find.call(window.frames, function(win) { 
    try { 
     return win.Object.prototype === proto; 
    } catch(err) { 
     return false; 
    } 
    }); 
    if (win) { 
    var iframe = win.frameElement; 
    console.log("function called from frame " + iframe.name); 
    } 
}; 
var iframe = document.createElement('iframe'); 
iframe.name = "myframe"; 
document.body.appendChild(iframe); 
var doc = iframe.contentDocument; 
var script = doc.createElement('script'); 
script.text = "(function f(){parent.func()})()"; 
doc.body.appendChild(script); 
// Logs "function called from frame myframe" 
相關問題