简体   繁体   English

如何注射<script> tag into empty iframe without document.write?

[英]How to inject <script> tag into empty iframe without document.write?

I want to load an iframe that does nothing else than load a JavaScript file from a given URL. 我要加载的iframe除了从给定的URL加载JavaScript文件外没有其他作用。 While this would be easy by loading a simple HTML page into the iframe that only contains the <script> tag to load the JavaScript file, but that would require two requests to the server. 通过将简单的HTML页面加载到仅包含<script>标记以加载JavaScript文件的iframe中,这很容易,但是这需要向服务器发送两个请求。

So my idea is to write the code to load the JS file from the calling method in the parent window into the empty iframe. 因此,我的想法是编写代码以将JS文件从父窗口中的调用方法加载到空的iframe中。

Something like this works on all browsers: 这样的事情适用于所有浏览器:

function createScriptFrame(container, url) {
    const frame = document.createElement('iframe');
    container.appendChild(frame);
    const doc = frame.contentDocument;
    doc.open();
    doc.write('<html><body><script src="' + url + '"></script></body></html>');
    doc.close();
}

But using document.write is a really nasty way of doing it. 但是使用document.write是一种非常讨厌的方式。 Chrome even complains with a warning in the console: [Violation] Avoid using document.write(). Chrome浏览器甚至在控制台中发出警告: [Violation]避免使用document.write()。

I've come up with a few alternative approaches, for example: 我提出了一些替代方法,例如:

// same as above until doc.open()
const s = doc.createElement('script');
s.src = url;
doc.head.appendChild(s);

or 要么

const s = doc.createElement('script');
s.appendChild(doc.createTextNode('(function() { const s = 
document.createElement("script"); s.src = "' + url + '"; 
document.body.appendChild(s); })()'));
doc.head.appendChild(s);

These work nicely in Chrome and Safari but not in Firefox . 这些可以在Chrome和Safari中很好地工作,但不能在Firefox中工作

I've compiled a test with several methods to load the script: https://embed.plnkr.co/l8DwUBQs7cQsi938eTOn/ 我已经使用几种方法来编译测试以加载脚本: https : //embed.plnkr.co/l8DwUBQs7cQsi938eTOn/

Any ideas how to make this work? 任何想法如何使这项工作?

You can create a blob and open it 您可以创建一个Blob并将其打开

var url = 'foo'
var blob = new Blob([
  '<html><body><script src="' + url + '"></script></body></html>'
], {type: 'text/html'})
var iframeUrl = URL.createObjectURL(blob)
console.log(iframeUrl)

...Or if you like a base64 url ...或者如果您喜欢base64网址

You can also use the srcdoc but it isn't supported by IE/Edge 您也可以使用srcdoc,但IE / Edge不支持

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM