2012-05-15 69 views
0

我正在寫一個腳本,它需要在iframe中執行一些內容。這是一個我不擁有的網站的用戶腳本,因爲跨域問題,我不能只將iframesrc設置爲帶有我自己的代碼的頁面。相反,我正在動態構建iframe。在iframe中加載jQuery

要做到這一點,我有

function childScripts(){ 
    //Stuff that must be injected into the iframe. 
    //Needs jQuery 
} 


//because I'm lazy: 
var iframeWin=$('#my-iframe')[0].contentWindow; 

//Load jQuery: 
var script = iframeWin.document.createElement("script"); 
script.type = "text/javascript"; 
script.src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" 
iframeWin.document.head.appendChild(script); 

//Inject script 
var script = iframeWin.document.createElement("script"); 
script.type = "text/javascript"; 
script.textContent="("+childScripts.toString()+")()"; 
iframeWin.document.body.appendChild(script); 

現在,注入腳本需要jQuery的,但由於某些原因,jQuery的未加載當注入的腳本運行 - 即使jQuery是在<head>和注入腳本在<body>

我試過其他解決方法 - 使注入的腳本運行onload。我不喜歡設置超時並檢查jQuery的存在的想法,我更喜歡更優雅的解決方案。

我也嘗試將$對象複製到iframeWin.$,但當然這不起作用,因爲它只是反向引用父代$並操縱父文檔。

回答

2

使用jQuery處理iframe更容易。請嘗試:

$('<iframe id="my-iframe"/>').load(function(){ 
    $('#my-iframe').contents().find('body').append('asd').end() 
          .find('body').append('<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"><\/script>').end() 
          .find('body').append('<script>$(function() {alert("hello from jquery");console.log("hello from jquery"); })<\/script>');        

}).appendTo("body"); 

放置:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> 
    <script> 
     $('<iframe id="my-iframe"/>').load(function(){..... 
    </script> 
</body> 
</html> 
+0

什麼是'asd'呢? – Manishearth

+0

你可以忽略''asd'',忘記刪除它。我用它來測試iframe,然後插入腳本標記。 –

+0

由於某些原因,腳本不會被附加到_all_。如果我刪除'load',然後附加東西 - 但腳本仍然被剝離。 O_0 – Manishearth