Skip to content

Instantly share code, notes, and snippets.

@third774
Created April 28, 2023 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save third774/21cdcb1011202b3c979f55cb27c0b683 to your computer and use it in GitHub Desktop.
Save third774/21cdcb1011202b3c979f55cb27c0b683 to your computer and use it in GitHub Desktop.
const exceptions = ["www.example.com"];
if (!exceptions.includes(new URL(window.location).hostname)) {
console.log("Adding slash keybinding");
document.addEventListener("keydown", function (event) {
const searchInput =
// https://caniuse.com/css-case-insensitive
document.querySelector('input[type="search" i]') ??
document.querySelector('form[role="search" i] text[type="text"]') ??
document.querySelector('input[aria-label="search" i]') ??
document.querySelector('input[name="search" i]') ??
document.querySelector('input[placeholder*="search" i]') ??
document.querySelector('input[class*="search" i]') ??
document.querySelector('input[title*="search" i]') ??
document.querySelector('form[action*="/search" i] input[type="text"]');
if (isFocusable(document.activeElement) || !searchInput) return;
if (event.key === "/") {
event.preventDefault();
searchInput.focus();
}
});
}
function isFocusable(element) {
return (
[
"a",
"button",
"details",
"input",
"select",
"textarea",
"area",
"audio",
"iframe",
"img",
"link",
"object",
"summary",
"video",
].includes(element.tagName?.toLowerCase()) ||
element.isContentEditable ||
element.hasAttribute("tabindex")
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment