How to inject JavaScript into an iFrame

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

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.

Cheers,

 

 

VN:F [1.9.22_1171]
Rating: 5.0/5 (2 votes cast)
VN:F [1.9.22_1171]
Rating: +2 (from 2 votes)
How to inject JavaScript into an iFrame , 5.0 out of 5 based on 2 ratings

Speak Your Mind

*

CommentLuv badge