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>
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.
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.
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.
Did you try:
script.setAttribute('type', 'text/javascript');
script.innerHTML = 'alert(\'hello\')';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With