Hello,
This is not common but sometimes required because of variety of reasons. Without wasting much time into hows and whats lets jump on straight into the problem
The Problem
How do we inject, include JavaScript into an iFrame using JavaScript
Things to look for
You can only perform this task if the iFrame source is loaded from same domain. i.e. if you are running a site abc.com then iframe src could be abc.com/hello.html
The Markup
To be more clean on how to achieve this lets first of all do our markup
Example HTML
<iframe style="width:100%;height:100%;overflow:auto" name="myiframe" id="myiframe" onLoad="injectJS()" src="demo.html">IFrame is not supported</iframe>
Now lets go on an implement our function injectJS() this is the function that will be called when IFrame src is fully loaded.
The JavaScript
Okay so the injectJS() function looks like this.
Say you want to load a script called myscript.js
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); }
tada! that’s it.
There are a few use cases that I would do this in but I think the best way is to include the required scripts and styles in the source file it self.
I hope that this makes sense
If I missed any important stuff to mention please let me know so that other users are aware of this.
Cheers,
How to inject JavaScript into an iFrame ,





JC WordPress Coupon Revealer Plugin Pro License
Australian Street Names with City, State and Display Names only, Single Server License
Recent Comments