简体   繁体   中英

javascript adding javascript to iframe dynamically

The code below will add an iframe dynamically, is there a way to insert javascript to this iframe dynamically?

Thx

  var iFrame = document.createElement('iframe');
  var iFrameSRC = "http://www.google.com";
  iFrame.name = 'hehe';
  iFrame.id = 'hehe';
  iFrame.src = iFrameSRC;
  iFrame.width = '1px';
  iFrame.height = '1px';
  iFrame.frameBorder = 0;
  iFrame.style.overflow = "hidden";
  iFrame.style.align = "left";
  iFrame.style.display = "block";
  iFrame.style.fontSize = "10px";

  bodyInner.appendChild(iFrame);

I think it will be something like this:

var script=iframe.createElement('script');

    script=iframe.standardCreateElement('script');
    script.setAttribute('src','http://localhost/jquery-1.3.2.js');
    script.setAttribute('type','text/javascript');
    iframe.lastChild.firstChild.appendChild(script);

Note this can be done just if the iframe and the holder page are in the same domain, or if you calling this from a bookmarklet or a browser extension/plugin.

This should work... Maybe you are trying to create something like this:

<body onload="initialize()">
<script language="JavaScript">
function initialize() {
  var testFrame =
        document.createElement("IFRAME");
  testFrame.id = "testFrame";
  testFrame.name = 'hehe';
  testFrame.src = "http://www.seekload.tk";
  testFrame.style.border='20px';
  testFrame.style.width='900px';
  testFrame.style.height='300px';
  testFrame.style.frameBorder = 10;
  testFrame.style.overflow = "hidden";
  testFrame.style.align = "left";
  testFrame.style.display = "block";
  testFrame.style.fontSize = "10px";
  document.body.appendChild(testFrame);
}
</script>

PS: You made some mistakes in your coding try the above instead.

No, you cannot insert code into a document from another domain. This is a security measure enforced by the browser to prevent cross-site scripting (XSS) and phishing attacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM