1

我正試圖在Firefox搜索引擎框中使用搜索引擎執行搜索。使用安裝的搜索引擎使用javascript執行搜索

我可以用下面的代碼

// 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的使用已安裝的搜索引擎搜索訪問引擎。有誰知道我能做到這一點?

回答

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

謝謝Noitidart!這正是我正在尋找的。 – hooray

+0

我的榮幸:)! – Noitidart

+0

對不起再次打擾你Noitidart,但你知道如果/我怎麼能得到一個搜索引擎的圖標?我希望以data.url格式使用它。我查看了一系列引擎,並將圖標列爲空或用本地代碼顯示getIcons methonds,迄今爲止我的搜索沒有結果。有任何想法嗎 ? – hooray