0

To get the name of the current search engine, it's enough to read browser.search.defaultenginename.

However, to get the URL to the search engine (for example https://duckduckgo.com/?q=), I have no idea.

keyword.url was once used, but it is no longer available.

I would like to use JavaScript to get the URL.

1 Answers1

0

In fact, it is possible to get the URL of the current search engine using the Browser Search Service (BSS).

Please note that you need to provide search terms in order for this to work. A single space won't work (you can always strip off the search parameters again after =)

This code was tested as addon code in Pale Moon.


var browserengine = "google"; // if all else fails 
try{
    // does work for all search engines, except the default one
    browserengine = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch).getCharPref("browser.search.defaultenginename");
}catch(e){
    alert("You don't seem to have search engines installed. Defaulting to Google.");
}

// if the selected engine is the default engine, get the value from the
// default preferences branch in order to avoid this value:
// chrome://browser-region/locale/region-properties
if(browserengine.indexOf("chrome://") > -1){
    try{
        var branch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranch).getBranch("browser.search.");
        var value = branch.getComplexValue("defaultenginename",Components.interfaces.nsIPrefLocalizedString).data;
        browserengine = value;
    }catch(e){
        // this should not happen
        alert("Failed to retrieve the default search engine.");
    }
}
browserengine = browserengine.toLowerCase(); // to compare with lowercase values

// The magic begins here
var bss = Components.classes["@mozilla.org/browser/search-service;1"].getService(Components.interfaces.nsIBrowserSearchService);
var engines = bss.getVisibleEngines({});
var i = 0;

// get current search engine URL
// mimic browser.search.defaulturl based on browser.search.defaultenginename

for(i = 0; i < engines.length; i++){

    if(engines[i].name.toLowerCase() == browserengine){
        // we don't have the URL of browser.search.defaultenginename, but we can get it now!
        alert("The URL to the engine is " + engines[i].getSubmission("search terms here (required)", null).uri.spec);

    }
}