您的位置:首页 > 其它

Firefox extension 开发之常用XPCOM service

2016-04-26 17:31 232 查看
当进行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;
},
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: