预设开启 Google 的“工具”选单

在 Google 搜索载入后自动打开“工具”选单。

当前为 2024-02-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Opens “Tools” Menu by Default on Google
  3. // @name:zh-TW 預設開啟 Google 的「工具」選單
  4. // @name:zh-CN 预设开启 Google 的“工具”选单
  5. // @description Opens the “Tools” menu on Google Search automatically when page loaded.
  6. // @description:zh-TW 在 Google 搜尋載入後自動打開「工具」選單。
  7. // @description:zh-CN 在 Google 搜索载入后自动打开“工具”选单。
  8. // @icon https://wsrv.nl/?url=https://www.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png
  9. // @author Jason Kwok
  10. // @namespace https://jasonhk.dev/
  11. // @version 1.1.4
  12. // @license MIT
  13. // @match https://www.google.com/search
  14. // @match https://www.google.com/search?*
  15. // @run-at document-end
  16. // @grant none
  17. // @supportURL https://greasyfork.org/scripts/460247/feedback
  18. // ==/UserScript==
  19.  
  20. const TOOLS_BUTTON_ATTRIBUTES = [
  21. ["aria-controls", "hdtbMenus"],
  22. ["jsname", "I4bIT"],
  23. ["jscontroller", "LbcJwc"],
  24. ];
  25.  
  26. const TOOLS_BUTTON_SELECTOR = TOOLS_BUTTON_ATTRIBUTES.map(([name, value]) => `[${name}=${value}]`).join(",");
  27.  
  28. function handleToolsButton(button)
  29. {
  30. console.debug("“Tools” button found, activating the “Tools” menu...");
  31.  
  32. clearTimeout(observerTimeout);
  33. observer.disconnect();
  34.  
  35. const interval = setInterval(() =>
  36. {
  37. if (button.getAttribute("aria-expanded") === "true")
  38. {
  39. console.debug("“Tools” menu activated, congration!");
  40.  
  41. clearTimeout(activateTimeout);
  42. clearInterval(interval);
  43. }
  44. else
  45. {
  46. button.click();
  47. }
  48. }, 250);
  49.  
  50. const activateTimeout = setTimeout(() =>
  51. {
  52. console.debug("“Tools” menu not opened, aborting...");
  53. clearInterval(interval);
  54. }, 120000);
  55. }
  56.  
  57. const observer = new MutationObserver((records) =>
  58. {
  59. for (const record of records)
  60. {
  61. for (const node of record.addedNodes)
  62. {
  63. if (node instanceof Element)
  64. {
  65. if (TOOLS_BUTTON_ATTRIBUTES.some(([name, value]) => (node.getAttribute(name) === value)))
  66. {
  67. handleToolsButton(node);
  68. }
  69. else
  70. {
  71. const button = node.querySelector(TOOLS_BUTTON_SELECTOR);
  72. if (button)
  73. {
  74. handleToolsButton(button);
  75. }
  76. }
  77. }
  78. }
  79. }
  80. });
  81.  
  82. observer.observe(document.body, { subtree: true, childList: true });
  83. const observerTimeout = setTimeout(() =>
  84. {
  85. console.debug("“Tools” button still not exist, aborting...");
  86. observer.disconnect();
  87. }, 120000);
  88.  
  89. const button = document.querySelector(TOOLS_BUTTON_SELECTOR);
  90. if (button)
  91. {
  92. handleToolsButton(button);
  93. }
  94. else
  95. {
  96. console.debug("“Tools” button not exist, attempting the MutationObserver method...");
  97. }