Thursday, April 7, 2011

Modify iFrame Content Using JavaScript - Not Possible

It is not possible to modify the data loaded using iFrame. This is a security protection mechanism that disallow the user to do cross site scripting (XSS).
Imagine that if you are able to load a bank login page and then alter the form action to point to your own server? You cannot do that.
I saw some comments online said that it is possible to alter the content loaded by iFrame from the same domain. I tried today and it's not possible neither. Maybe someone can correct me and show me how.

What I did is I added a button to show the iFrame's innerHTML when clicked using jQuery. The theory is if I can retrieve the content of the iframe, I will be able to modify the content shown to the user.

<script language="JavaScript" type="text/javascript">
<input type="button" id="btn_show" value="show me"/>
<div class="ContentDetail" id="biIFrame" style="float: left; width: 100%;">
<iframe src="EXTERNAL_URL" height="800" id="iframe_window" width="100%">
  Content before loading the iframe

After the iFrame is completely loaded, I clicked the "show me" link and the alert box shows "Content before loading the iframe". Doesn't matter the 'EXTERNAL_URL' is from same domain or not, the iframe content retrieved by javascript is always the initial value. This demo shows that javascript engine is preventing user modifying the iFrame content. Sorry guys, it is just not safe to allow it.

1 comment :

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry.