运行使用 XMLHttpRequest 下载的 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3728798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running JavaScript downloaded with XMLHttpRequest
提问by TomC
I have a site that loads information using the XMLHttpRequest when a user clicks a link. The system works well but I would like to be able to execute JavaScript gathered in this process.
我有一个站点,它在用户单击链接时使用 XMLHttpRequest 加载信息。该系统运行良好,但我希望能够执行在此过程中收集的 JavaScript。
This is a problem as I would like to download the scripts 'on demand' if it were, rather than loading them all when the page is loaded.
这是一个问题,因为我想“按需”下载脚本,而不是在加载页面时加载它们。
Thanks for any help
谢谢你的帮助
回答by Mike Hofer
I believe the recommended solution is something like this:
我相信推荐的解决方案是这样的:
function include(scriptUrl)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", scriptUrl);
xmlhttp.onreadystatechange = function()
{
if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
{
eval(xmlhttp.responseText);
}
};
xmlhttp.send();
}
Or something like it.
或者类似的东西。
However, be wary of this approach. It's vulnerable to cross-site scripting, which can open you (and your users) up to all sorts of nastiness. You'll want to take suitable precautions.
但是,要警惕这种方法。它很容易受到跨站点脚本的攻击,这可能会让您(和您的用户)面临各种讨厌的问题。您需要采取适当的预防措施。
回答by Alex Skakun
Recently I found the answer (It works in Chrome, in another browsers it was not tested).
最近我找到了答案(它在 Chrome 中有效,在其他浏览器中未测试)。
You can create dataURL string and put it into src
attribute of script
element.
您可以创建 dataURL 字符串并将其放入元素的src
属性中script
。
var xhr = XMLHttpRequest(),
doc = document;
xhr.open('GET', pathToJSFile, true);
xhr.onload = function () {
var script = doc.createElement('script'),
base64 = 'data:application/javascript;base64,';
try {
base64 += btoa(data.responseText);
} catch (e) {
// script file may contain characters that not included in Latin1
var symbols = data.responseText.split('');
for (var i = 0, l = symbols.length; i < l; i++) {
var symbol = symbols[i];
// here we are trying to find these symbols in catch branch
try {
btoa(symbol);
} catch (e) {
var code = symbol.charCodeAt(0).toString(16);
while (code.length < 4) {
code = '0' + code;
}
// replace original symbol to unicode character
symbols[i] = '\u' + code;
}
}
// create new base64 string from string with replaced characters
base64 += btoa(symbols.join(''));
} finally {
script.src = base64;
// run script
doc.body.appendChild(script);
}
};
xhr.send();
You can subscribe to xhr.onprogress to show progress bar.
您可以订阅 xhr.onprogress 来显示进度条。
Update. You can download your script file as blob, and then create blob-url.
更新。您可以将脚本文件下载为 blob,然后创建 blob-url。
var xhr = XMLHttpRequest(),
doc = document;
xhr.responseType = 'blob';
xhr.open('GET', pathToJSFile, true);
xhr.onload = function () {
var script = doc.createElement('script'),
src = URL.createObjectURL(xhr.response);
script.src = src;
doc.body.appendChild(script);
};
xhr.send();
回答by Kirill Muzykov
You can run script downloaded in form of a string using
您可以使用以字符串形式运行下载的脚本
eval()
However I would recommend you to add new
但是我建议你添加新的
<script src='..'></script>
to your document and have a callback which will be called when it will be downloaded. There are many utils and jquery plug-ins for that.
到您的文档并有一个回调,它将在下载时调用。有许多实用程序和 jquery 插件。
回答by janCoffee
I had the challenge on a mobile web-project, the magic was to set "overrideMimeType". This has been verified to work on Android 4.1 to Android 6.0.
我在移动网络项目上遇到了挑战,神奇的是设置“overrideMimeType”。这已被验证适用于 Android 4.1 到 Android 6.0。
var head = document.getElementsByTagName('head');
var injectedScript = document.createElement('script');
head[0].appendChild(injectedScript);
var myRequest = new XMLHttpRequest();
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
injectedScript.innerHTML = myRequest.responseText;
//run a function in the script to load it
}
};
function start(){
myRequest.open('GET', 'javascript-url-to-download', true);
myRequest.overrideMimeType('application/javascript');
myRequest.send();
}
start();
回答by JaredM
You would need to use eval to parse the javascript from the XHR, note that this is EXTREMELY dangerous if you don't have absolute trust in the source of the javascript.
您需要使用 eval 来解析来自 XHR 的 javascript,请注意,如果您对 javascript 的来源没有绝对的信任,这是非常危险的。