inject a javascript function into an Iframe

First of all you can only accomplish this if your frame and the page displaying it is within the same domain (Due to cross-domain rules)

secondly you can manipulate dom and window objects of the frame directly through JS:

frames[0].window.foo = function(){
   console.log ("Look at me, executed inside an iframe!", window);
}

to get your frame from a DOMElement object you can use:

var myFrame = document.getElementById('myFrame');

myFrame.contentWindow.foo = function(){
       console.log ("Look at me, executed inside an iframe!");
}

Note that the scope in foo is NOT changed, so window is still the parent window etc. inside foo.

If you want to inject some code that needs to be run in the context of the other frame you could inject a script tag, or eval it:

frames[0].window.eval('function foo(){ console.log("Im in a frame",window); }');

Though the general consensus is to never use eval, I think its a better alternative than DOM injection if you REALLY need to accomplish this.

So in your specific case you could do something like:

frames[0].window.eval(foo.toString());

Leave a Comment