From e7a9cfae6985dd6840e3a4d72728f8af45ac5a91 Mon Sep 17 00:00:00 2001 From: Hazel Noack Date: Fri, 11 Jul 2025 12:38:35 +0200 Subject: [PATCH] added different search engines --- frontend/scripts/search.js | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/frontend/scripts/search.js b/frontend/scripts/search.js index 812d3e1..f506bc6 100644 --- a/frontend/scripts/search.js +++ b/frontend/scripts/search.js @@ -3,9 +3,13 @@ console.log("adding features to search..."); const form = document.getElementById("search-form"); const input = document.getElementById("search-input"); +// https://stackoverflow.com/a/3809435/16804841 +const expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; +const urlRegex = new RegExp(expression); + const searchEngines = { "g": { - action: "https://www.google.com/search/", + action: "https://www.google.com/search", name: "q", }, "d": { @@ -22,17 +26,33 @@ const searchEngines = { }, }; -// https://stackoverflow.com/a/3809435/16804841 -const expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi; -const urlRegex = new RegExp(expression); - form.addEventListener("submit", event => { + event.preventDefault(); + s = input.value; // check if url if (s.match(urlRegex)) { - event.preventDefault(); window.open(s, "_self"); return } + + // Check if the string starts with ! followed by a key from searchEngines + let selectedEngine = { + action: form.getAttribute("action"), + name: input.getAttribute("name"), + }; + + for (const [key, value] of Object.entries(searchEngines)) { + const prefix = `!${key} `; + if (s.startsWith(prefix)) { + selectedEngine = value; + s = s.slice(prefix.length); // Remove the !{key} prefix + break; + } + } + + const url = new URL(selectedEngine.action); + url.searchParams.set(selectedEngine.name, s.trim()); + window.open(url.toString(), "_self"); });