From f81073db76345656515e58385e0a91fa21a9f5d6 Mon Sep 17 00:00:00 2001 From: def00111 Date: Fri, 27 Sep 2024 18:54:22 +0200 Subject: [PATCH] Improve search.search() examples Get all search engines and check if the search engine is defined to the browser instead of using try/catch. --- .../webextensions/api/search/search/index.md | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/files/en-us/mozilla/add-ons/webextensions/api/search/search/index.md b/files/en-us/mozilla/add-ons/webextensions/api/search/search/index.md index c59c07cbb6d240c..d0ab1d883e02527 100644 --- a/files/en-us/mozilla/add-ons/webextensions/api/search/search/index.md +++ b/files/en-us/mozilla/add-ons/webextensions/api/search/search/index.md @@ -60,15 +60,17 @@ A search using Wikipedia with the results shown in a new window: ```js async function search() { - try { - // try to search using the `Wikipedia (en)` search engine + const engine = "Wikipedia (en)"; + const engines = await browser.search.get(); + if (engines.some((searchEngine) => searchEngine.name == engine)) { + // search using the `Wikipedia (en)` search engine await browser.search.search({ query: "styracosaurus", - engine: "Wikipedia (en)", + engine, disposition: "NEW_WINDOW", }); - } catch (ex) { - // if the search fails, e.g., because the search engine isn't defined to the browser, initiate the search using a url + } else { + // if the search engine isn't defined to the browser, initiate the search using a url await browser.windows.create({ url: "https://en.wikipedia.org/w/index.php?title=Special:Search&search=styracosaurus", }); @@ -82,15 +84,17 @@ A search using Wikipedia with the results shown in the current tab: ```js async function search(tab) { - try { - // try to search using the `Wikipedia (en)` search engine + const engine = "Wikipedia (en)"; + const engines = await browser.search.get(); + if (engines.some((searchEngine) => searchEngine.name == engine)) { + // search using the `Wikipedia (en)` search engine await browser.search.search({ query: "styracosaurus", - engine: "Wikipedia (en)", + engine, tabId: tab.id, }); - } catch (ex) { - // if the search fails, e.g., because the search engine isn't defined to the browser, initiate the search using a url + } else { + // if the search engine isn't defined to the browser, initiate the search using a url await browser.tabs.update(tab.id, { url: "https://en.wikipedia.org/w/index.php?title=Special:Search&search=styracosaurus", });