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

标签 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 使用已安装的搜索引擎执行搜索。有谁知道我怎样才能实现这一目标?

最佳答案

在此示例中,我查找一个打开的窗口,因为它在新选项卡中打开搜索结果。但你不需要这样做。你可以使用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);

关于javascript - 使用 javascript 使用已安装的搜索引擎执行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26961639/

相关文章:

javascript - 在文本高亮事件中?

javascript - 在 JavaScript 中缓存 onclick 对象

javascript - 在受尊敬的父级上切换下拉菜单的 ngClass

javascript - nodejs看不到已安装的mysql模块

css - 平板电脑上的 Firefox 正在为输入添加一个蓝色指针

css - 相同的字体在 Chrome 与 Firefox、IE 和 Safari 中看起来不同

javascript - Mozilla FF browser.tabs.create() 不起作用

javascript - 连续 Bootstrap 七列

javascript - 为什么 Mozilla Firefox 不处理正确的 jQuery?

javascript - 如何修改浏览器中加载的网页元素