I am working working in a project(like Jsfiddle or codepen) where i have to constantly inject code in an iframe. The html and css code is working properly with out any problem. however, newly injected javascript code is not executing and has no effect on output.
Is there anyway to refresh(not the whole iframe) or re-execute javascript code in an iframe. If I inject all html content again to the iframe, Some of the scripts will not work. i.e AngularJS.
Iframe:
<iframe id="preview" sandbox="allow-scripts allow-same-origin allow-pointer-lock">
<html>
<head>
<title>Iframe demo</title>
<script>
// JS code will be injected here
</script>
</head>
<body>
</body>
</html>
</iframe>
JS (Jquery):
var content = "alert('Welcome to Stackoverflow');";
var jscode = $('#preview').contents().find('script:first');
jscode.html(content);
** Vanilla JS:**
var content = "alert('Welcome to Stackoverflow');";
var iframe = document.getElementById("preview");
var iframewindow = iframe.contentWindow || iframe.contentDocument.defaultView;
var doc = iframewindow.document;
var js = doc.getElementsByTagName("script")[0];
js.text( content );
I have tried both Jquery and vanilla js but unable to execute the injected JS code.