问题
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>
回答1:
Did you try:
script.setAttribute('type', 'text/javascript');
script.innerHTML = 'alert(\'hello\')';
回答2:
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
来源:https://stackoverflow.com/questions/11000052/javascript-script-element-set-inner-text