Frank Cheng
Frank Cheng

Reputation: 6186

Can i inject javascript into iframe?

<html>
    <head>
        <link rel="stylesheet" href="my.css" />
    </head>
    <body>
        <iframe id="baidu-container" src="http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1374487244324_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=giant" frameborder="0">
        </iframe>
        <script type="text/javascript" src="my.js"></script>
    </body>
</html>

I would like to execute the script in my.js after this iframe has loaded completely. So what shoud i do? Thanks.

Upvotes: 0

Views: 4893

Answers (3)

carl-lopez
carl-lopez

Reputation: 582

You can use the onload event on the iframe:

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

Upvotes: 1

sabof
sabof

Reputation: 8192

Answering the question in the title. If the page inside the iframe is from another domain, you can't. Otherwise:

function addScript() {
  var iframeDoc = iframe.contentDocument;
  var s = iframeDoc.createElement('script');
  s.type = 'text/javascript';
  s.src = 'my.js';
  iframeDoc.body.appendChild(s);
}

// I'm creating the iframe programmatically, to make sure the onload handler fires.
var iframe = document.createElement('iframe');
iframe.width = 300;
iframe.height = 100;
iframe.onload = addScript;
iframe.src = "iframe-test2.html";
document.body.appendChild(iframe);

Upvotes: 1

user2587420
user2587420

Reputation: 60

<html>
    <head>
        <link rel="stylesheet" href="my.css" />
    </head>
    <body>
        <iframe id="baidu-container" src="http://image.baidu.com/i?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1374487244324_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=giant" frameborder="0">
        </iframe>
        <script>
          window.document.getElementById("baidu-container").onload = function() {
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.src = "my.js";
            window.document.head.append(s);
          }
        </script>
    </body>
</html>
  1. Listen to the iframe load event.
  2. When the iframe document is loaded then add/execute your JavaScript code.

Upvotes: 1

Related Questions