18

We need to add a javascript element inside an iframe (its inside the same web/domain so no security problems attached). We got it working but dont know how to fill the script content betwen its tags...how would you do it?

var iframe = document.getElementById('iframeX');
var iframedocument = iframe.contentWindow.document;

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

script.setAttribute('type', 'text/javascript');
script.innerText = 'alert(\'hello\')'; //this doesnt work
script.value= 'alert(\'hello\')'; //this doesnt work either

var head = iframedocument.getElementsByTagName("head")[0];

head.appendChild(script);

Desired result in the iframe document:

<head>
    <script type="text/javascript" >
        alert('hello');
    </script>
</head>
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
VSP
  • 2,367
  • 8
  • 38
  • 59

2 Answers2

22

Did you try:

script.setAttribute('type', 'text/javascript');
script.innerHTML = 'alert(\'hello\')';
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
4

I had problem with script.innerHTML as it doesn't work in IE8-.

script.text = 'alert(\'hello\')';

script.text works better for me. Found on: Create script tag in IE8

Community
  • 1
  • 1
Maju
  • 616
  • 4
  • 9