Javascript script element set inner text

杀马特。学长 韩版系。学妹 提交于 2019-12-05 12:52:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!