火狐扩展开发:添加书签功能的封装

这几日需要写一个给火狐浏览器增加书签的功能,需要实现给指定的书签文件夹添加文件夹和网址,封装了一些原生的方法。

参考资料:

 1.XPCOM nsINavBookmarkObserver (火狐开放书签接口)
 2.XPCOM nsINavBookmarksService (火狐开放书签接口)

 3.Code Snippets Bookmarks (官方示例)

第一步:引入firefox的Bookmark API的常量;

var bmsvc = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]
    .getService(Components.interfaces.nsINavBookmarksService);
var htService = Components.classes["@mozilla.org/browser/nav-history-service;1"].
    getService(Components.interfaces.nsINavHistoryService);
var ioService = Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);

var menuFolder = bmsvc.bookmarksMenuFolder; // 书签菜单文件夹
var toolbarFolder = bmsvc.toolbarFolder; // 书签工具栏文件夹

第二步:给根书签工具栏根目录添加书签;

function addUrl(name, url) {
   var uri = ioService.newURI(url, null, null);
   if (!bmsvc.isBookmarked(uri)) {//检测网址是否存在
        bmsvc.insertBookmark(bmsvc.toolbarFolder, uri,bmsvc.DEFAULT_INDEX, name);//添加书签
  }
}
 

第三步:给指定目录添加书签文件夹;

function addFolderUrl(folderType, folderName) {
 var query = htService.getNewQuery();
 var options = htService.getNewQueryOptions();
 query.setFolders([toolbarFolder], 1);
 var result = htService.executeQuery(query, options);
 var rootNode = result.root;
 var childFolder = 0;
 rootNode.containerOpen = true;
 //检测是否有同名的文件夹
 for (var i = 0; i < rootNode.childCount; i++) {
  var node = rootNode.getChild(i);
  if (node.type == node.RESULT_TYPE_FOLDER && node.title == folderName) {
      childFolder = node.itemId;
 //创建文件夹
      var newFolderId = bmsvc.createFolder(folderType, folderName, bmsvc.DEFAULT_INDEX);
      break;
     }
 }
  rootNode.containerOpen = false;
};
 

相关推荐