I want to run javascript in the context of an iframe window. Right now, the only way I can do this is to enter a script tag:
myIframe = document.createElement('iframe'); myIframe.setAttribute('name', 'xyz123'); document.body.appendChild(myIframe); myIframe.contentWindow.document.write(` <script> console.log('The current window name is:', window.name); </script> `);
Note: this is an iframe with the same domain without src, so I have full access to contentWindow .
For my use case, it is important that the code works with the correct global ones; window , document , etc. all should be tied to the iframe itself.
Is there any other way to do this? The above works, but the script should work in different domains with different CSP rules, which means adding support for nonces / hashes, etc.
Is it possible to do something like:
myIframe.contentWindow.run(function() { console.log('The current window name is:' window.name); });
I tried myIframe.contentWindow.setTimeout , but it still seems to run code in the context of the parent window.
source share