Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript script element set inner text

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>
like image 786
VSP Avatar asked Jun 12 '12 15:06

VSP


People also ask

How do I change the inner text of a div?

const div = document. getElementById('container'); // ✅ Change (replace) the text with HTML div. innerHTML = `<span style="background-color: lime">Replacement HTML</span>`; The innerHTML property gets or sets the HTML contained within the element.

Can innerHTML contains JavaScript?

It is possible to execute JavaScript via innerHTML without using tags as illustrated on MDN's innerHTML page. To dynamically add a script tag, you need to create a new script element and append it to the target element.

Should I use innerText or textContent?

textContent gets the content of all elements, including <script> and <style> elements. In contrast, innerText only shows "human-readable" elements. textContent returns every element in the node. In contrast, innerText is aware of styling and won't return the text of "hidden" elements.


1 Answers

Did you try:

script.setAttribute('type', 'text/javascript');
script.innerHTML = 'alert(\'hello\')';
like image 117
Praveen Kumar Purushothaman Avatar answered Sep 28 '22 09:09

Praveen Kumar Purushothaman