How can I create a XMLHttpRequest wrapper/proxy?
These methods that come to mind, what are the pros and cons of each?
Method 1: Augment native instance
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
var xhr = new _XMLHttpRequest();
// augment/wrap/modify here
var _open = xhr.open;
xhr.open = function() {
// custom stuff
return _open.apply(this, arguments);
}
return xhr;
}
Method 2: Sub-"class" native XMLHttpRequest
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
// definePropertys here etc
}
XMLHttpRequest.prototype = new _XMLHttpRequest());
// OR
XMLHttpRequest.prototype = Object.create(_XMLHttpRequest);
// custom wrapped methods on prototype here
XMLHttpRequest.prototype.open = function() {
// custom stuff
return _XMLHttpRequest.prototype.open.apply(this, arguments);
}
Method 3: Full proxy to nati开发者_运维技巧ve XMLHttpRequest
var _XMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
this.xhr = new _XMLHttpRequest();
}
// proxy ALL methods/properties
XMLHttpRequest.prototype.open = function() {
// custom stuff
return this.xhr.open.apply(this.xhr, arguments);
}
Depending on the JS engine, method 1 produces considerable overhead, since xhr.open
is redefined whenever XHR is instantiated.
Method 2 makes me think "why would you need the new _XMLHttpRequest
in the first place"? There's a minor feeling of undesired side effects, but it appears to work just fine.
Method 3: simple, old-school, but it won't work straight-away. (Think about reading properties)
In general, I'm personally reluctant when it comes to overwriting browser objects, so that would be a big con to all three methods. Better use some other variable like ProxyXHR
(just my 2 cents)
It may depend on the use case. In my case I wanted to create a complete proxy which seems to be only possible with the third method. The problem is that onreadystatechange
needs to be set on the original XHR implementation. I guess there are getter and setter defined that cannot be changed from outside.
Because of this method 1 and 2 will not work. To achieve this I wrote a complete, meaning I didn't find any bugs, proxy to XHR here: A: How can I catch and process the data from the XHR responses using casperjs?. It needs to be done with method 3.
I have tried all 3. I have to intercept calls from within code that I do not manage that already has Boomerang AutoXHR plugin running and intercepting calls. #2 and #3 just resulted in errors but #1 worked perfectly in my strange messed up use-case.
Use the below config
_XMLHTTPRequest.setProxy(proxySetting, varProxyServer, varBypassList);
Parameters Details: proxySetting - proxy configuration ex: SXH_PROXY_SET_DEFAULT, SXH_PROXY_SET_DIRECT, SXH_PROXY_SET_PROXY, SXH_PROXY_SET_PRECONFIG
varProxyServer - The name of a proxy server
varBypassList - host names or IP addresses for which you want to permit bypass of the proxy server.
精彩评论