unduck/src/main.ts

32 lines
861 B
TypeScript
Raw Normal View History

2025-02-14 21:48:15 -08:00
import { bangs } from "./bang";
2025-02-14 21:30:33 -08:00
2025-02-14 21:48:15 -08:00
const defaultBang = bangs.find((b) => b.t === "g");
2025-02-14 22:03:20 -08:00
function getBangredirectUrl() {
2025-02-14 21:48:15 -08:00
const url = new URL(window.location.href);
const query = url.searchParams.get("q")?.trim() ?? "";
if (!query) return null;
2025-02-14 22:03:20 -08:00
2025-02-14 21:48:15 -08:00
const match = query.match(/!([a-z]+)/i);
2025-02-14 22:03:20 -08:00
2025-02-14 22:16:04 -08:00
const bangCandidate = match?.[1]?.toLowerCase();
2025-02-14 21:48:15 -08:00
const selectedBang = bangs.find((b) => b.t === bangCandidate) ?? defaultBang;
2025-02-14 22:03:20 -08:00
// Remove the first bang from the query
const cleanQuery = query.replace(/![a-z]+\s*/i, "").trim();
2025-02-14 21:48:15 -08:00
2025-02-14 22:03:20 -08:00
// Format of the url is:
// https://www.google.com/search?q={{{s}}}
const searchUrl = selectedBang?.u.replace(
"{{{s}}}",
encodeURIComponent(cleanQuery)
);
if (!searchUrl) return null;
2025-02-14 21:48:15 -08:00
2025-02-14 22:03:20 -08:00
return searchUrl;
2025-02-14 21:48:15 -08:00
}
2025-02-14 22:03:20 -08:00
const searchUrl = getBangredirectUrl() ?? "https://www.google.com";
2025-02-14 21:30:33 -08:00
2025-02-14 22:03:20 -08:00
window.location.replace(searchUrl);