Firefox extension 开发之常用XPCOM service

本文介绍Firefox扩展开发中遇到的问题及解决方法,包括替代console.log的日志记录方式、偏好设置管理和获取当前URL等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当进行firefox extension 开发时,经常用的一些语句就不能继续开心地使用了,想要获得正确的结果,就需要用到其XPCOM service。

Components.classes 对象

参考链接:https://developer.mozilla.org/zh-CN/docs/Components.classes

  • 下面列举一些我项目中遇到的使用实例

console log

无法在add-on里面直接使用console.log
替代方案代码:

var debug = {
    init : function()
    {
       this.consoleService = Components.classes["@mozilla.org/consoleservice;1"]
                      .getService(Components.interfaces.nsIConsoleService);
    },
    log : function(msg)
    {
       if (this.isEnabled)
          if (this.consoleService)
             this.consoleService.logStringMessage(msg);
    },
    consoleService : null,
    isEnabled : true,
};

debug.init();

...
debug.log("Debug info....");

Prefenence system

如果想要在add-on中添加默认的preference value,可以在
default>preferences>pref.js中 添加下列类似语句

pref("your.extension.prefix.key1", false);
pref("your.extension.prefix.key2", true);

prefernce system 对应的是about:config,假设存入的key是

your.extension.prefix.key1 = true
your.extension.prefix.key2 = “char value”

则代码对应是

var prefs_service= Components.classes["@mozilla.org/preferences-service;1"]
    .getService(Components.interfaces.nsIPrefService);
var myprefs = prefs_service.getBranch("your.extension.prefix.");
//set preference
myprefs.setBoolPref("key1", false);
//read preference
myprefs.getCharPref("key2");
myprefs.getBoolPref("key1");

Note: getBranch的prefix string 参数必须以”.”结尾。

Get Current URL

对于常规js,可以直接使用(参考网址:http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser ):

window.location.href;
//or
document.URL;

在firefox extension内执行该语句时,window.location.href 获得的值 就是browser.xul。
如果想要获取真正的url,可以使用:

 get_current_url: function(){
   //get current url in the browser.
      var windowsService = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);

     // window object representing the most recent (active) instance of Firefox
     var currentWindow = windowsService.getMostRecentWindow('navigator:browser');

     // most recent (active) browser object - that's the document frame inside the chrome
     var browser = currentWindow.getBrowser();

     // object containing all the data about an address displayed in the browser
     var uri = browser.currentURI;

     // textual representation of the actual full URL displayed in the browser
     var url = uri.spec;
     return url;
 },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值