在 iframe 中加载 jQuery

Man*_*rth 1 html javascript iframe jquery

我正在编写一个脚本,需要在 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);
Run Code Online (Sandbox Code Playgroud)

现在,注入的脚本需要 jQuery,但由于某种原因,当注入的脚本运行时,jQuery 不会被加载——即使 jQuery 位于<head>并且注入的脚本位于 <body>.

我尝试了其他解决方法——使注入的脚本运行onload。我不喜欢设置超时并检查 jQuery 是否存在的想法,我更喜欢更优雅的解决方案。

我还尝试将$对象复制到iframeWin.$,但这当然不起作用,因为它只是反向引用父级$并操作父级文档。

Ard*_*ase 5

使用 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");
Run Code Online (Sandbox Code Playgroud)

放置:

    <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>
Run Code Online (Sandbox Code Playgroud)