我有以下 iFrame:
<div id="sandbox-inner">
<iframe sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts" frameborder="0" name="Output " id="output" src="JavaScript:''"></iframe>
</div>
当用户单击运行其代码时,它会在此 iframe 中成功注入(inject) javascript。然而,它实际上在整个窗口上运行,而不仅仅是 iframe。所以基本上,如果我向 iframe 外部的一个元素添加一个类“test”,然后向 iframe 内部的一个元素添加一个类“test”,然后将以下内容注入(inject) iframe 的头部...
$(function() {
$('.test').css({ background: "blue" });
});
它也会影响 iframe 之外的元素,这是我真的不想要的。我需要 iFrame 成为一个完全独立的环境。这就是我目前注入(inject) javascript 的方式:
$('#runGuestCode').on("click", function () {
var js = $('#js-input').val(),
iframe = $("#output"),
iframeHead = iframe.contents().find("head").first(),
frame = document.getElementById("output"),
scriptTag = '<script>' + js + '<\/script>';
$('#output').contents().find("head").append(scriptTag);
});
非常感谢
更新#1
javascript 取自文本区域 #js-input,即用户输入的内容。然后将其附加到 iframe 的头部,但当前相对于父文档而不是 iframe 文档运行。
最佳答案
您可以按照以下方式执行此操作,这不会影响您当前的页面元素仅适用于 iframe 元素:-
var iframe = $('iframe');
$(element, iframe.contents()).css({'background':'blue'});
<强> Working Fiddle
展示用户在 iframe 中放置的 JavaScript 代码:
$('#submit1').click(function (e) {
e.preventDefault();
var myIframe = document.getElementById("resultFrame");
var s = document.createElement("script");
s.type = "text/javascript";
s.innerHTML = $("#textarea1").val();
myIframe.contentWindow.document.head.appendChild(s);
});
关于javascript - 如何仅相对于该框架而不是整个窗口执行 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27656458/