来自this answer的代码在Chrome中不再有效,因为oldReady
变量为空,因此我认为onreadystatechange
在代码中是不可接受的。
特别是,我发现不再工作的代码如下:
(function() {
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
var oldReady;
if (async) {
oldReady = this.onreadystatechange; // IS NULL IN NEWER CHROMES
// override onReadyStateChange
this.onreadystatechange = function() {
if (this.readyState == 4) {
// this.responseText is the ajax result
// create a dummay ajax object so we can modify responseText
var self = this;
var dummy = {};
["statusText", "status", "readyState", "responseType"].forEach(function(item) {
dummy[item] = self[item];
});
dummy.responseText = '{"msg": "Hello"}';
return oldReady.call(dummy);
} else {
// call original onreadystatechange handler
return oldReady.apply(this, arguments);
}
}
}
// call original open method
return open.apply(this, arguments);
}
})();
上述代码应该覆盖XMLHttpRequest对象返回的responseText,因此在用户脚本等中很有用。我仍然需要一个有效的解决方案。