如何获取 Firefox 中当前搜索引擎的 URL?

如何获取 Firefox 中当前搜索引擎的 URL?

要获取当前搜索引擎的名称,读取 browser.search.defaultenginename 就足够了。

但是,要获取搜索引擎的 URL(例如https://duckduckgo.com/?q=), 我不知道。

keyword.url 曾经被使用过,但是现在不再可用。

我想使用 JavaScript 来获取 URL。

答案1

事实上,可以使用浏览器搜索服务(BSS)获取当前搜索引擎的URL。

请注意,您需要提供搜索词才能使用此功能。单个空格不起作用(您始终可以在 = 后再次删除搜索参数)

该代码已作为附加代码在 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);

    }
}

相关内容