Javascript script element set inner text

VSP picture VSP · Jun 12, 2012 · Viewed 30.5k times · Source

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>

Answer

Praveen Kumar Purushothaman picture Praveen Kumar Purushothaman · Jun 12, 2012

Did you try:

script.setAttribute('type', 'text/javascript');
script.innerHTML = 'alert(\'hello\')';