使用安装的搜索引擎使用javascript执行搜索

时间:2014-11-16 20:22:37

标签: javascript firefox firefox-addon search-engine firefox-addon-sdk

我正在尝试使用Firefox搜索引擎框中的搜索引擎执行搜索。

我可以使用以下代码访问引擎

// quick Proof of Concept code
const {Cc,Ci} = require("chrome");

var browserSearchService = Cc["@mozilla.org/browser/search-service;1"]
                         .getService(Ci.nsIBrowserSearchService);

var test = browserSearchService.getEngines();
//I can query test.attribute for each engine

我发现无法使用安装的搜索引擎使用JavaScript执行搜索。有谁知道我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

在此示例中,我查找打开的窗口,因为它在新选项卡中打开搜索结果。但你不需要这样做。你可以使用XHR。如果您想要这样做,只需采用下面显示的submission参数,而不是将它们插入win.openLinkIn,然后将其插入XHR。

Cu.import('resource://gre/modules/Services.jsm'); 
var win = Services.wm.getMostRecentWindow('navigator:browser');
if (!win) {
    throw new Error('no win found of type "navigator:browser" is open');
}

var engineName = 'NAME OF INSTALLED ENGINE YOU WANT TO SEARCH WITH HERE';
console.log('enigneName:', engineName)

var engine = Services.search.getEngineByName(engineName)
if (!engine) {
    throw new Error('could not find engine with name of "' + engineName + '"');
}
var searchText = 'i want to search this value'; //if you want currently filled in text of search bar do this: win.BrowserSearch.searchBar.value
var submission = engine.getSubmission(searchText, null, 'searchbar');

var useNewTab = true;
var inBg = false; //if use new tab do you want to open it in background or foreground?

win.openLinkIn(submission.uri.spec,
    useNewTab ? 'tab' : 'current', {
        postData: submission.postData,
        inBackground: inBg,
        relatedToCurrent: true //set this to true, if you are opening in new tab AND want the tab to sit next to it, if you are opening in new tab and set this to false then the new tab will open at end of tab bar
    });

如果您想获得可用搜索引擎名称的列表,您可以这样做:

var engines = Services.search.getVisibleEngines();
var engineNames = [];
for (var i=0; i<engines.length; i++) {
  engineNames.push(engines[i].name);
}
console.log('engine names of the installed engines:', engineNames);