2015-04-25 56 views
0

我可以注入這樣一個iframe:如何將在父頁面中聲明的函數注入到iframe中,然後調用它?

iframe.contentWindow.action... 

但是,如果我要發送要在iframe中聲明的函數,然後叫什麼?

例如

function hello(){...} 
iframe.contentWindow... 

基本上都是從iframe中聲明並調用hello

只是爲了澄清,hello的行爲應該在iframe中完成。例如,如果我將document.getElementById("input").value="foo";放在hello的內部,然後在iframe內調用它,則更改應該在iframe內而不是在父窗口內在input之內生效。

回答

3

將腳本標記插入框架的<head>部分,其中包含代碼。腳本標記可以是外部腳本引用或內聯腳本。你必須是相同的來源才能進行注射。

var idoc = iframe.contentWindow.document; 
var script = idoc.createElement("script"); 
script.textContent = 'document.getElementById("input").value="foo";' 
idoc.getElementsByTagName("head")[0].appendChild(script); 
+0

如何將我的函數的內容轉換爲字符串? – DaemonOfTheWest

+0

@DaemonOfTheWest - 你可以在函數中調用'.toString()'來獲得一個字符串表示。 – jfriend00

+0

好的,謝謝! – DaemonOfTheWest

相關問題