Dean
Dean

Reputation: 1150

Javascript cross-domain fire-and-forget requests

I'm looking to create a simple javascript system for making cross-domain fire-and-forget calls to a url. Since this url doesn't give me anything other than a status:200 when all is well, I'm trying to come up with the best solution.

The url I'm calling is out of my control, so implementing a JSONP solution or setting "Access-Control-Allow-Origin" in the header is not an option.

Also, I've been asked to write this without a dependency on jQuery.

One such solution I'm investigating involves creating a new script elelement with a src attribute to the url. However, since there will be many of these calls made, I also want to clean up after each call.

Here's what I'm thinking so far:

var fireAndForgetGETRequest = function(url) {
    var head = document.getElementsByTagName("head")[0];
    var scriptTag = document.createElement("script");
    scriptTag.type = "text/javascript";
    head.appendChild(scriptTag);

    scriptTag.src = url;

    setTimeout(function() {
        head.removeChild(scriptTag);
        scriptTag = null;
    }, 5000);
};

This will clean-up the script tag after an arbitrary amount of time (in this case 5 seconds).

Would this be a reasonable solution? Would I even have to wait before cleaning-up or will the request be made instantly?

Any help from you JavaScript gurus would be greatly appreciated :)

Upvotes: 0

Views: 1017

Answers (1)

epascarello
epascarello

Reputation: 207517

If you do not care about the response, why open yourself up to an XSS attack? Send the GET request via an image request.

function sendData(url) {
    function remove() { 
        img = null; 
    }
    var img = new Image();
    img.onerror = remove;
    img.onload = remove;
    img.src = url;   
}

Upvotes: 8

Related Questions