AIGPT Everywhere

Mini A.I. floating menu that can define words, answer questions, translate, and much more in a single click and with your custom prompts. Includes useful click to search on Google and copy selected text buttons, along with Rocker+Mouse Gestures and Units+Currency+Time zone Converters, all features can be easily modified or disabled.

当前为 2025-05-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name AIGPT Everywhere
  3. // @namespace OperaBrowserGestures
  4. // @description Mini A.I. floating menu that can define words, answer questions, translate, and much more in a single click and with your custom prompts. Includes useful click to search on Google and copy selected text buttons, along with Rocker+Mouse Gestures and Units+Currency+Time zone Converters, all features can be easily modified or disabled.
  5. // @version 77
  6. // @author hacker09
  7. // @include *
  8. // @exclude https://accounts.google.com/v3/signin/*
  9. // @icon https://i.imgur.com/8iw8GOm.png
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_getResourceText
  12. // @grant GM.xmlHttpRequest
  13. // @grant GM_setClipboard
  14. // @grant GM_deleteValue
  15. // @grant GM_openInTab
  16. // @grant window.close
  17. // @run-at document-end
  18. // @grant GM_setValue
  19. // @grant GM_getValue
  20. // @connect google.com
  21. // @connect generativelanguage.googleapis.com
  22. // @resource AIMenuContent https://hacker09.glitch.me/AIMenu.html
  23. // @require https://update.greasyfork.org/scripts/506699/marked.js
  24. // @require https://update.greasyfork.org/scripts/519002/Units%20Converter.js
  25. // ==/UserScript==
  26.  
  27. /* jshint esversion: 11 */
  28.  
  29. const toHTML = html => window.trustedTypes?.createPolicy('BypassTT', { createHTML: HTML => HTML })?.createHTML(html) || html; //Bypass Trusted Types API + create safe HTML for chromium browsers
  30.  
  31. if ((location.href === 'https://aistudio.google.com/app/apikey' && document.querySelector(".apikey-link") !== null) && GM_getValue("APIKey") === undefined || GM_getValue("APIKey") === null || GM_getValue("APIKey") === '') { //Set up the API Key
  32. window.onload = setTimeout(function() {
  33. document.querySelectorAll(".apikey-link")[1].click(); //Click on the API Key
  34. setTimeout(function() {
  35. GM_setValue("APIKey", document.querySelector(".apikey-text").innerText); //Store the API Key
  36. alert((GM_getValue("APIKey") !== undefined && GM_getValue("APIKey") !== null && GM_getValue("APIKey") !== '') ? 'API Key automatically added!' : 'Failed to add API Key automatically!');
  37. }, 500);
  38. }, 1000);
  39. }
  40.  
  41. if (GM_getValue("SearchHighlight") === undefined) { //Set up everything on the first run
  42. GM_setValue("SearchHighlight", true);
  43. GM_setValue("MouseGestures", true);
  44. GM_setValue("TimeConverter", true);
  45. GM_setValue("UnitsConverter", true);
  46. GM_setValue("CurrenciesConverter", true);
  47. }
  48.  
  49. function ToggleFeature(feature)
  50. {
  51. GM_setValue(feature, GM_getValue(feature) === true ? false : true);
  52. location.reload();
  53. }
  54. //Mouse Gestures_________________________________________________________________________________________________________________________________________________________________________________
  55. GM_registerMenuCommand(`${GM_getValue("MouseGestures") ? "Disable" : "Enable"} Mouse Gestures`, function() { ToggleFeature("MouseGestures"); });
  56.  
  57. if (GM_getValue("MouseGestures") === true) //If the MouseGestures is enabled
  58. {
  59. var link;
  60.  
  61. document.querySelectorAll('a').forEach(el => {
  62. el.addEventListener('mouseover', function() {
  63. link = this.href; //Store the hovered link
  64. });
  65.  
  66. el.addEventListener('mouseout', () => {
  67. const previousLink = link; //Save the hovered link
  68. setTimeout(() => {
  69. if (previousLink === link) { //Check if the same link is still hovered
  70. link = 'about:newtab'; //Open a new tab
  71. }
  72. }, 200);
  73. });
  74. });
  75.  
  76. const funcs = { //Store the MouseGestures functions
  77.  
  78. 'DL': function() { //Detect the Down+Left movement
  79. GM_openInTab(location.href, { incognito: true, });
  80. window.top.close();
  81. },
  82.  
  83. 'L': function() { //Detect the Left movement
  84. window.history.back();
  85. },
  86.  
  87. 'R': function() { //Detect the Right movement
  88. window.history.forward();
  89. },
  90.  
  91. 'D': function(e) { //Detect the Down movement
  92. if (e.shiftKey) {
  93. open(link, '_blank', 'height=' + screen.height + ',width=' + screen.width);
  94. }
  95. else {
  96. GM_openInTab(link, { active: true, insert: true, setParent: true });
  97. }
  98. },
  99.  
  100. 'UD': function() { //Detect the Up+Down movement
  101. location.reload();
  102. },
  103.  
  104. 'DR': function(e) { //Detect the Down+Right movement
  105. top.close();
  106. e.preventDefault();
  107. e.stopPropagation();
  108. },
  109.  
  110. 'DU': function() { //Detect the Down+Up movement
  111. GM_openInTab(link, { active: false, insert: true, setParent: true });
  112. }
  113. };
  114.  
  115. //Math codes to track the mouse movement gestures
  116. var x, y, path;
  117. const TOLERANCE = 3;
  118. const SENSITIVITY = 3;
  119. const s = 1 << ((7 - SENSITIVITY) << 1);
  120. const t1 = Math.tan(0.15708 * TOLERANCE),t2 = 1 / t1;
  121.  
  122. const tracer = function(e) {
  123. var cx = e.clientX, cy = e.clientY, deltaX = cx - x, deltaY = cy - y, distance = deltaX * deltaX + deltaY * deltaY;
  124. if (distance > s) {
  125. var slope = Math.abs(deltaY / deltaX), direction = '';
  126. if (slope > t1) {
  127. direction = deltaY > 0 ? 'D' : 'U';
  128. } else if (slope <= t2) {
  129. direction = deltaX > 0 ? 'R' : 'L';
  130. }
  131. if (path.charAt(path.length - 1) !== direction) {
  132. path += direction;
  133. }
  134. x = cx;
  135. y = cy;
  136. }
  137. };
  138.  
  139. window.addEventListener('mousedown', function(e) {
  140. if (e.which === 3) {
  141. x = e.clientX;
  142. y = e.clientY;
  143. path = "";
  144. window.addEventListener('mousemove', tracer, false); //Detect the mouse position
  145. }
  146. }, false);
  147.  
  148. window.addEventListener('contextmenu', function(e) { //When the right click BTN is released
  149. window.removeEventListener('mousemove', tracer, false); //Track the mouse movements
  150. if (path !== "") {
  151. e.preventDefault();
  152. if (funcs.hasOwnProperty(path)) {
  153. funcs[path](e);
  154. }
  155. }
  156. }, false);
  157. }
  158. //Rocker Mouse Gestures__________________________________________________________________________________________________________________________________________________________________________
  159. GM_registerMenuCommand(`${GM_getValue("RockerMouseGestures") ? "Disable" : "Enable"} Rocker Gestures`, function() { ToggleFeature("RockerMouseGestures"); });
  160.  
  161. if (GM_getValue("RockerMouseGestures") === true) //If the RockerMouseGestures is enabled
  162. {
  163. const mouseState = { 0: false, 2: false }; //0: Left, 2: Right
  164.  
  165. window.addEventListener("mouseup", function(e) {
  166. mouseState[e.button] = false; //Update the state for the released button
  167.  
  168. if (mouseState[0] && !mouseState[2]) { //Left clicked, Right released
  169. history.back();
  170. } else if (mouseState[2] && !mouseState[0]) { //Right clicked, Left released
  171. history.forward();
  172. }
  173. }, false);
  174.  
  175. window.addEventListener("mousedown", function(e) {
  176. mouseState[e.button] = true; //Update the state for the pressed button
  177. }, false);
  178. }
  179. //Search HighLight + Time + Currencies + Units Converters + Search HighLight + AI menus__________________________________________________________________________________________________________
  180. GM_registerMenuCommand(`${GM_getValue("SearchHighlight") ? "Disable" : "Enable"} Search Highlight`, function() { ToggleFeature("SearchHighlight"); });
  181.  
  182. if (GM_getValue("SearchHighlight") === true) //If the SearchHighlight is enabled
  183. {
  184. var SelectedText;
  185. const Links = new RegExp(/\.org|\.ly|\.net|\.co|\.tv|\.me|\.biz|\.club|\.site|\.br|\.gov|\.io|\.ai|\.jp|\.edu|\.au|\.in|\.it|\.ca|\.mx|\.fr|\.tw|\.il|\.uk|\.zoom\.us|\.youtu\.be|\.com|\.us|\.de|\.cn|\.ru|\.es|\.ch|\.nl|\.se|\.no|\.dk|\.fi|\.pl|\.tr|\.xyz|\.za/i);
  186.  
  187. document.body.addEventListener('mouseup', async function() { //When the user releases the mouse click after selecting something
  188. HtmlMenu.style.display = 'block'; //Display the container div
  189. SelectedText = getSelection().toString().trim(); //Store the selected text
  190. shadowRoot.querySelector("#ShowCurrencyORUnits").innerText = ''; //Remove the previous Units/Currency text
  191.  
  192. function ShowConversion(UnitORCurrency, Type, Result) {
  193. shadowRoot.querySelector("#SearchBTN span")?.remove(); //Return previous HTML
  194. shadowRoot.querySelector("#SearchBTN").innerHTML = toHTML('<span class="GreyBar">│ </span>' + shadowRoot.querySelector("#SearchBTN").innerHTML);
  195.  
  196. if (UnitORCurrency === 'Currencies') {
  197. const hasSymbol = SelectedText.match(Currencies)[2].match(CurrencySymbols) !== null;
  198. const currencyFormat = Intl.NumberFormat(navigator.language, {
  199. style: 'currency',
  200. currency: GM_getValue("YourLocalCurrency")
  201. }).format(Result);
  202.  
  203. const displayText = hasSymbol ? (Type + ' 🠂 ' + currencyFormat) : currencyFormat;
  204. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = toHTML(displayText);
  205. }
  206. else
  207. {
  208. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = toHTML(UnitORCurrency === 'Units' ? `${Result} ${Type}` : Result); //Show the converted time results
  209. }
  210.  
  211. setTimeout(() => { //Wait for Units to show up to get the right offsetWidth
  212. const offsetWidth = shadowRoot.querySelector("#ShowCurrencyORUnits").offsetWidth; //Store the current menu size
  213. shadowRoot.querySelector("#ShowCurrencyORUnits").onmouseover = function() { //When the mouse hovers the unit/currency
  214. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = toHTML(`Copy`);
  215. shadowRoot.querySelector("#ShowCurrencyORUnits").style.display = 'inline-flex';
  216. shadowRoot.querySelector("#ShowCurrencyORUnits").style.width = `${offsetWidth}px`; //Maintain the aspect ratio
  217. };
  218. }, 0);
  219.  
  220. const htmlcode = shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML; //Save the converted unit/currency value
  221. shadowRoot.querySelector("#ShowCurrencyORUnits").onmouseout = function() { //When the mouse leaves the unit/currency
  222. shadowRoot.querySelector("#ShowCurrencyORUnits").style.width = ''; //Return the original aspect ratio
  223. shadowRoot.querySelector("#ShowCurrencyORUnits").style.display = ''; //Return the original aspect ratio
  224. shadowRoot.querySelector("#ShowCurrencyORUnits").innerHTML = toHTML(htmlcode); //Return the previous html
  225. };
  226.  
  227. shadowRoot.querySelector("#ShowCurrencyORUnits").onclick = function() { //When the unit/currency is clicked
  228. UnitORCurrency.match(/Units|Time/) ? GM_setClipboard(`${Result} ${Type}`) : GM_setClipboard(Intl.NumberFormat(navigator.language, { style: 'currency', currency: GM_getValue("YourLocalCurrency") }).format(Result));
  229. };
  230. }
  231.  
  232. function Get(url) { //Get the final converted time/currency value
  233. return new Promise(resolve => GM.xmlHttpRequest({
  234. method: "GET",
  235. url: url,
  236. onload: response => resolve(new DOMParser().parseFromString(response.responseText, 'text/html'))
  237. }));
  238. }
  239. //Time Converter_____________________________________________________________________________________________________________________________________________________________________________
  240. GM_registerMenuCommand(`${GM_getValue("TimeConverter") ? "Disable" : "Enable"} Time Converter`, function() { ToggleFeature("TimeConverter"); });
  241. const time = new RegExp(/^[ \t\xA0]*(?=.*?(\d{1,2}:\d{2}(?::\d{2})?\s?(?:[aApP]\.?[mM]\.?)?)|\d{1,2}(?::\d{2}(?::\d{2})?)?\s?(?:[aApP]\.?[mM]\.?)?)(?=.*?(PST|PDT|MST|MDT|CST|CDT|EST|EDT|AST|ADT|NST|NDT|GMT|BST|MET|CET|CEST|EET|EEST|WET|WEST|JST|KST|IST|MSK|UTC|PT))(?:\1[ \t\xA0]*\2|\2[ \t\xA0]*\1)[ \t\xA0]*$/i);
  242.  
  243. if (GM_getValue("TimeConverter") === true && SelectedText.match(time) !== null) //If the TimeConverter is enabled and if the selected text is a time
  244. {
  245. const timeResponse = await Get(`https://www.google.com/search?q=${SelectedText.match(time)[0].replace("WET", "Western European Time")} to local time`);
  246. const ConvertedTime = timeResponse.querySelector(".aCAqKc")?.innerText;
  247. const Secs = SelectedText.match(time)[0].match(/(?:\d{1,2}:\d{2}(:\d{2})\s?[ap]\.?m)/i)?.[1] || '';
  248. ConvertedTime && ShowConversion('Time', '', ConvertedTime.replace(/(\d{1,2}):(\d{2})\s?([pP][mM])/, (_, h, m) => `${(h % 12 + 12) % 24}:${m}`).match(/[\d:]+/g)[0] + Secs); //Convert PM to 24-hour format if we got the final time conversion value
  249. }
  250. //Currencies Converter_______________________________________________________________________________________________________________________________________________________________________
  251. GM_registerMenuCommand(`${GM_getValue("CurrenciesConverter") ? "Disable" : "Enable"} Currencies Converter`, function() { ToggleFeature("CurrenciesConverter"); });
  252. const CurrencySymbols = new RegExp(/AU\$|HK\$|US\$|\$US|R\$|\$|¥|€|Rp|Kč|kr(?!w)|zł|£|฿|₩|лв|₪|円|₱|₽|руб|lei|Fr|krw|RON|TRY|₿|Br|₾|₴|₸|₺/i);
  253. const Currencies = new RegExp(/^[ \t\xA0]*\$?(?=.*?(\d+(?:.*\d+)?))(?=(?:\1[ \t\xA0]*)?(Dólares|dolares|dólares|dollars?|AU\$?D?|BGN|BRL|BCH|BTC|BYN|CAD|CHF|Fr|CNY|CZK|DKK|EUR|EGP|ETH|GBP|GEL|HKD|HUF|IDR|ILS|INR|JPY|LTC|KRW|MXN|NOK|NZD|PHP|PLN|RON|RUB|SEK|SGD|THB|TRY|USD|UAH|ZAR|KZT|YTL|\$|R\$|HK\$|US\$|\$US|¥|€|Rp|Kč|kr|krw|zł|£|฿|₩|лв|₪|円|₱|₽|руб|lei|Kč|₿|Br|₾|₴|₸|₺))(?:\1[ \t\xA0]*\2|\2[ \t\xA0]*\1)[ \t\xA0]*$/i); //https://regex101.com/r/6vTbtv/20 Davidebyzero
  254.  
  255. if (GM_getValue("CurrenciesConverter") === true && SelectedText.match(Currencies) !== null) { //If Currencies Converter is enabled and if the selected text is a currency
  256. if (GM_getValue("YourLocalCurrency") === undefined) {
  257. const UserInput = prompt('Write your local currency.\nThe script will always use your local currency to make exchange-rate conversions.\n\n*Currency input examples:\nBRL\nCAD\nUSD\netc...\n\n*Press OK');
  258. GM_setValue("YourLocalCurrency", UserInput);
  259. }
  260. const currencyMap = { 'AU$': 'AUD', '$': 'USD', 'us$': 'USD', '$us': 'USD', 'r$': 'BRL', 'hk$': 'HKD', '¥': 'JPY', '€': 'EUR', 'rp': 'IDR', 'kč': 'CZK', 'kr': 'NOK', 'zł': 'PLN', '£': 'GBP', '฿': 'THB', '₩': 'KRW', 'лв': 'BGN', '₪': 'ILS', '円': 'JPY', '₱': 'PHP', '₽': 'RUB', 'руб': 'RUB', 'lei': 'RON', 'ron': 'Romanian Leu', 'krw': 'KRW', 'fr': 'CHF', '₿': 'BTC', 'Br': 'BYN', '₾': 'GEL', '₴': 'UAH', '₸': 'KZT', '₺': 'YTL', 'try': 'Turkish Lira' };
  261. if((currencyMap[SelectedText.match(CurrencySymbols)?.[0].toLowerCase()]||SelectedText.match(Currencies)[2]).toUpperCase() === GM_getValue("YourLocalCurrency").toUpperCase()) return; //Disable same unit conversion
  262. const CurrencySymbol = currencyMap[SelectedText.match(CurrencySymbols)?.[0].toUpperCase()] || SelectedText.match(Currencies)[2]; //Store the currency symbol
  263. const currencyResponse = await Get(`https://www.google.com/search?q=${SelectedText.replace(/[.,]/g, '').match(Currencies)[1]} ${CurrencySymbol} in ${GM_getValue("YourLocalCurrency")}`);
  264. const FinalCurrency = parseFloat(currencyResponse.querySelector(".SwHCTb, .pclqee").innerText.split(' ')[0].replaceAll(',', '')); //Store the FinalCurrency and erase all commas
  265. ShowConversion('Currencies', CurrencySymbol, FinalCurrency);
  266. }
  267. //Units Converter____________________________________________________________________________________________________________________________________________________________________________
  268. GM_registerMenuCommand(`${GM_getValue("UnitsConverter") ? "Disable" : "Enable"} Units Converter`, function() { ToggleFeature("UnitsConverter"); });
  269. const Units = new RegExp(/^[ \t\xA0]*(-?\d+(?:[., ]\d+)?)(?:[ \t\xA0]*(in|inch|inches|"|”|″|cm|cms|centimeters?|m|mt|mts|meters?|ft|kg|lbs?|pounds?|kilograms?|ounces?|g|ozs?|fl oz|fl oz \(us\)|fluid ounces?|kphs?|km\/h|kilometers per hours?|mhp|mphs?|meters per hours?|(?:°\s?|º\s?|)(?:degrees?\s+)?(?:celsius|fahrenheit|[CF])|km\/hs?|ml|milliliters?|l|liters?|litres?|gal|gallons?|yards?|yd|Millimeter|millimetre|kilometers?|mi|mm|miles?|ft|fl|feets?|grams?|kilowatts?|kws?|brake horsepower|mechanical horsepower|hps?|bhps?|miles per gallons?|mpgs?|liters per 100 kilometers?|lt?\/100km|liquid quarts?|lqs?|qt|foot-? ?pounds?|ft-?lbs?|lb fts?|newton-? ?meters?|n·?m))?(?:[ \t\xA0]*x[ \t\xA0]*(-?\d+(?:[., ]\d+)?)(?:[ \t\xA0]*(in|inch|inches|"|”|″|cm|cms|centimeters?|m|mt|mts|meters?|ft))?)?[ \t\xA0]*(?:\(\w+\)[ \t\xA0]*)?(?:[ \t\xA0]*\^(\d+\.?\d*))*$/i);
  270.  
  271. if (GM_getValue("UnitsConverter") === true && SelectedText.match(/\^(\d+\.?\d*)/) || (SelectedText.match(Units)?.[1] && SelectedText.match(Units)?.[2] || SelectedText.match(Units)?.[3])) { //If the Units Converter option is enabled and if the selected text is a math power or an unit
  272.  
  273. const selectedUnitType = (SelectedText.match(Units)[2]||SelectedText.match(Units)[4])?.toLowerCase();
  274. const SelectedUnitValue = SelectedText.match(Units)[1].replaceAll(',', '.');
  275. const SecondSelectedUnitValue = SelectedText.match(Units)[3]?.replaceAll(',', '.')||0;
  276.  
  277. const convertValue = (value, unitType) => {
  278. const { factor, convert } = window.UConv[unitType] || {};
  279. return convert ? convert(value) : value * factor;
  280. };
  281.  
  282. var NewUnit = window.UConv[selectedUnitType]?.unit || selectedUnitType;
  283. var ConvertedUnit = `${convertValue(parseFloat(SelectedUnitValue), selectedUnitType).toFixed(2)}${SecondSelectedUnitValue != 0 ? ` x ${convertValue(parseFloat(SecondSelectedUnitValue), selectedUnitType).toFixed(2)}` : ''}`;
  284. ConvertedUnit = SelectedText.match(/\^(\d+\.?\d*)/) ? (NewUnit = 'power', Math.pow(parseFloat(SelectedUnitValue), parseFloat(SelectedText.match(/\^(\d+\.?\d*)/)[1]))) : ConvertedUnit;
  285. ShowConversion('Units', NewUnit, ConvertedUnit);
  286. }
  287. //Mini Menu__________________________________________________________________________________________________________________________________________________________________________________
  288. if (shadowRoot.querySelector("#SearchBTN").innerText === 'Open') //If the Search BTN text is 'Open'
  289. {
  290. shadowRoot.querySelector("#highlight_menu > ul").style.paddingInlineStart = '19px'; //Increase the menu size
  291. shadowRoot.querySelector("#SearchBTN").innerText = 'Search'; //Display the BTN text as Search again
  292. shadowRoot.querySelectorAll(".AI-BG-box button").forEach(button => { button.style.marginLeft = ''; }); //Remove the margin left
  293. shadowRoot.querySelector("#OpenAfter").remove(); //Remove the custom Open white hover overlay
  294. }
  295.  
  296. if (SelectedText.match(Links) !== null) //If the selected text is a link
  297. {
  298. shadowRoot.querySelector("#highlight_menu > ul").style.paddingInlineStart = '27px'; //Increase the menu size
  299. shadowRoot.querySelector("#SearchBTN").innerText = 'Open'; //Change the BTN text to Open
  300. shadowRoot.querySelectorAll(".AI-BG-box button").forEach(button => { button.style.marginLeft = '-2%'; }); //Add a margin left
  301. shadowRoot.innerHTML += toHTML(`<style id="OpenAfter"> #SearchBTN::after { width: 177% !important; transform: translate(-34%, -71%) !important; } </style> `); //Add a custom Open white hover overlay
  302. }
  303.  
  304. shadowRoot.querySelector("#SearchBTN").onmousedown = function() {
  305. GM_openInTab(SelectedText.match(Links) ? SelectedText.replace(/^(?!https?:\/\/)(.+)$/, 'https://$1') : `https://www.google.com/search?q=${SelectedText.replaceAll('&', '%26').replace(/\s+/g, ' ')}`, { active: true, setParent: true, loadInBackground: true }); //Open link or Google and search for the selected text
  306. shadowRoot.querySelector("#highlight_menu").classList.remove('show'); //Hide the menu
  307. };
  308.  
  309. const menu = shadowRoot.querySelector("#highlight_menu");
  310. if (document.getSelection().toString().trim() !== '') { //If text has been selected
  311. const p = document.getSelection().getRangeAt(0).getBoundingClientRect(); //Store the selected position
  312.  
  313. menu.classList.add('show'); //Show the menu
  314. menu.offsetHeight; //Trigger reflow by forcing a style calculation
  315. menu.style.left = p.left + (p.width / 2) - (menu.offsetWidth / 2) + 'px';
  316. menu.style.top = p.top - menu.offsetHeight - 18 + 'px';
  317. menu.classList.add('highlight_menu_animate');
  318.  
  319. return; //Keep the menu open
  320. }
  321. menu.classList.remove('show'); //Hide the menu
  322. shadowRoot.querySelector("#SearchBTN span")?.remove(); //Return previous HTML
  323. }); //Finishes the mouseup event listener
  324. //AI Menu______________________________________________________________________________________________________________________________________________________________________________________
  325. var desiredVoice = null, isRecognizing = false;
  326. const HtmlMenu = document.createElement('div'); //Create a container div
  327. HtmlMenu.setAttribute('style', `width: 0px; height: 0px; display: none;`); //Hide the container div by default
  328. const shadowRoot = HtmlMenu.attachShadow({ mode: 'closed' });
  329. const UniqueLangs = navigator.languages.filter((l, i, arr) => !arr.slice(0, i).some(e => e.split('-')[0].toLowerCase() === l.split('-')[0].toLowerCase()) ); //Filter unique languages
  330. const Lang = UniqueLangs.join(' and into '); //Use 1 or more languages
  331.  
  332. shadowRoot.innerHTML = toHTML(GM_getResourceText("AIMenuContent")); //Set the AI menu HTML+CSS
  333.  
  334. document.addEventListener('keydown', function(e) {
  335. if ((e.shiftKey && e.code === 'Digit7' || e.key === '/') && (e.ctrlKey || e.metaKey)) { //Detect Ctrl/Cmd + / or Ctrl/Cmd + Shift + 7
  336. shadowRoot.querySelector("#prompt").value = document.activeElement.value?.trim() || ""; //If the focused element has text and isn't undefined, auto copy the texbox text into the AI prompt
  337. shadowRoot.querySelectorAll("#dictate, #CloseOverlay, .animated-prompt-box").forEach(el => el.classList.add('show')); //Show the AI transcript button, Close Overlay, and prompt box
  338.  
  339. shadowRoot.querySelector("#CloseOverlay").onclick = function() {
  340. shadowRoot.querySelectorAll("#CloseOverlay, #AIBox, .animated-prompt-box, #AIBox.AnswerBox").forEach(el => el.classList.remove('show')); //Hide the Close Overlay, prompt and answer boxes
  341. };
  342. }
  343. });
  344.  
  345. function SwitchMode() {
  346. if (shadowRoot.querySelector("#prompt").placeholder.match('about')) { //If the input bar contains the word "about"
  347. shadowRoot.querySelector("#AddContext").remove(); //Return original prompt input styles
  348. shadowRoot.querySelector("#context").classList.remove('show'); //Hide the context view
  349. shadowRoot.querySelector("#prompt").placeholder = 'Ask Gemini anything...'; //Return default placeholder
  350. }
  351. else
  352. {
  353. shadowRoot.querySelector("#context").classList.add('show'); //Show the context view
  354. shadowRoot.querySelector("#prompt").placeholder = `Ask about ${location.host.replace('www.','')}`; //Change placeholder
  355. shadowRoot.querySelector("#highlight_menu").insertAdjacentHTML('beforebegin', `<style id="AddContext"> #gemini { display: none; } #prompt { left: 14%; width: 71%; } #tabcontext { display: none; } .animated-prompt-box { --color-OrangeORLilac: #FF8051; } </style> `); //Show the context bar
  356. }
  357. }
  358.  
  359. shadowRoot.querySelectorAll(".prompt-arrow").forEach(el => el.onclick = () => SwitchMode());
  360.  
  361. function Generate(Prompt, button) { //Call the AI endpoint
  362. const IsLatin = !/\p{Script=Latin}/u.test(Prompt) ? `, add 2 headings, "Pronunciation:" and "Language:"` : '';
  363. const responsePrompt = Prompt.includes('?') ? 'Give me a very short, then a long, detailed answer' : 'Help me further understand/learn a term or topic from the text/word';
  364. const extraPromptForShortInput = Prompt.split(' ').length < 5 ? `\nAfter showing (in order) (add a heading as "${Prompt}") ${IsLatin} , a few possible "Synonyms:", "Definition:" and "Example:".` : '';
  365. const context = !!shadowRoot.querySelector("#context.show") ? `"${Prompt}"\n\nMainly base yourself on the text below\n\n${document.body.innerText}` : Prompt; //Add the page context if context is enabled
  366. const msg = button.match('translate') ? `Translate this text: "${Prompt.trim().slice(0, 215)}${Prompt.length > 215 ? '…' : ''}"` : button.match('Prompt') ? `${Prompt.trim().slice(0, 240)}${Prompt.length > 240 ? '…' : ''}` : `Help me further explore a term or topic from the text: "${Prompt.trim().slice(0, 180)}${Prompt.length > 180 ? '…' : ''}"`; //AI Box top text
  367. const AIPrompt = button.match('translate') ? `Translate into ${Lang} the following text:\n\n"${Prompt}"\n${extraPromptForShortInput}${UniqueLangs.length > 1 ? `\n\nYou must answer using only 1 language first, then use only the other language, don't mix both languages!\nAlso, be sure to say which language is the translated text from, if the text isn't into ${Lang}!\n\n"${Prompt}" should be translated for the other languages.\nUse --- ${UniqueLangs.length-1}x to divide your answer into language sections.` : ''}` : button.match('Prompt') ? context : `${responsePrompt}: "${Prompt}"`;
  368.  
  369. function handleState(state) { //Show #AIMenu + #dictate but hide #TopPause for the load/abort states. Do the opposite for the 'start' state.
  370. ["#AIMenu", "#dictate", "#TopPause"].forEach(el => {
  371. if (el === "#TopPause") {
  372. shadowRoot.querySelector(el).classList[state !== 'start' ? 'remove' : 'add']('show');
  373. } else {
  374. shadowRoot.querySelector(el).classList[state !== 'start' ? 'add' : 'remove']('show');
  375. }
  376. });
  377. }
  378.  
  379. const request = GM.xmlHttpRequest({
  380. method: "POST",
  381. url: `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-latest:streamGenerateContent?key=${GM_getValue("APIKey")}`,
  382. responseType: 'stream',
  383. headers: { "Content-Type": "application/json" },
  384. data: JSON.stringify({
  385. contents: [{
  386. parts: [{
  387. text: AIPrompt
  388. }]
  389. }],
  390. systemInstruction: {
  391. parts: [{
  392. text: `List of things you aren't allowed to say/do anything like:\n1 "Based on the provided text"\n2 "The text is already in"\n3 "No translation is needed"\n4 Ask for more context\n5 "You haven't provided context"\n6 Use bullet points for Synonyms`
  393. }]
  394. },
  395. safetySettings: [
  396. { category: "HARM_CATEGORY_HARASSMENT", threshold: "BLOCK_NONE" },
  397. { category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_NONE" },
  398. { category: "HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold: "BLOCK_NONE" },
  399. { category: "HARM_CATEGORY_DANGEROUS_CONTENT", threshold: "BLOCK_NONE" }
  400. ],
  401. }),
  402. onerror: function(err) {
  403. shadowRoot.querySelector("#msg").innerHTML = 'Error';
  404. shadowRoot.querySelector("#finalanswer").innerHTML = toHTML(`<br>Please copy and paste the error below:<br><a class="feedback" href="https://greasyfork.org/scripts/419825/feedback">Click here to report this bug</a><br><br> Prompt: ${Prompt}<br> Button: ${button}<br> Error: <pre>${JSON.stringify(err, null, 2)}</pre><br><br><br>`);
  405. },
  406. onload: function(response) {
  407. handleState('load');
  408. },
  409. onabort: function(response) {
  410. handleState('abort');
  411. shadowRoot.querySelector("#finalanswer").innerHTML = toHTML('<div>ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤResponse has been interrupted.<div>');
  412. },
  413. onloadstart: function(response) {
  414. handleState('start');
  415. shadowRoot.querySelector("#prompt").focus();
  416. shadowRoot.querySelector("#msg").innerHTML = msg;
  417.  
  418. shadowRoot.querySelector("#copyAnswer").onclick = function() {
  419. shadowRoot.querySelector("#copyAnswer").style.display = 'none';
  420. shadowRoot.querySelector("#AnswerCopied").style.display = 'inline-flex';
  421. GM_setClipboard(shadowRoot.querySelector("#finalanswer").innerText.replace('ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ', ''));
  422. setTimeout(() => { //Return play BTN svg
  423. shadowRoot.querySelector("#copyAnswer").style.display = 'inline-flex';
  424. shadowRoot.querySelector("#AnswerCopied").style.display = 'none';
  425. }, 1000);
  426. };
  427.  
  428. const reader = response.response.getReader();
  429. const decoder = new TextDecoder();
  430. var buffer = '', partialMarkdown = '';
  431.  
  432. function readStream() {
  433. reader.read().then(({ value }) => {
  434. buffer += decoder.decode(value, { stream: true });
  435. var startIdx = 0;
  436. while (true) {
  437. const openBrace = buffer.indexOf('{', startIdx);
  438. if (openBrace === -1) break;
  439. var balance = 1, closeBrace = openBrace + 1;
  440.  
  441. while (balance > 0 && closeBrace < buffer.length) {
  442. if (buffer[closeBrace] === '{') balance++;
  443. if (buffer[closeBrace] === '}') balance--;
  444. closeBrace++;
  445. }
  446.  
  447. if (balance !== 0) break; //Incomplete JSON object
  448.  
  449. const jsonString = buffer.substring(openBrace, closeBrace);
  450. const item = JSON.parse(jsonString);
  451. partialMarkdown += item.candidates?.[0]?.content?.parts?.[0]?.text || item.error.message; //If there's no error show the AI answer, else show the error message
  452.  
  453. const tempDiv = document.createElement('div');
  454. tempDiv.innerHTML = window.marked.parse(partialMarkdown);
  455.  
  456. shadowRoot.querySelector("#finalanswer").innerHTML = '';
  457. shadowRoot.querySelector("#finalanswer").appendChild(tempDiv);
  458. startIdx = closeBrace;
  459. }
  460. buffer = buffer.substring(startIdx);
  461. readStream();
  462. });
  463. }
  464.  
  465. readStream();
  466.  
  467. shadowRoot.querySelector("#highlight_menu").classList.remove('show'); //Hide the mini menu on the page
  468. shadowRoot.querySelectorAll("#CloseOverlay, #AIBox, .animated-prompt-box, #AIBox.AnswerBox").forEach(el => el.classList.add('show')); //Show the AI Close Overlay, prompt and answer box
  469.  
  470. let silenceTimer;
  471. const SILENCE_TIMEOUT = 5000;
  472. var SpeechRecognition = SpeechRecognition || window.webkitSpeechRecognition;
  473. const recognition = new SpeechRecognition();
  474. recognition.interimResults = true; //Show partial results
  475. recognition.continuous = true; //Keep listening until stopped
  476.  
  477. var transcript = ""; //Add words
  478. shadowRoot.querySelector("#CloseOverlay").onclick = function() {
  479. [...shadowRoot.querySelector("#finalanswer div").childNodes].slice(0, -1).forEach(node => node.remove()); //Reset the text content
  480. shadowRoot.querySelectorAll("#CloseOverlay, #AIBox, .animated-prompt-box, #AIBox.AnswerBox").forEach(el => el.classList.remove('show')); //Hide the Close Overlay, prompt and answer boxes
  481. recognition.stop(); //Stop recognizing audio
  482. speechSynthesis.cancel(); //Stop speaking
  483. request.abort(); //Abort any ongoing request
  484. if (shadowRoot.querySelector("#gemini").style.display === 'none') {
  485. shadowRoot.querySelector("#AddContext").remove(); //Return original prompt input styles
  486. shadowRoot.querySelector("#context").classList.remove('show');
  487. shadowRoot.querySelector("#prompt").placeholder = 'Ask Gemini anything...'; //Return default placeholder
  488. }
  489. };
  490.  
  491. shadowRoot.querySelector("#TopPause").onclick = function() {
  492. request.abort();
  493. };
  494.  
  495. recognition.onend = function() {
  496. clearTimeout(silenceTimer); //Clear any pending timeout
  497. isRecognizing = false;
  498.  
  499. shadowRoot.querySelectorAll('.state1, .state2, .state3').forEach((state, index) => { //ForEach SVG animation state
  500. index.toString().match(/1|2/) && (state.style.display = 'none'); //Show only the 1 state
  501. state.classList.remove('animate'+index); //Stop the voice recording animation
  502. });
  503. transcript ? Generate(transcript, shadowRoot.querySelector("#prompt").className) : shadowRoot.querySelector("#finalanswer").innerHTML = toHTML(`<br>No audio detected. Please try again or check your mic settings.ㅤㅤㅤㅤㅤㅤㅤㅤㅤ<br><br>`); //Call the AI API if transcript audio words were detected or show an error message
  504. }; //Finish the recognition end event listener
  505.  
  506. recognition.onresult = function(event) {
  507. clearTimeout(silenceTimer); //Reset the silence timer on new input
  508. silenceTimer = setTimeout(() => {
  509. if (isRecognizing) {
  510. recognition.stop();
  511. }
  512. }, SILENCE_TIMEOUT);
  513.  
  514. transcript = ""; // Clear the transcript at the start of the event
  515. for (var i = 0; i < event.results.length; i++) { //For all transcript results
  516. transcript += event.results[i][0].transcript + ' '; //Concatenate all intermediate transcripts
  517. }
  518. shadowRoot.querySelector("#msg").innerText = transcript.slice(0, 240) + (transcript.length > 240 ? '…' : '');
  519. };
  520.  
  521. shadowRoot.querySelector("#dictate").onclick = function() {
  522. if (isRecognizing) {
  523. recognition.stop();
  524. } else {
  525. isRecognizing = true;
  526. recognition.start();
  527. shadowRoot.querySelectorAll('.state1, .state2, .state3').forEach((state, index) => { //ForEach SVG animation state
  528. state.style.display = 'unset'; //Show all states
  529. state.classList.add('animate'+index); //Start the voice recording animation
  530. });
  531. }
  532. };
  533.  
  534. speechSynthesis.onvoiceschanged = () => desiredVoice = speechSynthesis.getVoices().find(v => v.name === "Microsoft Zira - English (United States)"); //Find and store the desired voice
  535. speechSynthesis.onvoiceschanged(); //Handle cases where the event doesn't fire
  536.  
  537. shadowRoot.querySelectorAll("#speak, #SpeakingPause").forEach(function(el) {
  538. el.onclick = function() { //When the speak or the bottom pause BTNs are clicked
  539. if (speechSynthesis.speaking) {
  540. speechSynthesis.cancel();
  541. shadowRoot.querySelector("#speak").style.display = 'inline-flex'; //Show the play BTN
  542. shadowRoot.querySelector("#SpeakingPause").classList.remove('show'); //Hide the pause BTN
  543. }
  544. else
  545. {
  546. shadowRoot.querySelector("#speak").style.display = 'none'; //Hide the play BTN
  547. shadowRoot.querySelector("#SpeakingPause").classList.add('show');
  548.  
  549. var audio = new SpeechSynthesisUtterance(shadowRoot.querySelector("#finalanswer").innerText.replace(/.*?\(?..-..\)?|[^\p{L}\p{N}\s%.,!?]/gui, '')); //Play the AI response text, removing non-alphanumeric characters and lang locales for better pronunciation
  550. audio.voice = desiredVoice; //Use the desiredVoice
  551. speechSynthesis.speak(audio); //Speak the text
  552.  
  553. audio.onend = (event) => {
  554. shadowRoot.querySelector("#speak").style.display = 'inline-flex'; //Show the play BTN
  555. shadowRoot.querySelector("#SpeakingPause").classList.remove('show');
  556. };
  557. }
  558. };
  559. });
  560.  
  561. shadowRoot.querySelector("#NewAnswer").onclick = function() {
  562. recognition.stop(); //Stop recognizing audio
  563. speechSynthesis.cancel(); //Stop speaking
  564. Generate(Prompt, button); //Call the AI API
  565. };
  566. } //Finishes the onloadstart event listener
  567. });//Finishes the GM.xmlHttpRequest function
  568. } //Finishes the Generate function
  569.  
  570. shadowRoot.querySelector("#prompt").addEventListener("keydown", (event) => {
  571. event.stopPropagation(); //Don't execute event listeners of the main site
  572. if (event.key === "Enter") {
  573. Generate(shadowRoot.querySelector("#prompt").value, shadowRoot.querySelector("#prompt").className); //Call the AI API
  574. shadowRoot.querySelector("#prompt").value = ''; //Erase the prompt text
  575. }
  576. if (event.key === "Tab") {
  577. SwitchMode(event);
  578. }
  579. setTimeout(() => { //Wait for the code above to execute
  580. shadowRoot.querySelector("#prompt").focus(); //Refocus on the input bar
  581. }, 0);
  582. });
  583.  
  584. shadowRoot.querySelectorAll("#AIBTN").forEach(function(button) {
  585. button.onmousedown = function(event, i) { //When the Explore or the Translate BTNs are clicked
  586. if (GM_getValue("APIKey") === undefined || GM_getValue("APIKey") === null || GM_getValue("APIKey") === '') { //Set up the API Key if it isn't already set
  587. GM_setValue("APIKey", prompt('Enter your API key\n*Press OK\n\nYou can get a free API key at https://aistudio.google.com/app/apikey'));
  588. }
  589. if (GM_getValue("APIKey") !== null && GM_getValue("APIKey") !== '') {
  590. Generate(SelectedText, this.className); //Call the AI API
  591. }
  592. };
  593. });
  594.  
  595. if (document.body.textContent !== '' || document.body.innerText !== '') //If the body has any text
  596. {
  597. document.body.appendChild(HtmlMenu); //Add the script menu div container
  598. }
  599.  
  600. shadowRoot.querySelector('#CopyBTN').onmousedown = function() {
  601. GM_setClipboard(SelectedText);
  602. };
  603.  
  604. window.addEventListener('scroll', async function() {
  605. shadowRoot.querySelector("#highlight_menu").classList.remove('show'); //Hide the menu
  606. });
  607. }