我已阅读NsIContentPolicy并已搜索整个Stackoverflow以获取实施NsIContentPolicy的正确教程,但都是徒劳的。我知道Adblock使用NsIContentPolicy作为主要武器。逆向工程Adblock没有帮助我理解如何实现NsIContentPolicy。是否有使用NsIContentPolicy进行学习的简单插件,或者有关NsIContentPolicy的任何优秀教程?
答案 0 :(得分: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
documentation)之外,它不会执行任何操作。显然,在实际实现中,字段classDescription
,classID
和contractID
应该更改为正确的内容。 onShutdown
属于我正在使用的私有框架:这个扩展是无重启的,这就是为什么它需要“手动”注册组件,并且如果在浏览器会话期间关闭它也将运行此代码以删除它。 / p>
您还可以下载完整的扩展程序:testpolicy.xpi。