【问题标题】:Can't keep script isolated to iframe无法将脚本与 iframe 隔离
【发布时间】:2017-01-15 22:11:50
【问题描述】:

我在 iframe 中有一个脚本,它使用 jquery 查找元素,但是当它运行时,它只找到 iframe 之外的元素,而不是 iframe 内部的元素。

请帮助我将脚本隔离为仅在 iframe 内执行。

我这里有例子:my example

说明我的例子的图片:

我如何创建 iframe,如链接示例中所示:

//Head to iframe:
var head = '<meta charset="utf-8">' +
  '<meta http-equiv="X-UA-Compatible" content="IE=edge">' +
  '<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' +
  '<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script>';

//Body to iframe that contains a script that I would like only to run inside the iframe:
var body = '<code id="codeInside">code tag inside</code>' +
  '<script>var codeTag = $("code").text("TAG FOUND!!");<\/script>';

//Insert the iframe:
var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body'));
iframe.contents().find('head').html(head); //Append head til the iframe
iframe.contents().find('body').html(body); //Append body to the iframe

【问题讨论】:

  • 在此处发布您的代码,而不是作为指向其他网站的链接。
  • 等等,什么?你使用 javascript 来附加执行 javascript 的 javascript,为什么?

标签: javascript jquery iframe


【解决方案1】:

我知道了:a working solution

//Head to iframe:
    var head = '<head><meta charset="utf-8">' +
      '<meta http-equiv="X-UA-Compatible" content="IE=edge">' +
      '<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">' +
      '<script src="http://code.jquery.com/jquery-1.10.2.js"><\/script></head>';

    //Body to iframe that contains a script that I would like only to run inside the iframe:
    var body = '<body><code id="codeInside">code tag inside</code>' +
      '<script>var codeTag = $("code").text("TAG FOUND!!"); console.log("codeTag", codeTag);<\/script></body>';

    //Insert the iframe:
    var iframe = $('<iframe src="javascript:\'\'">').appendTo($('body'));

    var doc = iframe[0].contentWindow.document;
    doc.open();
    doc.write(head);
    doc.write(body);
    doc.close();

【讨论】:

    【解决方案2】:

    你有没有尝试过正常的做法

    var codeTag = iframe.contents().find("code").text("TAG FOUND!!"); console.log("codeTag", codeTag);
    

    【讨论】:

    • 不幸的是,这在我的情况下不起作用。我必须使用解释的设置,因为我正在为用户编写一些 html 和 javascript,然后在插入的 iframe 中查看结果 - 有点像 jsfiddle.net 所做的那样。所以用户应该能够编写普通的 javascript 而不会考虑它会在 iframe 中执行。
    • 另一个可能有帮助的问题stackoverflow.com/questions/13247798/…
    • 谢谢。我现在已经阅读了您发送的链接并尝试了一些没有运气的建议。这让我回到了我原来的问题——我怎样才能让 jquery 在 iframe 中运行。如果我能把它炒起来,我可以做剩下的。
    • 保存并重新加载 iframe 可能会更好
    猜你喜欢
    • 2011-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2023-03-16
    • 2022-08-17
    • 2017-05-22
    • 1970-01-01
    相关资源
    最近更新 更多