AlessandroEmm
AlessandroEmm

Reputation: 698

Append something always to an XHR Request

I want to attach a JS Variable to every XHR request that will be issued from my single page web application.

What would be the best approach to achieve this? I don't want to establish special methods for sending with this attributes, as there may be third parties integrating with my application.

I thought about overriding the send method on the XHR Object but thats not considered good style either. I can't use cookies due to requests being cross-domain.

Any better idea or approach to this?

Thank you! -Alessandro

Upvotes: 0

Views: 396

Answers (1)

manu
manu

Reputation: 1017

if you really want to extend the existing functionalities without adding any library-like function, you could solve this using monkey patching:

(function() {
    var originalOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
        var getParameter = 'foo=bar';

        if(url.indexOf('?') === -1) {
           url = url + '?' + getParameter;
        } else {
           url = url + '&' + getParameter;
        }

        console.log('you just got monkey-patched! url is now:', url);

        originalOpen.call(this, method, url, async, user, password);
    }
})();

var request = new XMLHttpRequest();
request.open('get', 'http://google.com');

see also this jsfiddle for a working example.

you can use the same technique when injecting stuff into the body of a request if you patch the send() function. if you do, ensure you take care for the type of the data to be transmitted (see MDN). it doesn't make sense to append a parameter to a binary body ;)

Upvotes: 1

Related Questions