我已经阅读了 NsIContentPolicy并在整个 Stackoverflow 中搜索了实现 NsIContentPolicy 的适当教程,但都是徒劳的。我知道 Adblock 使用 NsIContentPolicy 作为他们的主要武器。逆向工程 Adblock 并没有帮助我理解如何实现 NsIContentPolicy。有没有使用 NsIContentPolicy 进行学习的简单插件,或者关于 NsIContentPolicy 的任何好的教程?
问问题
1703 次
1 回答
9
我不知道有什么好的教程,但我可以给你一些最小的示例代码:
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
let policy =
{
classDescription: "Test content policy",
classID: Components.ID("{12345678-1234-1234-1234-123456789abc}"),
contractID: "@adblockplus.org/test-policy;1",
xpcom_categories: ["content-policy"],
init: function()
{
let registrar = Components.manager.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);
onShutdown.add((function()
{
for each (let category in this.xpcom_categories)
catMan.deleteCategoryEntry(category, this.contractID, false);
// This needs to run asynchronously, see bug 753687
Services.tm.currentThread.dispatch(function()
{
registrar.unregisterFactory(this.classID, this);
}.bind(this), Ci.nsIEventTarget.DISPATCH_NORMAL);
}).bind(this));
},
// nsIContentPolicy interface implementation
shouldLoad: function(contentType, contentLocation, requestOrigin, node, mimeTypeGuess, extra)
{
dump("shouldLoad: " + contentType + " " +
(contentLocation ? contentLocation.spec : "null") + " " +
(requestOrigin ? requestOrigin.spec : "null") + " " +
node + " " +
mimeTypeGuess + "\n");
return Ci.nsIContentPolicy.ACCEPT;
},
shouldProcess: function(contentType, contentLocation, requestOrigin, node, mimeTypeGuess, extra)
{
dump("shouldProcess: " + contentType + " " +
(contentLocation ? contentLocation.spec : "null") + " " +
(requestOrigin ? requestOrigin.spec : "null") + " " +
node + " " +
mimeTypeGuess + "\n");
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();
这来自我用来查看内容策略实现问题的最小内容策略实现——除了将所有内容策略调用转储到控制台(window.dump
文档)之外,它没有做任何事情。显然,在实际实现中,字段classDescription
,classID
和contractID
应该更改为适当的内容。onShutdown
属于我正在使用的私有框架:这个扩展是无需重启的,这就是它需要“手动”注册组件的原因,并且如果它在浏览器会话期间关闭,它也会运行此代码以将其删除。
您还可以下载完整的扩展:testpolicy.xpi。
于 2012-05-28T18:13:55.437 回答