我正在使用 Selenium 来测试 Web 应用程序,并且不允许修改应用程序的 javascript 代码。我试图通过使用 GreaseMonkey 覆盖 XMLHttpRequest.send 来跟踪未完成的 AJAX 请求的数量。新的 send() 基本上将包装设置为 onreadystatechange 回调的内容,检查readyState,适当增加或减少计数器,并调用原始回调函数。
我遇到的问题似乎是权限问题,因为如果我只是浏览到普通 Firefox 浏览器中的页面,打开 Firebug 并粘贴以下代码,它似乎工作正常:
document.ajax_outstanding = 0;
if (typeof XMLHttpRequest.prototype.oldsend != 'function') {
XMLHttpRequest.prototype.oldsend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {
console.log('in new send');
console.log('this.onreadystatechange = ' + this.onreadystatechange);
this.oldonreadystatechange = this.onreadystatechange;
this.onreadystatechange = function() {
if (this.readyState == 2) {
/* LOADED */
document.ajax_outstanding++;
console.log('set ajax_outstanding to ' + document.ajax_outstanding);
}
this.oldonreadystatechange.handleEvent.apply(this, arguments);
if (this.readyState == 4) {
/* COMPLETED */
document.ajax_outstanding--;
console.log('set ajax_outstanding to ' + document.ajax_outstanding);
}
};
this.oldsend.apply(this, arguments);
};
}
现在,如果我在 GreaseMonkey 用户脚本中使用该代码片段的稍微修改版本,如下所示:
unsafeWindow.document.ajax_outstanding = 0;
if (typeof unsafeWindow.XMLHttpRequest.prototype.oldsend != 'function') {
unsafeWindow.XMLHttpRequest.prototype.oldsend = unsafeWindow.XMLHttpRequest.prototype.send;
unsafeWindow.XMLHttpRequest.prototype.send = function() {
GM_log('in new send');
GM_log('this.onreadystatechange = ' + this.onreadystatechange);
this.oldonreadystatechange = this.onreadystatechange;
this.onreadystatechange = function() {
if (this.readyState == 2) {
/* LOADED */
unsafeWindow.document.ajax_outstanding++;
GM_log('set ajax_outstanding to ' + unsafeWindow.document.ajax_outstanding);
}
this.oldonreadystatechange.handleEvent.apply(this, arguments);
if (this.readyState == 4) {
/* COMPLETED */
unsafeWindow.document.ajax_outstanding--;
GM_log('set ajax_outstanding to ' + unsafeWindow.document.ajax_outstanding);
}
};
this.oldsend.apply(this, arguments);
};
}
我转到一个页面,执行一些导致 AJAX 请求的操作,我在 javascript 错误控制台中收到以下消息:
http://www.blah.com/gmscripts/overrides: in new send
uncaught exception: [Exception... "Illegal value" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: file:///tmp/customProfileDir41e7266f56734c97a2ca02b1f7f528e1/extensions/%7Be4a8a97b-f2ed-450b-b12d-ee082ba24781%7D/components/greasemonkey.js :: anonymous :: line 372" data: no]
因此,在尝试访问 this.onreadystatechange 时似乎抛出异常
据推测,这是由于沙盒环境造成的。
任何帮助将不胜感激。我不依赖于这个解决方案,所以欢迎任何其他建议来完成我需要的事情。只是我已经尝试了其他几种,这似乎是最有希望的。要求是我需要确保计数器达到 0afterReadyState 变为 4,onreadystatechange 回调已完成执行。