Stack Overflow on Google Search

Adds a button to search stackoverflow via Google Search

当前为 2023-05-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Stack Overflow on Google Search
  3. // @version 2.0.3
  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. // Settings
  14. const iconVisible = true;
  15.  
  16. // Start Code
  17. const queryRegex = /q=[^&]+/g;
  18. const siteRegex = /\+site(?:%3A|\:).+\.[^&+]+/g;
  19. const stackoverflowUrl = "+site%3Astackoverflow.com";
  20. let stackoverflowIcon =
  21. '<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>';
  22. const isImageSearch = /[?&]tbm=isch/.test(location.search);
  23. console.log(isImageSearch);
  24.  
  25. if (typeof trustedTypes !== "undefined") {
  26. const policy = trustedTypes.createPolicy("html", {
  27. createHTML: (input) => input,
  28. });
  29. stackoverflowIcon = policy.createHTML(stackoverflowIcon);
  30. }
  31.  
  32. (function () {
  33. // Create the link element
  34. const el = document.createElement("a");
  35. el.className = isImageSearch ? "NZmxZe" : "zItAnd FOU1zf GMT2kb";
  36.  
  37. // Add icon to the link
  38. if (iconVisible) {
  39. const span = document.createElement("span");
  40. span.className = isImageSearch ? "m3kSL" : "mUKzod";
  41. span.style.cssText = "height:16px;width:16px;display:block";
  42. span.innerHTML = stackoverflowIcon;
  43. el.appendChild(span);
  44. }
  45.  
  46. // Create the div element for the text
  47. const link = document.createElement("div");
  48. link.textContent = "Stack Overflow";
  49. el.appendChild(link);
  50.  
  51. // Add site:stackoverflow.com to the query
  52. el.href = window.location.href.replace(queryRegex, (match) =>
  53. match.search(siteRegex) >= 0
  54. ? match.replace(siteRegex, stackoverflowUrl)
  55. : match + stackoverflowUrl
  56. );
  57.  
  58. // Insert the link into Google search
  59. if (isImageSearch) {
  60. let menuBar = document.querySelector(".T47uwc");
  61. menuBar.insertBefore(el, menuBar.children[menuBar.childElementCount - 1]);
  62. } else {
  63. let menuBar = document.querySelectorAll(".nfdoRb")[1];
  64. menuBar.appendChild(el);
  65. }
  66.  
  67. // Fix Sizing
  68. const buttonBox = document.querySelector(".xhjkHe");
  69. buttonBox.style.width = "auto";
  70. })();