AutoFocusSearchBox

Automatically focuses the search box on page load

  1. // ==UserScript==
  2. // @license MIT
  3. // @name AutoFocusSearchBox
  4. // @namespace http://tampermonkey.net/
  5. // @version 1.0
  6. // @description Automatically focuses the search box on page load
  7. // @author aceitw
  8. // @match *://*/*
  9. // @grant GM_registerMenuCommand
  10. // @grant GM_setValue
  11. // @grant GM_getValue
  12. // ==/UserScript==
  13.  
  14. (function () {
  15. 'use strict';
  16.  
  17. // Utility: Determine if the current hostname is in the user-defined list
  18. const hostname = window.location.hostname;
  19. const siteList = GM_getValue('siteList', []);
  20.  
  21. // Try to focus the search box
  22. function focusSearchBox() {
  23. const inputTags = Array.from(document.querySelectorAll('input[type="search"], input[type="text"], input:not([type])'))
  24. .filter(el => el.offsetParent !== null && el.offsetHeight > 0 && el.offsetWidth > 0);
  25.  
  26. // Try the first element that looks like a search bar
  27. const searchInput = inputTags.find(input =>
  28. input.placeholder?.toLowerCase().includes('search') ||
  29. input.name?.toLowerCase().includes('search') ||
  30. input.id?.toLowerCase().includes('search') ||
  31. input.ariaLabel?.toLowerCase().includes('search')
  32. );
  33.  
  34. if (searchInput) {
  35. searchInput.focus();
  36. }
  37. }
  38.  
  39. // Focus only if the site is allowed
  40. if (siteList.includes(hostname)) {
  41. window.addEventListener('load', () => {
  42. setTimeout(focusSearchBox, 200); // Delay to wait for page load
  43. });
  44. }
  45.  
  46. // === SETTINGS UI ===
  47. GM_registerMenuCommand('🔧 Manage Focus Sites', () => {
  48. const currentList = GM_getValue('siteList', []);
  49. const input = prompt(
  50. `Enter a list of hostnames (one per line).\nExample:\nwww.google.com\ndocs.google.com`,
  51. currentList.join('\n')
  52. );
  53. if (input !== null) {
  54. const newList = input
  55. .split('\n')
  56. .map(s => s.trim())
  57. .filter(s => s.length > 0);
  58. GM_setValue('siteList', newList);
  59. alert('✅ Site list updated!\n\nReload the page to apply changes.');
  60. }
  61. });
  62. })();