当进行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;
},