简介
我正在尝试拦截某些HTTP请求,然后通知用户并取消这些请求:
更新:可重现的代码
const {Cc, Ci, Cr} = require("chrome");
const self = require("sdk/self");
const data = self.data;
const notif = require("notifications");
const REGEX = {
'lookup.bluecava.com': "1",
'ds.bluecava.com/v50/AC/BCAC': "2"
};
// ------------------------------------------------------------------
// Initialize observer service
var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
function TracingListener() {
this.originalListener = null;
}
// Request observer
var httpRequestObserver = {
observe: function (aSubject, aTopic, aData) {
var httpChannel = aSubject.QueryInterface(Ci.nsIHttpChannel);
if ("http-on-modify-request" == aTopic) {
var url = httpChannel.originalURI.spec;
for (var str_re in REGEX) {
var re = new RegExp(str_re, "g");
if (url.match(re)) {
console.log("Requested URL: " + url.match(re));
notif.notify({
title: "foo",
text: "foo"
});
aSubject.cancel(Cr.NS_BINDING_ABORTED); // Cancel request TODO: fix if uncommented notification won't pop up!
}
}
}
},
QueryInterface: function (aIID) {
if (aIID.equals(Ci.nsIObserver) || aIID.equals(Ci.nsISupports)) {
return this;
}
throw Cr.NS_NOINTERFACE;
}
};
// Register service
observerService.addObserver(httpRequestObserver,
"http-on-modify-request", false);
exports.main = function () {
console.log("Addon is running...");
};
// Unload addon event
exports.onUnload = function (reason) {
// Unregister service
observerService.removeObserver(httpRequestObserver,
"http-on-modify-request");
};
问题
问题在于,无论调用cancel
方法和notify
方法的顺序如何,都不会弹出通知。
可能的原因
我猜它与javascript的异步性质有关,并且该方法取消阻止以某种方式通知调用。但是,我没有在通知和取消方法中找到任何回调,我可以使用它来链接调用。有什么想法吗?