Search code examples
javascriptfirefoxfirefox-addonsearch-enginefirefox-addon-sdk

Perform a search using the installed search engines using javascript


I am trying to perform a search using search engines in the Firefox search engine box .

I can access the engines with the following code

// 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

I have found no way to execute a search using the installed search engines using JavaScript. Does anyone know how I can achieve this ?


Solution

  • in this example i look for an open window as it opens the search results in a new tab. but you don't need to do that. you can use XHR. if yo uwanted to do that just take the submission parameters seen below and instead of plugging them into win.openLinkIn then plug it into 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
        });
    

    if you want to get a list of the available search engine names you can do this:

    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);