Stack Overflow on Google Search

Adds a button to search stackoverflow via Google Search

当前为 2023-03-22 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Stack Overflow on Google Search
  3. // @version 2.0.0
  4. // @description Adds a button to search stackoverflow via Google Search
  5. // @author Alexyoe
  6. // @namespace https://github.com/Alexyoe/stackoverflow-search-on-google.git
  7. // @include http*://www.google.*/search*
  8. // @include http*://google.*/search*
  9. // @run-at document-end
  10. // @license MIT
  11. // ==/UserScript==
  12.  
  13. const queryRegex = /q=[^&]+/g;
  14. const siteRegex = /\+site(?:%3A|\:).+\.[^&+]+/g;
  15. const stackoverflowUrl = "+site%3Astackoverflow.com";
  16. let stackoverflowIcon =
  17. '<svg class="DCxYpf" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 384 512"><path d="M290.7 311L95 269.7 86.8 309l195.7 41zm51-87L188.2 95.7l-25.5 30.8 153.5 128.3zm-31.2 39.7L129.2 179l-16.7 36.5L293.7 300zM262 32l-32 24 119.3 160.3 32-24zm20.5 328h-200v39.7h200zm39.7 80H42.7V320h-40v160h359.5V320h-40z"/></svg>';
  18. const isImageSearch = /[?&]tbm=isch/.test(location.search);
  19. console.log(isImageSearch);
  20.  
  21. if (typeof trustedTypes !== "undefined") {
  22. const policy = trustedTypes.createPolicy("html", {
  23. createHTML: (input) => input,
  24. });
  25. stackoverflowIcon = policy.createHTML(stackoverflowIcon);
  26. }
  27.  
  28. (function () {
  29. // Create the link element
  30. const el = document.createElement("a");
  31. el.className = isImageSearch ? "NZmxZe" : "zItAnd FOU1zf GMT2kb";
  32.  
  33. // Add icon to the link
  34. const span = document.createElement("span");
  35. span.className = isImageSearch ? "m3kSL" : "mUKzod";
  36. span.style.cssText = "height:16px;width:16px";
  37. span.innerHTML = stackoverflowIcon;
  38. el.appendChild(span);
  39.  
  40. // Create the div element for the text
  41. const link = document.createElement("div");
  42. link.textContent = "Stack Overflow";
  43. el.appendChild(link);
  44.  
  45. // Add site:stackoverflow.com to the query
  46. el.href = window.location.href.replace(queryRegex, (match) =>
  47. match.search(siteRegex) >= 0
  48. ? match.replace(siteRegex, stackoverflowUrl)
  49. : match + stackoverflowUrl
  50. );
  51.  
  52. // Insert the link into Google search
  53. const menuBar = document.querySelector(isImageSearch ? ".T47uwc" : ".nfdoRb");
  54. if (isImageSearch) {
  55. menuBar.insertBefore(el, menuBar.children[menuBar.childElementCount - 1]);
  56. } else {
  57. menuBar.appendChild(el);
  58. }
  59.  
  60. // Fix Sizing
  61. const buttonBox = document.querySelector(".TrmO7");
  62. buttonBox.classList.add("size-fix");
  63. const buttonBoxCSS = document.createElement("style");
  64. buttonBoxCSS.innerHTML = ".size-fix { width: 100% !important; }";
  65. document.head.appendChild(buttonBoxCSS);
  66. })();