views:

40

answers:

2

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);
+1  A: 

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.

Emil Vikström
A: 

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.

Amr ElGarhy