August 29, 2013

How to change content of website loaded in iframe?

Ivan.daragan’s Question:

I need to change content of website using jQuery loaded in iframe from other domain such this:

<html>
  <head>
  </head>
  <body>
    <iframe src="site.com/somepage.html></iframe>
    <script>
      $('iframe').find('div#message').value('hello');
    </script>
  </body>
</html>

Also I added target link to whitelist.
Could any helps? Thanks.

Your script is running during runtime so it will not find the DOM of the iframe and will break. What you can do is create a function on your parent page like:

//On Your Parent page
function modifyIframeContent() {
     $('iframe').find('div#message').value('hello');
}

Then call this function from the iframe after it loads.

// On Your Iframe page
window.onload = function() {
    parent.modifyIframeContent();
}

Of course: Your iframe must be of same domain for this work.

...

Please fill the form - I will response as fast as I can!