我正在尝试将一些代码附加到XMLHttpRequest对象的方法,但有些东西不起作用。相关代码:
XMLHttpRequest.prototype.oldOpen = XMLHttpRequest.prototype.open;
var newOpen = function(method, url, async, user, password) {
alert( "[debug info]" );
this.oldOpen(method, url, async, user, password);
}
XMLHttpRequest.prototype.open = newOpen;
调用open()时,警报会消失,但不会调用原始函数。这是为什么?
作为参考,它是GreaseMonkey脚本的一部分,应该监听XHR流量。完整的脚本如下:
var XMLHttpRequest = unsafeWindow.XMLHttpRequest;
var startTracing = function () {
XMLHttpRequest.prototype.uniqueID = function() {
// each XMLHttpRequest gets assigned a unique ID and memorizes it
// in the "uniqueIDMemo" property
if (!this.uniqueIDMemo) {
this.uniqueIDMemo = Math.floor(Math.random() * 1000);
}
return this.uniqueIDMemo;
}
// backup original "open" function reference
XMLHttpRequest.prototype.oldOpen = XMLHttpRequest.prototype.open;
var oOpen = XMLHttpRequest.prototype.open;
var newOpen = function(method, url, async, user, password) {
alert("open: " + method + "," + url + "," + async + "," + user + "," + password );
this.oldOpen(method, url, async, user, password);
}
XMLHttpRequest.prototype.open = newOpen;
}
startTracing();
答案 0 :(得分:3)
我试过这个,这实际上是对代码的修改,而且它运行得很好。这是我的整个油脂脚本。
// ==UserScript==
// @name sof
// @namespace taylor.kelly.sof
// @description Stack overflow testing
// @include http://localhost:8080/tests/sof.html
// ==/UserScript==
var XMLHttpRequest = unsafeWindow.XMLHttpRequest;
var startTracing = function () {
// backup original "open" function reference
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
alert("open: " + method + "," + url + "," + async + "," + user + "," + password );
open.apply(this, arguments);
}
}
startTracing();
当greasemonkey脚本加载时会出现计时问题。您可能必须等待window.onload在您的测试页面上启动XHTTPRequest。
我还建议您的uniqueId方案可能会发生一些冲突。使用新的Date()。getTime()与Math.random一起使用会将这些减少到接近0.类似于:
new Date().getTime() + '' + Math.floor(Math.random() * 1000)