Friday, February 1, 2013

Javascript to Change Div & Body Style in IFrame

Before showing the codes, here are the conditions that these codes WON'T work:
  • Run with Chrome in localhost environment
  • Cross domain for the main HTML and dummy.html in your iframe. These codes have to comply with the same domain policy or hackers will be very happy if it is not


The Main HTML:


<iframe id="myFrame" scrolling="no" style="overflow: hidden; height: 580px; width: 325px;"
src="dummy.html"></iframe>

<script>

function changeColor() {

    document.getElementById('myFrame').contentWindow.document.getElementById('divInDummy').
style.backgroundColor = '#123456'; // myFrame is the name of your iframe,
divInDummy is the DIV name in the iframe


    document.getElementById('myFrame').contentWindow.document.body.style.backgroundColor = "#234567";
// change the body color of iframe

}

changeColor();

</script>




The dummy.html:



<html>

<body bgcolor="#ccaaee">

Hello World! My name is dummy.html
<div id=divInDummy style="background:#55aadd;width:120px;height:120px">
<table><tr><td><br> <br><br>I am inside a DIV<br><br>
</td></tr></table>
</div>

</body>

</html>



If you think the dummy.html is not able to load before you call the script, you can put it in an interval loop to make sure the function is called successfully eventually. Here's the code: setInterval('changeColor()', 1000);

No comments:

Post a Comment