将JS添加到空iframe

时间:2015-06-15 17:21:38

标签: javascript html iframe

我正在尝试将JavaScript文件添加到iframe的标头中,以便在加载时,iframe可以在我的“后台任务”之前。目前iframe是空的,因为没有我希望它显示的来源。也就是说,所有iframe都会执行我希望提供给它的脚本。

我从这里尝试过建议:

  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/
  6. 然而,我无法对iframe进行简单的“写”工作。 这是我正在使用的代码:

    demo.html

    document.write("Hello, I'm a Demo.");
    

    demo.js

    {{1}}

2 个答案:

答案 0 :(得分:1)

您可以直接添加内容字符串

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);

答案 1 :(得分:0)

对于某些来电,您应该使用iframe.contentWindow.document而非iframe。此外,demo.js位于外部页面中,而不在iframe中,因此您需要提供绝对路径(即http://www.example.com/demo.js),或者您需要设置脚本的内容。这对我有用:

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);