Google Search Translate Button [Improved]

Adds a Translate button to the Google Search page

当前为 2021-08-03 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Google Search Translate Button [Improved]
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @description Adds a Translate button to the Google Search page
  6. // @author neoOpus
  7. // @include http*://www.google.*/search*
  8. // @include http*://google.*/search*
  9. // @run-at document-end
  10. // ==/UserScript==
  11.  
  12. // Change this to false if you don't want an icon
  13. const useIcon = true;
  14. // Change this to true if you want to add the button to the right of the 'Tools' button
  15. const appendRight = false;
  16.  
  17. const queryRegex = /q=[^&]+/g;
  18. const siteRegex = /\+site(?:%3A|\:).+\.[^&+]+/g;
  19. const gTranslateUrl = "https://translate.google.com/#auto/en/";
  20. const gTranslateIcon = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M22,4H12.23L11,.34A.5.5,0,0,0,10.5,0H2A2,2,0,0,0,0,2V18a2,2,0,0,0,2,2h9.65L13,23.68a.5.5,0,0,0,.47.32H22a2,2,0,0,0,2-2V6A2,2,0,0,0,22,4ZM7.5,15a4.5,4.5,0,1,1,2.92-7.92.5.5,0,1,1-.65.76A3.5,3.5,0,1,0,11,11H7.5a.5.5,0,0,1,0-1h4a.5.5,0,0,1,.5.5A4.5,4.5,0,0,1,7.5,15Zm11.9-4a11.26,11.26,0,0,1-1.86,3.29,6.67,6.67,0,0,1-1.07-1.48.5.5,0,0,0-.93.38,8,8,0,0,0,1.34,1.87,8.9,8.9,0,0,1-.65.62L14.62,11ZM23,22a1,1,0,0,1-1,1H14.6l2.77-3.17a.49.49,0,0,0,.09-.48h0l-.91-2.66a9.36,9.36,0,0,0,1-.89c1,1,1.93,1.91,2.12,2.08a.5.5,0,0,0,.68-.74c-.47-.43-1.33-1.25-2.13-2.1a11.49,11.49,0,0,0,2.22-4H21.5a.5.5,0,0,0,0-1H18V9.5a.5.5,0,0,0-1,0V10H14.5a.49.49,0,0,0-.21,0L12.57,5H22a1,1,0,0,1,1,1Z" data-name="Google Translate"/></svg>';
  21.  
  22. (function process(mutations) {
  23. // Creating the element
  24. var el = document.createElement('div');
  25. el.className = 'hdtb-mitem';
  26. var link = document.createElement('a');
  27.  
  28. // Adding the svg icon
  29. if (useIcon) {
  30. var span = document.createElement('span');
  31. span.className = 'bmaJhd iJddsb';
  32. span.style.cssText = 'height:16px;width:16px';
  33. span.innerHTML += gTranslateIcon;
  34. link.appendChild(span);
  35. }
  36.  
  37. var q = '',
  38. queryElement = document.querySelector('input[name="q"]'); // selector for the Google search input textbox
  39. if (queryElement) {
  40. q = encodeURIComponent(queryElement.value);
  41. }
  42. // Hyperlink to go to google translate
  43. link.appendChild(document.createTextNode('Translate'));
  44. link.href = gTranslateUrl + q
  45. el.appendChild(link);
  46.  
  47. // Inserting the element into Google search
  48. if (appendRight) {
  49. var toolsBtn = document.getElementById('hdtb-tls');
  50. toolsBtn.parentNode.insertBefore(el, toolsBtn.nextSibling);
  51. } else {
  52. var button = document.querySelector('.MUFPAc');
  53. button.appendChild(el);
  54. }
  55. })();