简体   繁体   中英

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

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 ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM