如何在 iframe 中插入动态 JavaScript 标签

sca*_*der 5 javascript iframe jquery

最终更新:第二个代码块正在运行——我只是漏输入了 URL。

我正在尝试将动态创建的脚本放入 iframe 中。我可以访问 iframe 的头部,但它似乎不接受追加请求。控制台日志调用返回 head 标记,并且以下将文本附加到正文中效果很好。我还尝试将脚本标签附加到正文。(注意:脚本标记不在同一域中,因此我避免使用 getScript 或 ajax)。

$(document).ready(function() {
  $('<iframe></iframe>', {
      name:"contentFrame"
      ,id:"contentFrame"
  }).css("height", 300).css("width", 500).load(function() {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "//cross-domain.com/script.js";
      console.log($(this).contents().find("head")); // outputs: [<head></head>]
      $(this).contents().find("head").append(script); // doesn't work
      $(this).contents().find("body").append(script); // doesn't work
      $(this).contents().find("body").append("Test"); // works
  }).appendTo("#content");
});
Run Code Online (Sandbox Code Playgroud)

这是根据以下建议成功附加脚本的新版本,但该脚本不会评估(通过简单警报进行测试)。另外,另一个奇怪的地方是:“正在工作”图标显示大约 15 秒,状态(在 Chrome 中)显示“正在检索...”最终它停止了,但没有任何反应。

    $(document).ready(function() {
  $('<iframe></iframe>', {
      name:"contentFrame"
      ,id:"contentFrame"
  }).css("height", 300).css("width", 500).load(function() {
      var script   = document.createElement("script");
      script.type  = "text/javascript";
      script.src   = "//cross-domain.com/script.js";
      console.log($(this).contents().find("head"));
      $(this).contents().find("head")[0].appendChild(script);
      $(this).contents().find("body").append("Test");
  }).appendTo("#content");
});
Run Code Online (Sandbox Code Playgroud)

更新:当光标图标最终完成工作时(大约 10 秒,这很奇怪,因为它是具有一行代码的本地服务器),我在 Chrome 控制台中收到此消息(它是全红色的,带有红色圆圈“X”图标在它的旁边):

GET http://cross-domain.com/script.js 
(anonymous function)temp.html:16
jQuery.event.dispatchjquery-1.7.1.js:3261
jQuery.event.add.elemData.handle.eventHandlejquery-1.7.1.js:2880
jQuery.fn.extend.appendjquery-1.7.1.js:5771
jQuery.fn.extend.domManipjquery-1.7.1.js:5973
jQuery.fn.extend.appendjquery-1.7.1.js:5769
jQuery.each.jQuery.fn.(anonymous function)jquery-1.7.1.js:6162
(anonymous function)temp.html:18
jQuery.Callbacks.firejquery-1.7.1.js:1049
jQuery.Callbacks.self.fireWithjquery-1.7.1.js:1167
jQuery.extend.readyjquery-1.7.1.js:435
DOMContentLoaded
Run Code Online (Sandbox Code Playgroud)

Pau*_*sey 3

请参阅此答案/sf/answers/252244751/

它实际上可能有效,但脚本标签不可见。