【发布时间】:2014-06-26 11:37:03
【问题描述】:
我正在尝试使用 SDK(1.6 版)构建一个 Firefox 插件,但我遇到了与扩展程序打开的选项卡有关的问题。
我想获取aContext(节点)所在的选项卡。为此,我一直在“获取”节点的窗口,然后使用 SDK 中的 Tab Utils,特别是 getTabForContentWindow()。这有时不起作用,从getTabForContentWindow() 返回的 Tab 为空。有没有更好、更健壮的方法来获取节点的 Tab?
另外,我在the Tab Utils page 上注意到它表示它“不稳定”。我应该避免使用 Tab Utils SDK 吗?
下面是 main.js 中的代码:
const {Cc, Ci, Cr, Cu, Cm, components} = require("chrome");
const { XPCOMUtils } = Cu.import("resource://gre/modules/XPCOMUtils.jsm");
var winUtils = require('sdk/window/utils');
var tabUtils = require('sdk/tabs/utils');
let policy =
{
classDescription: "my content policy",
classID: components.ID("{2DA54ECA-FBDD-11E3-B3B1-695C1D5D46B0}"),
contractID: "@www.com/policy;1",
xpcom_categories: ["content-policy"],
init: function()
{
let registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
registrar.registerFactory(this.classID, this.classDescription, this.contractID, this);
let catMan = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
for each (let category in this.xpcom_categories)
catMan.addCategoryEntry(category, this.contractID, this.contractID, false, true);
},
// nsIContentPolicy interface implementation
shouldLoad: function(aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra, aRequestPrincipal) {
console.log("*****");
console.log("aContentLocation.spec [" + aContentLocation.spec + "] ");
console.log("aContentType [" + aContentType + "] ");
if (aContext instanceof components.interfaces.nsIDOMNode) {
var node = aContext.QueryInterface(components.interfaces.nsIDOMNode);
var win = getWindow(node);
if (win) {
console.log("window found" );
var selectedTab = tabUtils.getTabForContentWindow(win);
if (selectedTab) {
console.log("tab found" );
var tabId = tabUtils.getTabId(selectedTab);
console.log("Node's tabId:" + tabId);
} else {
console.log("tab undefined" );
}
} else {
console.log("win undefined" );
}
}
return Ci.nsIContentPolicy.ACCEPT;
},
shouldProcess: function(contentType, contentLocation, requestOrigin, node, mimeTypeGuess, extra) {
return Ci.nsIContentPolicy.ACCEPT;
},
// nsIFactory interface implementation
createInstance: function(outer, iid) {
if (outer)
throw Cr.NS_ERROR_NO_AGGREGATION;
return this.QueryInterface(iid);
},
// nsISupports interface implementation
QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPolicy, Ci.nsIFactory])
};
policy.init();
var scheduleCheckFilterUpdates = function() {
var tabs = require("sdk/tabs");
tabs.open("http://wikipedia.org");
}
require('sdk/timers').setTimeout(scheduleCheckFilterUpdates, 1000);
function getWindow(node) {
if ("ownerDocument" in node && node.ownerDocument)
node = node.ownerDocument;
if ("defaultView" in node)
return node.defaultView;
return null;
}
【问题讨论】:
标签: javascript firefox firefox-addon firefox-addon-sdk