title: inject a javascript function into an Iframe
body: <p><a href="http://jaspreetchahal.org/how-to-inject-javascript-into-an-iframe/" rel="noreferrer">This link</a> (<a href="http://web.archive.org/web/20160922170751/http://jaspreetchahal.org/how-to-inject-javascript-into-an-iframe/" rel="noreferrer">archived version</a>) describes how to inject code from a script into an iframe:</p>
  
  <pre><code>function injectJS() {
    var iFrameHead = window.frames["myiframe"].document.getElementsByTagName("head")[0];
    var myscript = document.createElement('script');
    myscript.type = 'text/javascript';
    myscript.src = 'myscript.js'; // replace this with your SCRIPT
    iFrameHead.appendChild(myscript);
  }
  </code></pre>
  
  <p>That's ok, but what if I want to insert a function object into an iframe <em>and get it executed in the iframe context</em>? Let's say I have:</p>
  
  <pre><code>function foo () {
      console.log ("Look at me, executed inside an iframe!", window);
  }
  </code></pre>
  
  <p>and I want to insert foo's code inside an iframe? (<strong>function foo could be something loaded dynamically, I can't just wrap it in quotes</strong>)</p>
  
  <p>I naively tried:</p>
  
  <p><code>var scriptFooString = "&lt;script&gt;" + foo.toString() + "&lt;/script&gt;"</code></p>
  
  <p>to get the code inside function, but</p>
  
  <ul>
  <li>I don't know how to insert it in the iframe HEAD (maybe with jquery?)</li>
  <li>I don't know if it's the right way</li>
  <li>I don't know what happens when if function is way more complex than that</li>
  <li>I don't know what happens with double and single quotes in <code>scriptFooString</code></li>
  </ul>
  
  <p>Any hint?</p>