【问题标题】:Perform a search using the installed search engines using javascript使用 javascript 使用已安装的搜索引擎执行搜索
【发布时间】:2014-11-16 20:22:36
【问题描述】:

我正在尝试使用 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 的搜索引擎执行搜索。有谁知道我如何做到这一点?

【问题讨论】:

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


    【解决方案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);
    

    【讨论】:

    • 谢谢诺伊达特!这正是我想要的。
    • 很抱歉再次打扰您 Noitidart 但您知道我是否/如何获得搜索引擎的图标吗?我希望以 data.url 格式使用它。我查看了引擎数组,它将图标列为空或显示带有本机代码的 getIcons 方法,到目前为止我的搜索没有结果。有什么想法吗?
    • 没问题,没有对不起人。像这样Services.search.getEngineByName('Bing').iconURI.spec
    • 再次感谢 Noitidart。似乎 Bing 是唯一一个真正有图标的。这就解释了为什么我无法得到它们。
    • @hooray 你是什么其他引擎我有 7 个搜索引擎,它们都有图标:i.imgur.com/gMfPd6d.png 如果它在搜索栏中有图标,你应该可以访问它。
    猜你喜欢
    • 2011-04-03
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多