簡體   English   中英

將 javascript 函數注入 Iframe

[英]inject a javascript function into an Iframe

此鏈接存檔版本)描述了如何將腳本中的代碼注入 iframe:

function injectJS() {
  var iFrameHead = window.frames["myiframe"].document.getElementsByTagName("head")[0];
  var myscript = document.createElement('script');
  myscript.type = 'text/javascript';
  myscript.src = 'myscript.js'; // replace this with your SCRIPT
  iFrameHead.appendChild(myscript);
}

沒關系,但是如果我想將函數對象插入 iframe並讓它在 iframe 上下文中執行怎么辦? 假設我有:

function foo () {
    console.log ("Look at me, executed inside an iframe!", window);
}

我想在 iframe 中插入 foo 的代碼? 函數 foo 可能是動態加載的東西,我不能把它用引號括起來

我天真地嘗試:

var scriptFooString = "<script>" + foo.toString() + "</script>"

獲取函數內部的代碼,但是

  • 我不知道如何將它插入 iframe HEAD(也許用 jquery?)
  • 不知道這樣對不對
  • 我不知道當 if 函數比那更復雜時會發生什么
  • 我不知道scriptFooString雙引號和單引號會發生什么

任何提示?

首先,只有當您的框架和顯示它的頁面在同一個域中時,您才能完成此操作(由於跨域規則)

其次你可以直接通過JS操作框架的dom和window對象:

frames[0].window.foo = function(){
   console.log ("Look at me, executed inside an iframe!", window);
}

要從 DOMElement 對象中獲取您的框架,您可以使用:

var myFrame = document.getElementById('myFrame');

myFrame.contentWindow.foo = function(){
       console.log ("Look at me, executed inside an iframe!");
}

請注意,foo 中的范圍沒有改變,因此 window 仍然是 foo 中的父窗口等。

如果你想注入一些需要在另一個框架的上下文中運行的代碼,你可以注入一個腳本標簽,或者對其進行評估:

frames[0].window.eval('function foo(){ console.log("Im in a frame",window); }');

雖然普遍的共識是永遠不要使用 eval,但我認為如果你真的需要完成這個,我認為它比 DOM 注入更好。

因此,在您的特定情況下,您可以執行以下操作:

frames[0].window.eval(foo.toString());

這是我的解決方案。 我使用 jquery 插入內容,然后使用 eval 在該 iframe 的上下文中執行腳本標記:

    var content = $($.parseHTML(source, document, true));
    $("#content").contents().find("html").html(content);
    var cw = document.getElementById("content").contentWindow;
    [].forEach.call(cw.document.querySelectorAll("script"), function (el, idx) {
        cw.eval(el.textContent);
    });

這段代碼是我研究的結果。 接受的答案也對我有很大幫助。 首先,我創建了一個簡單的 iframe:

<iframe id="myiframe" width="200" height="200" srcdoc="<h1 id='title'>Hello from Iframe</h1><button type='button' id='fire'>Click Me!</button>
"></iframe>

為了訪問 iframe 的窗口和文檔,我使用了此代碼。

const iframe = document.getElementById('myiframe');
const iframeWin = iframe.contentWindow || iframe;
const iframeDoc = iframe.contentDocument || iframeWin.document;

最后我在 iframe 中注入了 js 代碼:

var script = iframeDoc.createElement("script");
  script.append(`
    window.onload = function() {
     document.getElementById("fire").addEventListener('click', function() {
        const text = document.getElementById('title').innerText;
        alert(text);
     })
  }
`);
  iframeDoc.documentElement.appendChild(script);

演示: https : //jsfiddle.net/aliam/1z8f7awk/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM