简体   繁体   English

iFrame JavaScript会影响父DOM

[英]iFrame javascript affecting parent DOM

I am injecting inline javascript into a pre-existing frame. 我正在将嵌入式javascript注入到预先存在的框架中。 This javascript is not affecting the frame it's in at all, rather than parent DOM containing the frame. 此javascript根本不影响框架,而不是包含框架的父DOM。

I have a JSFiddle demonstrating my issue: http://jsfiddle.net/vfspadgt/ 我有一个JSFiddle演示了我的问题: http : //jsfiddle.net/vfspadgt/

HTML HTML

<iframe class="editor" id="preview" name="result" sandbox="allow-forms allow-popups allow-scripts allow-same-origin" frameborder="0">
#document
<!-- Editor content goes here -->
</iframe>

<div class=".dropdown">
    <p>hi2</p>
</div>

JavaScript JavaScript的

var preview = $("#preview").contents();

var css = "<style type='text/css'></style>";

var html = "<p>hi1</p>";
preview.find("head").html(css);

var script   = document.createElement("script");
script.type  = "text/javascript";
script.text  = "$('p').remove();";
preview.find("head").append(script);

preview.find("body").html(html);

Results 结果

hi1 is within the iFrame and hi2 is within the parent DOM. hi1在iFrame中, hi2在父DOM中。 The javascript injected into the iFrame however removes hi2 which it should not have access to, nor should it have access to the jQuery it's using to delete it. 但是,注入到iFrame中的javascript会删除它不应该访问的hi2 ,也不应访问它用来删除它的jQuery的访问权。

Thanks for your help. 谢谢你的帮助。

I was able to fix this myself. 我自己能够解决此问题。 The problem was that appending the script to be within the iFrame wasn't enough to make it work. 问题在于,将脚本附加到iFrame中不足以使其正常工作。 To make the script only be executed within the iFrames DOM was to write directly to it. 要使脚本仅在iFrames DOM中执行,是直接对其进行写入。

I was also creating the script element with the parent document thus giving them a relationship. 我还在父文档中创建了script元素,从而给了他们一个关系。

$("#btnRun").click(function(event) {  
    event.preventDefault();

    var previewDoc = window.frames[0].document;

    var css    = ace.edit("css-editor").getSession().getValue();
    var script = ace.edit("js-editor").getSession().getValue();
    var html   = ace.edit("html-editor").getSession().getValue();

    previewDoc.write("<!DOCTYPE html>");
    previewDoc.write("<html>");
    previewDoc.write("<head>");
    previewDoc.write("<style type='text/css'>" + css + "</style>");
    previewDoc.write("<script type='text/javascript'>window.onload = function() {" + script + "}</script>");
    previewDoc.write("</head>");
    previewDoc.write("<body>");
    previewDoc.write(html);
    previewDoc.write("</body>");
    previewDoc.write("</html>");
    previewDoc.close();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM