Question

I have a javascript file in a server I can't modify.

Here is a sample of the script I have to download:

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

I started downloading the script via AJAX and executing it, but I bumped into the "document.write cannot be executed in asynchronous call" problem.

So I wanted to download the script as a plain text and take what I need from the response and put it where it should go in my html page without modyfing the original script.

$.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);
});

But AJAX throws an error when I do the download request using dataType = "text". Is there any way to go around this and actually download it as a text?

P.S: The script is for a Firefox OS privileged app, so I can't put the script directly in the html page because the security CSP doesn't allow it (https://developer.mozilla.org/en-US/Apps/CSP).

Was it helpful?

Solution

Since you seem able to run the script successfully somehow, here's a terrible idea that might work: overwrite document.write.

Before you run the script, do:

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

where handleTagStringInApp is a function you write that processes the tag string somehow. This is basicallyJSONP, but you can't adjust the callback name to be something unobtrusive or helpful and must instead use the callback name document.write.

Note that this will be really bad if anything else in your app actually needs to use document.write. (You might get around this in your own code by keeping a reference to the real document.write, e.g., using var realDocWrite = document.write; on page load and calling it with realDocWrite.call(document, "whatever").)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top