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">
  $(document).ready(function(){ 
    $("#btn_show").click(function(event){
      event.preventDefault();
      alert($("#iframe_window")[0].innerHTML);
    });
  });
</script>
<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
</iframe>
</div>

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.

No comments :

Post a Comment