How to inject JavaScript into an iFrame


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 then iframe src could be



The Markup

To be more clean on how to achieve this lets first of all do our markup

Example HTML

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

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.





  1. The script I’d like to inject is very short. Is there a way to avoid using a separate “myscript.js” file? Thanks!

  2. very nice

  3. good job boss

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.