title: How can I execute code in an iFrame's onload event?
body: <p>I am currently using Ace (<a href="http://ace.c9.io/" rel="nofollow">http://ace.c9.io/</a>) to take code from an editor and execute it within an iFrame. My issue is that when I add something along the lines of</p>
  
  <p><strong>Code in Editor</strong></p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      window.onload = function() {
          alert("hello");
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>to the <em>head</em> or <em>body</em> of the iFrame, the code is never executed. This is my current code:</p>
  
  <p><strong>Injecting Code into iFrame</strong></p>
  
  <pre><code>$("#btnRun").click(function(event) {  
      event.preventDefault();
  
      // iFrame with id="preview"
      var preview = $("#preview").contents();
  
      // Get code from editor and wrap in &lt;script&gt; tags
      var script = "&lt;script type='text/javascript'&gt;" + ace.edit("js-editor").getSession().getValue()  + "&lt;/script&gt;";
  
      // Append code to head or body, in this case head
      preview.find("head").append(script);
  });
  </code></pre>
  
  <p>The code is successfully added to the iFrame, however it is never executed. I can also successfully add HTML/CSS and it displays in the iFrame, but the javascript is never touched.</p>
  
  <p>I have tried wrapping the code in script tags within the editor only, as well as using an escape character on the closing tag: "&lt;/script>" but to no avail.</p>
  
  <p>This is the iFrame in my index.html document.</p>
  
  <p><strong>iFrame in index.html</strong></p>
  
  <pre><code>&lt;iframe class="editor" id="preview" name="result" sandbox="allow-forms allow-popups allow-scripts allow-same-origin" frameborder="0"&gt;
      #document
      &lt;!-- Editor content goes here --&gt;
  &lt;/iframe&gt;
  </code></pre>
  
  <p>After the code is injected the iFrame looks like this</p>
  
  <p><strong>iFrame with Injected Code</strong></p>
  
  <pre><code>&lt;iframe class="editor" id="preview" name="result" sandbox="allow-forms allow-popups allow-scripts allow-same-origin" frameborder="0"&gt;
      #document
      &lt;html&gt;
        &lt;head&gt;
          &lt;script type="text/javascript"&gt;
            window.onload = function() {
              alert("hello");
            }
          &lt;/script&gt;
        &lt;/head&gt;
      &lt;body&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  &lt;/iframe&gt;
  </code></pre>
  
  <p>Also when calling the <em>window.onload</em> or <em>window.top.onload</em> event from within the iFrame, the code executes but only affects the page containing the iFrame and not the contents of the iFrame itself.</p>
  
  <p>Thank you.</p>
  
  <p><strong>Note</strong>: When the code is not within <em>window.onload</em> it runs fine. However I wish to be able to execute this code when the frame's <em>onload</em> function is executed.</p>