【发布时间】:2015-03-31 20:38:34
【问题描述】:
我将内联 javascript 注入到预先存在的框架中。此 javascript 根本不会影响它所在的框架,而不是包含该框架的父 DOM。
我有一个 JSFiddle 来演示我的问题:http://jsfiddle.net/vfspadgt/
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
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);
结果
hi1 在 iFrame 中,hi2 在父 DOM 中。然而,注入 iFrame 的 javascript 会删除它不应该访问的 hi2,也不应该访问它用来删除它的 jQuery。
感谢您的帮助。
【问题讨论】:
-
您需要获取 iFrame 的
contentDocument,并在该范围内创建元素,而不是使用父窗口中的document。 -
我改变了 document.createElement("script");到 window.frames[0].document.createElement("script");但这并没有什么不同。我做错了吗?
标签: javascript jquery html dom iframe