title: Run code in context of frame window
body: <p>I'd like to run some javascript in the context of an iframe's window. Right now the only way I can think to do that is to inject a script tag:</p>
  
  <pre><code>myIframe = document.createElement('iframe');
  myIframe.setAttribute('name', 'xyz123');
  document.body.appendChild(myIframe);
  
  myIframe.contentWindow.document.write(`
      &lt;script&gt;
          console.log('The current window name is:', window.name);
      &lt;/script&gt;
  `);
  </code></pre>
  
  <p>Note: this is a same-domain iframe, without a src, so I have full access to the <code>contentWindow</code>.</p>
  
  <p>It's important for my use case that the code runs with the correct globals; <code>window</code>, <code>document</code> etc should all be scoped to the iframe itself.</p>
  
  <p>Is there any other way I can do this? The above works, but the script needs to run on different domains all with different CSP rules, which means adding support for nonces/hashes etc.</p>
  
  <p>Is it possible to do something like:</p>
  
  <pre><code>myIframe.contentWindow.run(function() {
      console.log('The current window name is:' window.name);
  });
  </code></pre>
  
  <p>I've tried <code>myIframe.contentWindow.setTimeout</code> but that still seems to run the code in the context of the parent window.</p>