Reputation: 892
I am injecting inline javascript into a pre-existing frame. This javascript is not affecting the frame it's in at all, rather than parent DOM containing the frame.
I have a JSFiddle demonstrating my issue: 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);
Results
hi1 is within the iFrame and hi2 is within the parent 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.
Thanks for your help.
Upvotes: 0
Views: 1147
Reputation: 892
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. To make the script only be executed within the iFrames DOM was to write directly to it.
I was also creating the script element with the parent document thus giving them a relationship.
$("#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();
});
Upvotes: 1