我在服务器中有一个javascript文件,我无法修改。

这是我必须下载的脚本的样本:

var tags = '';
tags += '<a href="#somelink"><img src="someimage.gif"/></a>;
document.write(tags);
.

我开始通过ajax下载脚本并执行它,但我将我撞到“document.write无法在异步调用中执行”问题。

所以我想将脚本作为纯文本下载,并从响应中拍摄我需要的东西,并将其放在我的HTML页面中,而不修改原始脚本。

$.ajax({
    type: "GET",
    url: "http://myurlexample.com",
    dataType: "text",
}).success(function(msg){
    console && console.log("The script was downloaded as text: "+msg);
}).error(function(object,status,errortxt){
    console && console.log("The script wasn't downloaded as text. The error:"+ errortxt);
});
.

但是使用dataType = "text"执行下载请求时,ajax会抛出错误。有没有办法来解决这个问题并将其实际下载为文本?

ps:脚本用于firefox操作系统特权应用程序,因此我不能将脚本直接放在HTML页面中,因为安全性CSP不允许它( https://developer.mozilla.org/en-us/apps/csp )。

有帮助吗?

解决方案

由于您似乎能够以某种方式成功地运行运行脚本,这是一个可能有效的可怕的想法:覆盖生成的document.write

在运行脚本之前,请执行以下操作:

document.write = function(msg) {
    handleTagStringInApp(msg);
    delete document.write; // revert to original document.write when done
};
// now load execute the script...
.

,其中handleTagStringInApp是您编写的函数,以某种方式处理标记字符串。这是基本上的jsonp,但你无法调整回调名称是不引人注目的或有用的东西,而且必须使用回调名称生成generacicetagcode。

请注意,如果应用程序中的其他任何其他内容需要使用document.write,这将是非常糟糕。(您可能通过对真实的世代odicetagcode,例如,使用页面加载和使用document.write调用它来电,以您自己的代码绕过您自己的代码。)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top