0

I'm trying to add a JavaScript file to the header of an iframe so that upon loading, the iframe can before a "background task" for me. Currently the iframe is empty, because there is no source I want it to display. Namely, all the iframe will do is perform the script I wish to supply to it.

I have tried suggestions from here:

  1. Can't append <script> element
  2. Insert a Script into a iFrame's Header, without clearing out the body of the iFrame
  3. Invoking JavaScript code in an iframe from the parent page
  4. Calling javascript function in iframe
  5. http://www.getallfix.com/2013/08/how-to-include-or-add-external-javascript-file-to-iframe-how-to-add-js-to-iframe/

Yet I cannot get a simple "write" to the iframe to work. Here's the code I am working with:

demo.html

<html>
<head>
<script src="demo.js"></script>  

<script>  
addScript('demo.js');  

function addScript(src){
// Find the iFrame
var iframe = document.getElementById('test');
var val = '<scr' + 'ipt type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></scr' + 'ipt>';

var headID = iframe.getElementsByTagName("head")[0];         

var newScript = iframe.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'demo.js';
headID.appendChild(newScript);

</script>  
</head>
<body>
    <div class="output">  
        <iframe id="test"></iframe>  
    </div>
</body>
</html>

demo.js

document.write("Hello, I'm a Demo.");
Community
  • 1
  • 1
user2958542
  • 331
  • 1
  • 8
  • 18

2 Answers2

1

You can add directly the content string

http://jsfiddle.net/0m5axpxx/

var iframe = document.createElement('iframe');
var html = '<body><scr'+ 'ipt>alert(1)</s' + 'cript>Content</body>';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);
document.body.appendChild(iframe);
Raúl Martín
  • 4,471
  • 3
  • 23
  • 42
0

You should use iframe.contentWindow.document instead of just iframe for some of your calls. Also, demo.js is in the outside page, not inside the iframe, so you either need to give an absolute path (i.e. http://www.example.com/demo.js) or you need to set the contents of the script. This worked for me:

var iframe = document.getElementById('test');
var headID = iframe.contentWindow.document.getElementsByTagName("head")[0];         

var newScript = iframe.contentWindow.document.createElement('script');
newScript.innerHTML = 'document.write("Hello, I\'m a Demo")';
newScript.type = 'text/javascript';
headID.appendChild(newScript);
mpallansch
  • 1,174
  • 6
  • 16