2017-10-18 82 views
1

我想在父窗口(到iframe)的窗口中運行javascript。我完全控制了iframe內容,但不能直接在父窗口中加載腳本。在父窗口的上下文中運行腳本

使用案例:父頁面包含菜單項,並根據菜單選項加載iframe內容。我需要在iframe中加載一個腳本,並在父窗口的上下文中執行它,以便即使我導航我們的iframe也能保持活動/持久性。相同的域。

image

DOM腳本注入的作品,但我不知道是否有更好的解決方案。

+0

Upvoted的例證。 –

+0

因此,將腳本注入父項 – epascarello

+0

腳本注入工作正常,但審計不喜歡。這就是爲什麼我正在尋找其他選項(如果有的話)...甚至是複雜的,但沒有腳本注入。 –

回答

0

不確定此解決方案在您的案例中是否面臨任何限制。嘗試加載JS腳本在您的iFrame內容:

<script src="iframed.js"></script>

iframed.js

和內:

// call function with context of parent window, and pass window and document as parameters. 
foo.call(window.parent, window.parent, window.parent.document); 

function foo(window, document) { 
    // now you can access all globals from the main window: 
    var target = document.getElementsByTagName('iframe'); 
    // logs collection of iframes from the main window: 
    console.log('iframes from main window:', target); 
    // global context is main window 
    console.log('global context: ', this); 
} 
相關問題