javascriptiframeeval

How to execute the eval function with a modified window object


I make a call to eval in my code, and I have a reference to an iframe's window object. Is there any way to execute eval (or something that achieves the same) but have the window object set to the iframe.contentWindow for all code executed by eval. I need to retain access to the window in the rest of the code.


Solution

  • Don't use the normal eval, but the eval function from the iframe's realm:

    iframe.contentWindow.eval(…)
    

    Notice that this runs the code in the global scope of the iframe, not in the current scope. And all literals will create instances of the respective Object, Array, RegExp objects from the iframe realm as well, which might cause some annoyances.