0

我正在编写一个脚本,它需要在 iframe 中执行一些内容。这是一个我不拥有的网站的用户脚本,所以由于跨域问题,我不能只使用我自己的代码将其设置为页面srciframe相反,我正在动态构建 iframe。

为此,我有

 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.$,但这当然不起作用,因为它只是反向引用父级$并操作父级文档。

4

1 回答 1

4

使用 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>
于 2012-05-15T06:57:13.670 回答