SerialCom

stack tracking

May 26th, 2022
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 29.65 KB | None | 0 0
  1. "use strict";
  2.  
  3. //TODO abrir pagina de opções sem precisar abrir novas abas
  4.  
  5. // Avoid outputting the error message "Receiving end does not exist" in the Console.
  6. function checkedLastError() {
  7. chrome.runtime.lastError
  8. }
  9.  
  10. // get mimetype
  11. var tabToMimeType = {}
  12. chrome.webRequest.onHeadersReceived.addListener(function(details) {
  13. if (details.tabId !== -1) {
  14. let contentTypeHeader = null
  15. for (const header of details.responseHeaders) {
  16. if (header.name.toLowerCase() === 'content-type') {
  17. contentTypeHeader = header
  18. break
  19. }
  20. }
  21. tabToMimeType[details.tabId] = contentTypeHeader && contentTypeHeader.value.split(';', 1)[0]
  22. }
  23. }, {
  24. urls: ['*://*/*'],
  25. types: ['main_frame']
  26. }, ['responseHeaders']);
  27.  
  28. chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  29. if (request.action === "getMainFramePageLanguageState") {
  30. chrome.tabs.sendMessage(sender.tab.id, {
  31. action: "getCurrentPageLanguageState"
  32. }, {
  33. frameId: 0
  34. }, pageLanguageState => {
  35. checkedLastError()
  36. sendResponse(pageLanguageState)
  37. })
  38.  
  39. return true
  40. } else if (request.action === "getMainFrameTabLanguage") {
  41. chrome.tabs.sendMessage(sender.tab.id, {
  42. action: "getOriginalTabLanguage"
  43. }, {
  44. frameId: 0
  45. }, tabLanguage => {
  46. checkedLastError()
  47. sendResponse(tabLanguage)
  48. })
  49.  
  50. return true
  51. } else if (request.action === "setPageLanguageState") {
  52. updateContextMenu(request.pageLanguageState)
  53. } else if (request.action === "openOptionsPage") {
  54. chrome.tabs.create({
  55. url: chrome.runtime.getURL("/options/options.html")
  56. })
  57. } else if (request.action === "openDonationPage") {
  58. chrome.tabs.create({
  59. url: chrome.runtime.getURL("/options/options.html#donation")
  60. })
  61. } else if (request.action === "detectTabLanguage") {
  62. try {
  63. chrome.tabs.detectLanguage(sender.tab.id, result => sendResponse(result))
  64. } catch (e) {
  65. console.error(e)
  66. sendResponse("und")
  67. }
  68.  
  69. return true
  70. } else if (request.action === "getTabHostName") {
  71. sendResponse(new URL(sender.tab.url).hostname)
  72. } else if (request.action === "thisFrameIsInFocus") {
  73. chrome.tabs.sendMessage(sender.tab.id, {action: "anotherFrameIsInFocus"}, checkedLastError)
  74. } else if (request.action === "getTabMimeType") {
  75. chrome.tabs.query({active: true, currentWindow: true}, tabs => {
  76. sendResponse(tabToMimeType[tabs[0].id])
  77. })
  78. return true
  79. }
  80. })
  81.  
  82. function updateTranslateSelectedContextMenu() {
  83. if (typeof chrome.contextMenus !== "undefined") {
  84. chrome.contextMenus.remove("translate-selected-text", checkedLastError)
  85. if (twpConfig.get("showTranslateSelectedContextMenu") === "yes") {
  86. chrome.contextMenus.create({
  87. id: "translate-selected-text",
  88. title: chrome.i18n.getMessage("msgTranslateSelectedText"),
  89. contexts: ["selection"]
  90. })
  91. }
  92. }
  93. }
  94.  
  95. function updateContextMenu(pageLanguageState = "original") {
  96. let contextMenuTitle
  97. if (pageLanguageState === "translated") {
  98. contextMenuTitle = chrome.i18n.getMessage("btnRestore")
  99. } else {
  100. const targetLanguage = twpConfig.get("targetLanguage")
  101. let uilanguage = chrome.i18n.getUILanguage()
  102. uilanguage = uilanguage.toLowerCase() != "zh-cn" && uilanguage.toLowerCase() != "zh-tw" ? uilanguage.split("-")[0] : uilanguage
  103.  
  104. let languageName
  105. if (twpLang.languages[uilanguage]) {
  106. languageName = twpLang.languages[uilanguage][targetLanguage]
  107. } else {
  108. languageName = twpLang.languages['en'][targetLanguage]
  109. }
  110. contextMenuTitle = chrome.i18n.getMessage("msgTranslateFor", languageName)
  111. }
  112. if (typeof chrome.contextMenus != 'undefined') {
  113. chrome.contextMenus.remove("translate-web-page", checkedLastError)
  114. if (twpConfig.get("showTranslatePageContextMenu") == "yes") {
  115. chrome.contextMenus.create({
  116. id: "translate-web-page",
  117. title: contextMenuTitle,
  118. contexts: ["page", "frame"]
  119. })
  120. }
  121. }
  122. }
  123.  
  124. chrome.runtime.onInstalled.addListener(details => {
  125. if (details.reason == "install") {
  126. chrome.tabs.create({
  127. url: chrome.runtime.getURL("/options/options.html")
  128. })
  129. } else if (details.reason == "update" && chrome.runtime.getManifest().version != details.previousVersion) {
  130. twpConfig.onReady(async () => {
  131. if (platformInfo.isMobile.any) return;
  132. if (twpConfig.get("showReleaseNotes") !== "yes") return;
  133.  
  134. let lastTimeShowingReleaseNotes = twpConfig.get("lastTimeShowingReleaseNotes")
  135. let showReleaseNotes = false
  136. if (lastTimeShowingReleaseNotes) {
  137. const date = new Date();
  138. date.setDate(date.getDate() - 21)
  139. if (date.getTime() > lastTimeShowingReleaseNotes) {
  140. showReleaseNotes = true
  141. lastTimeShowingReleaseNotes = Date.now()
  142. twpConfig.set("lastTimeShowingReleaseNotes", lastTimeShowingReleaseNotes)
  143. }
  144. } else {
  145. showReleaseNotes = true
  146. lastTimeShowingReleaseNotes = Date.now()
  147. twpConfig.set("lastTimeShowingReleaseNotes", lastTimeShowingReleaseNotes)
  148. }
  149.  
  150. if (showReleaseNotes) {
  151. chrome.tabs.create({
  152. url: chrome.runtime.getURL("/options/options.html#release_notes")
  153. })
  154. }
  155.  
  156.  
  157. translationCache.deleteTranslationCache()
  158. })
  159. }
  160. })
  161.  
  162. function resetPageAction(tabId, forceShow = false) {
  163. if (twpConfig.get("translateClickingOnce") === "yes" && !forceShow) {
  164. chrome.pageAction.setPopup({
  165. popup: null,
  166. tabId
  167. })
  168. } else {
  169. if (twpConfig.get("useOldPopup") === "yes") {
  170. chrome.pageAction.setPopup({
  171. popup: "popup/old-popup.html",
  172. tabId
  173. })
  174. } else {
  175. chrome.pageAction.setPopup({
  176. popup: "popup/popup.html",
  177. tabId
  178. })
  179. }
  180. }
  181. }
  182.  
  183. function resetBrowserAction(forceShow = false) {
  184. if (twpConfig.get("translateClickingOnce") === "yes" && !forceShow) {
  185. chrome.browserAction.setPopup({
  186. popup: null
  187. })
  188. } else {
  189. if (twpConfig.get("useOldPopup") === "yes") {
  190. chrome.browserAction.setPopup({
  191. popup: "popup/old-popup.html"
  192. })
  193. } else {
  194. chrome.browserAction.setPopup({
  195. popup: "popup/popup.html"
  196. })
  197. }
  198. }
  199. }
  200.  
  201. if (typeof chrome.contextMenus !== "undefined") {
  202. chrome.contextMenus.create({
  203. id: "browserAction-showPopup",
  204. title: chrome.i18n.getMessage("btnShowPopup"),
  205. contexts: ["browser_action"]
  206. })
  207. chrome.contextMenus.create({
  208. id: "pageAction-showPopup",
  209. title: chrome.i18n.getMessage("btnShowPopup"),
  210. contexts: ["page_action"]
  211. })
  212. chrome.contextMenus.create({
  213. id: "never-translate",
  214. title: chrome.i18n.getMessage("btnNeverTranslate"),
  215. contexts: ["browser_action", "page_action"]
  216. })
  217. chrome.contextMenus.create({
  218. id: "more-options",
  219. title: chrome.i18n.getMessage("btnMoreOptions"),
  220. contexts: ["browser_action", "page_action"]
  221. })
  222. chrome.contextMenus.create({
  223. id: "browserAction-pdf-to-html",
  224. title: chrome.i18n.getMessage("msgPDFtoHTML"),
  225. contexts: ["browser_action"]
  226. })
  227. chrome.contextMenus.create({
  228. id: "pageAction-pdf-to-html",
  229. title: chrome.i18n.getMessage("msgPDFtoHTML"),
  230. contexts: ["page_action"]
  231. })
  232.  
  233. const tabHasContentScript = {}
  234.  
  235. chrome.contextMenus.onClicked.addListener((info, tab) => {
  236. if (info.menuItemId == "translate-web-page") {
  237. //TODO forçar tradução em vez de alternar
  238. chrome.tabs.sendMessage(tab.id, {
  239. action: "toggle-translation"
  240. }, checkedLastError)
  241. } else if (info.menuItemId == "translate-selected-text") {
  242. if (chrome.pageAction && chrome.pageAction.openPopup && (!tabHasContentScript[tab.id] || tab.isInReaderMode)) {
  243. chrome.pageAction.setPopup({
  244. popup: "popup/popup-translate-text.html#text=" + encodeURIComponent(info.selectionText),
  245. tabId: tab.id
  246. })
  247. chrome.pageAction.openPopup()
  248.  
  249. resetPageAction(tab.id)
  250. } else {
  251. // a merda do chrome não suporte openPopup
  252. chrome.tabs.sendMessage(tab.id, {
  253. action: "TranslateSelectedText",
  254. selectionText: info.selectionText
  255. }, checkedLastError)
  256. }
  257. } else if (info.menuItemId == "browserAction-showPopup") {
  258. resetBrowserAction(true)
  259.  
  260. chrome.browserAction.openPopup()
  261.  
  262. resetBrowserAction()
  263. } else if (info.menuItemId == "pageAction-showPopup") {
  264. resetPageAction(tab.id, true)
  265.  
  266. chrome.pageAction.openPopup()
  267.  
  268. resetPageAction(tab.id)
  269. } else if (info.menuItemId == "never-translate") {
  270. const hostname = new URL(tab.url).hostname
  271. twpConfig.addSiteToNeverTranslate(hostname)
  272. } else if (info.menuItemId == "more-options") {
  273. chrome.tabs.create({
  274. url: chrome.runtime.getURL("/options/options.html")
  275. })
  276. } else if (info.menuItemId == "browserAction-pdf-to-html") {
  277. const mimeType = tabToMimeType[tab.id]
  278. if (mimeType && mimeType.toLowerCase() === "application/pdf" && typeof chrome.browserAction.openPopup !== 'undefined') {
  279. chrome.browserAction.openPopup()
  280. } else {
  281. chrome.tabs.create({
  282. url: "https://translatewebpages.org/"
  283. })
  284. }
  285. } else if (info.menuItemId == "pageAction-pdf-to-html") {
  286. const mimeType = tabToMimeType[tab.id]
  287. if (mimeType && mimeType.toLowerCase() === "application/pdf" && typeof chrome.pageAction.openPopup !== 'undefined') {
  288. chrome.pageAction.openPopup()
  289. } else {
  290. chrome.tabs.create({
  291. url: "https://translatewebpages.org/"
  292. })
  293. }
  294. }
  295. })
  296.  
  297. chrome.tabs.onActivated.addListener(activeInfo => {
  298. twpConfig.onReady(() => updateContextMenu())
  299. chrome.tabs.sendMessage(activeInfo.tabId, {
  300. action: "getCurrentPageLanguageState"
  301. }, {
  302. frameId: 0
  303. }, pageLanguageState => {
  304. checkedLastError()
  305. if (pageLanguageState) {
  306. twpConfig.onReady(() => updateContextMenu(pageLanguageState))
  307. }
  308. })
  309. })
  310.  
  311. chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  312. if (tab.active && changeInfo.status == "loading") {
  313. twpConfig.onReady(() => updateContextMenu())
  314. } else if (changeInfo.status == "complete") {
  315. chrome.tabs.sendMessage(tabId, {
  316. action: "contentScriptIsInjected"
  317. }, {
  318. frameId: 0
  319. }, response => {
  320. checkedLastError()
  321. tabHasContentScript[tabId] = !!response;
  322. })
  323. }
  324. })
  325.  
  326. chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
  327. delete tabHasContentScript[tabId]
  328. })
  329.  
  330. chrome.tabs.query({}, tabs =>
  331. tabs.forEach(tab =>
  332. chrome.tabs.sendMessage(tab.id, {
  333. action: "contentScriptIsInjected"
  334. }, {
  335. frameId: 0
  336. }, response => {
  337. checkedLastError()
  338. if (response) {
  339. tabHasContentScript[tab.id] = true
  340. }
  341. })))
  342. }
  343.  
  344. twpConfig.onReady(() => {
  345. if (platformInfo.isMobile.any) {
  346. chrome.tabs.query({}, tabs => tabs.forEach(tab => chrome.pageAction.hide(tab.id)))
  347.  
  348. chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  349. if (changeInfo.status == "loading") {
  350. chrome.pageAction.hide(tabId)
  351. }
  352. })
  353.  
  354. chrome.browserAction.onClicked.addListener(tab => {
  355. chrome.tabs.sendMessage(tab.id, {
  356. action: "showPopupMobile"
  357. }, {
  358. frameId: 0
  359. }, checkedLastError)
  360. })
  361. } else {
  362. if (chrome.pageAction) {
  363. chrome.pageAction.onClicked.addListener(tab => {
  364. if (twpConfig.get("translateClickingOnce") === "yes") {
  365. chrome.tabs.sendMessage(tab.id, {
  366. action: "toggle-translation"
  367. }, checkedLastError)
  368. }
  369. })
  370.  
  371. }
  372. chrome.browserAction.onClicked.addListener(tab => {
  373. if (twpConfig.get("translateClickingOnce") === "yes") {
  374. chrome.tabs.sendMessage(tab.id, {
  375. action: "toggle-translation"
  376. }, checkedLastError)
  377. }
  378. })
  379.  
  380. resetBrowserAction()
  381.  
  382. twpConfig.onChanged((name, newvalue) => {
  383. switch (name) {
  384. case "useOldPopup":
  385. resetBrowserAction()
  386. break
  387. case "translateClickingOnce":
  388. resetBrowserAction()
  389. chrome.tabs.query({
  390. currentWindow: true,
  391. active: true
  392. }, tabs => {
  393. resetPageAction(tabs[0].id)
  394. })
  395. break
  396. }
  397. })
  398.  
  399. //TODO veriricar porque chrome.theme.getCurrent não funciona, apenas browser.theme.getCurrent
  400. if (chrome.pageAction && browser) {
  401. let pageLanguageState = "original"
  402.  
  403. let themeColorPopupText = null
  404. browser.theme.getCurrent().then(theme => {
  405. themeColorPopupText = null
  406. if (theme.colors && (theme.colors.toolbar_field_text || theme.colors.popup_text)) {
  407. themeColorPopupText = theme.colors.toolbar_field_text || theme.colors.popup_text
  408. }
  409. updateIconInAllTabs()
  410. })
  411.  
  412. chrome.theme.onUpdated.addListener(updateInfo => {
  413. themeColorPopupText = null
  414. if (updateInfo.theme.colors && (updateInfo.theme.colors.toolbar_field_text || updateInfo.theme.colors.popup_text)) {
  415. themeColorPopupText = updateInfo.theme.colors.toolbar_field_text || updateInfo.theme.colors.popup_text
  416. }
  417. updateIconInAllTabs()
  418. })
  419.  
  420. let darkMode = false
  421. darkMode = matchMedia("(prefers-color-scheme: dark)").matches;
  422. updateIconInAllTabs()
  423.  
  424. matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
  425. darkMode = matchMedia("(prefers-color-scheme: dark)").matches;
  426. updateIconInAllTabs()
  427. })
  428.  
  429. function getSVGIcon() {
  430. const svgXml = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
  431. <path fill="$(fill);" fill-opacity="$(fill-opacity);" d="M 45 0 C 20.186 0 0 20.186 0 45 L 0 347 C 0 371.814 20.186 392 45 392 L 301 392 C 305.819 392 310.34683 389.68544 313.17383 385.77344 C 315.98683 381.84744 316.76261 376.82491 315.22461 372.25391 L 195.23828 10.269531 A 14.995 14.995 0 0 0 181 0 L 45 0 z M 114.3457 107.46289 L 156.19336 107.46289 C 159.49489 107.46289 162.41322 109.61359 163.39258 112.76367 L 163.38281 112.77539 L 214.06641 276.2832 C 214.77315 278.57508 214.35913 281.05986 212.93555 282.98828 C 211.52206 284.90648 209.27989 286.04688 206.87695 286.04688 L 179.28516 286.04688 C 175.95335 286.04687 173.01546 283.86624 172.06641 280.67578 L 159.92969 240.18945 L 108.77148 240.18945 L 97.564453 280.52344 C 96.655774 283.77448 93.688937 286.03711 90.306641 286.03711 L 64.347656 286.03711 C 61.954806 286.03711 59.71461 284.90648 58.291016 282.98828 C 56.867422 281.05986 56.442021 278.57475 57.138672 276.29297 L 107.14648 112.79492 C 108.11572 109.62465 111.03407 107.46289 114.3457 107.46289 z M 133.39648 137.70117 L 114.55664 210.03125 L 154.06445 210.03125 L 133.91211 137.70117 L 133.39648 137.70117 z " />
  432. <path fill="$(fill);" fill-opacity="$(fill-opacity);" d="M226.882 378.932c28.35 85.716 26.013 84.921 34.254 88.658a14.933 14.933 0 0 0 6.186 1.342c5.706 0 11.16-3.274 13.67-8.809l36.813-81.19z" />
  433. <g>
  434. <path fill="$(fill);" fill-opacity="$(fill-opacity);" d="M467 121H247.043L210.234 10.268A15 15 0 0 0 196 0H45C20.187 0 0 20.187 0 45v301c0 24.813 20.187 45 45 45h165.297l36.509 110.438c2.017 6.468 7.999 10.566 14.329 10.566.035 0 .07-.004.105-.004h205.761c24.813 0 45-20.187 45-45V166C512 141.187 491.813 121 467 121zM45 361c-8.271 0-15-6.729-15-15V45c0-8.271 6.729-15 15-15h140.179l110.027 331H45zm247.729 30l-29.4 64.841L241.894 391zM482 467c0 8.271-6.729 15-15 15H284.408l45.253-99.806a15.099 15.099 0 0 0 .571-10.932L257.015 151H467c8.271 0 15 6.729 15 15z" />
  435. <path fill="$(fill);" fill-opacity="$(fill-opacity);" d="M444.075 241h-45v-15c0-8.284-6.716-15-15-15-8.284 0-15 6.716-15 15v15h-45c-8.284 0-15 6.716-15 15 0 8.284 6.716 15 15 15h87.14c-4.772 14.185-15.02 30.996-26.939 47.174a323.331 323.331 0 0 1-7.547-10.609c-4.659-6.851-13.988-8.628-20.838-3.969-6.85 4.658-8.627 13.988-3.969 20.839 4.208 6.189 8.62 12.211 13.017 17.919-7.496 8.694-14.885 16.57-21.369 22.94-5.913 5.802-6.003 15.299-.2 21.212 5.777 5.889 15.273 6.027 21.211.201.517-.508 8.698-8.566 19.624-20.937 10.663 12.2 18.645 20.218 19.264 20.837 5.855 5.855 15.35 5.858 21.208.002 5.858-5.855 5.861-15.352.007-21.212-.157-.157-9.34-9.392-21.059-23.059 21.233-27.448 34.18-51.357 38.663-71.338h1.786c8.284 0 15-6.716 15-15 0-8.284-6.715-15-14.999-15z" />
  436. </g>
  437. </svg>
  438. `
  439.  
  440. let svg64
  441. if (pageLanguageState === "translated" && twpConfig.get("popupBlueWhenSiteIsTranslated") === "yes") {
  442. svg64 = svgXml.replace(/\$\(fill\-opacity\)\;/g, "1.0")
  443. svg64 = btoa(svg64.replace(/\$\(fill\)\;/g, "#45a1ff"))
  444. } else {
  445. svg64 = svgXml.replace(/\$\(fill\-opacity\)\;/g, "0.5")
  446. if (themeColorPopupText) {
  447. svg64 = btoa(svg64.replace(/\$\(fill\)\;/g, themeColorPopupText))
  448. } else if (darkMode) {
  449. svg64 = btoa(svg64.replace(/\$\(fill\)\;/g, "white"))
  450. } else {
  451. svg64 = btoa(svg64.replace(/\$\(fill\)\;/g, "black"))
  452. }
  453. }
  454.  
  455. const b64Start = 'data:image/svg+xml;base64,';
  456. return b64Start + svg64
  457. }
  458.  
  459. function updateIcon(tabId) {
  460. resetPageAction(tabId)
  461. chrome.pageAction.setIcon({
  462. tabId: tabId,
  463. path: getSVGIcon()
  464. })
  465.  
  466. if (twpConfig.get("showButtonInTheAddressBar") == "no") {
  467. chrome.pageAction.hide(tabId)
  468. } else {
  469. chrome.pageAction.show(tabId)
  470. }
  471. }
  472.  
  473. function updateIconInAllTabs() {
  474. chrome.tabs.query({}, tabs =>
  475. tabs.forEach(tab => updateIcon(tab.id)))
  476. }
  477.  
  478. chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  479. if (changeInfo.status == "loading") {
  480. pageLanguageState = "original"
  481. updateIcon(tabId)
  482. }
  483. })
  484.  
  485. chrome.tabs.onActivated.addListener(activeInfo => {
  486. pageLanguageState = "original"
  487. updateIcon(activeInfo.tabId)
  488. chrome.tabs.sendMessage(activeInfo.tabId, {
  489. action: "getCurrentPageLanguageState"
  490. }, {
  491. frameId: 0
  492. }, _pageLanguageState => {
  493. checkedLastError()
  494. if (_pageLanguageState) {
  495. pageLanguageState = _pageLanguageState
  496. updateIcon(activeInfo.tabId)
  497. }
  498. })
  499. })
  500.  
  501. chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  502. if (request.action === "setPageLanguageState") {
  503. pageLanguageState = request.pageLanguageState
  504. updateIcon(sender.tab.id)
  505. }
  506. })
  507.  
  508. twpConfig.onChanged((name, newvalue) => {
  509. switch (name) {
  510. case "useOldPopup":
  511. updateIconInAllTabs()
  512. break
  513. case "showButtonInTheAddressBar":
  514. updateIconInAllTabs()
  515. break
  516. }
  517. })
  518. }
  519. }
  520. })
  521.  
  522. if (typeof chrome.commands !== "undefined") {
  523. chrome.commands.onCommand.addListener(command => {
  524. if (command === "hotkey-toggle-translation") {
  525. chrome.tabs.query({
  526. currentWindow: true,
  527. active: true
  528. }, tabs => {
  529. chrome.tabs.sendMessage(tabs[0].id, {
  530. action: "toggle-translation"
  531. }, checkedLastError)
  532. })
  533. } else if (command === "hotkey-translate-selected-text") {
  534. chrome.tabs.query({
  535. currentWindow: true,
  536. active: true
  537. }, tabs =>
  538. chrome.tabs.sendMessage(tabs[0].id, {
  539. action: "TranslateSelectedText"
  540. }, checkedLastError))
  541. } else if (command === "hotkey-swap-page-translation-service") {
  542. chrome.tabs.query({
  543. active: true,
  544. currentWindow: true
  545. }, tabs =>
  546. chrome.tabs.sendMessage(tabs[0].id, {
  547. action: "swapTranslationService"
  548. }, checkedLastError))
  549.  
  550. let currentPageTranslatorService = twpConfig.get("pageTranslatorService")
  551. if (currentPageTranslatorService === "google") {
  552. currentPageTranslatorService = "yandex"
  553. } else {
  554. currentPageTranslatorService = "google"
  555. }
  556.  
  557. twpConfig.set("pageTranslatorService", currentPageTranslatorService)
  558. } else if (command === "hotkey-show-original") {
  559. chrome.tabs.query({
  560. active: true,
  561. currentWindow: true
  562. }, tabs =>
  563. chrome.tabs.sendMessage(tabs[0].id, {
  564. action: "translatePage",
  565. targetLanguage: "original"
  566. }, checkedLastError))
  567. } else if (command === "hotkey-translate-page-1") {
  568. chrome.tabs.query({
  569. active: true,
  570. currentWindow: true
  571. }, tabs => {
  572. twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[0])
  573. chrome.tabs.sendMessage(tabs[0].id, {
  574. action: "translatePage",
  575. targetLanguage: twpConfig.get("targetLanguages")[0]
  576. }, checkedLastError)
  577. })
  578. } else if (command === "hotkey-translate-page-2") {
  579. chrome.tabs.query({
  580. active: true,
  581. currentWindow: true
  582. }, tabs => {
  583. twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[1])
  584. chrome.tabs.sendMessage(tabs[0].id, {
  585. action: "translatePage",
  586. targetLanguage: twpConfig.get("targetLanguages")[1]
  587. }, checkedLastError)
  588. })
  589. } else if (command === "hotkey-translate-page-3") {
  590. chrome.tabs.query({
  591. active: true,
  592. currentWindow: true
  593. }, tabs => {
  594. twpConfig.setTargetLanguage(twpConfig.get("targetLanguages")[2])
  595. chrome.tabs.sendMessage(tabs[0].id, {
  596. action: "translatePage",
  597. targetLanguage: twpConfig.get("targetLanguages")[2]
  598. }, checkedLastError)
  599. })
  600. }
  601. })
  602. }
  603.  
  604. twpConfig.onReady(async () => {
  605. updateContextMenu()
  606. updateTranslateSelectedContextMenu()
  607.  
  608. twpConfig.onChanged((name, newvalue) => {
  609. if (name === "showTranslateSelectedContextMenu") {
  610. updateTranslateSelectedContextMenu()
  611. }
  612. })
  613.  
  614. if (!twpConfig.get("installDateTime")) {
  615. twpConfig.set("installDateTime", Date.now())
  616. }
  617. })
  618.  
  619. twpConfig.onReady(async () => {
  620. let activeTabTranslationInfo = {}
  621.  
  622. function tabsOnActivated(activeInfo) {
  623. chrome.tabs.query({
  624. active: true,
  625. currentWindow: true
  626. }, tabs => {
  627. activeTabTranslationInfo = {
  628. tabId: tabs[0].id,
  629. pageLanguageState: "original",
  630. url: tabs[0].url
  631. }
  632. chrome.tabs.sendMessage(tabs[0].id, {
  633. action: "getCurrentPageLanguageState"
  634. }, {
  635. frameId: 0
  636. }, pageLanguageState => {
  637. activeTabTranslationInfo = {
  638. tabId: tabs[0].id,
  639. pageLanguageState,
  640. url: tabs[0].url
  641. }
  642. })
  643. })
  644. }
  645.  
  646. let sitesToAutoTranslate = {}
  647.  
  648. function tabsOnRemoved(tabId) {
  649. delete sitesToAutoTranslate[tabId]
  650. }
  651.  
  652. function runtimeOnMessage(request, sender, sendResponse) {
  653. if (request.action === "setPageLanguageState") {
  654. if (sender.tab.active) {
  655. activeTabTranslationInfo = {
  656. tabId: sender.tab.id,
  657. pageLanguageState: request.pageLanguageState,
  658. url: sender.tab.url
  659. }
  660. }
  661. }
  662. }
  663.  
  664. function webNavigationOnCommitted(details) {
  665. if (details.transitionType === "link" && details.frameId === 0 &&
  666. activeTabTranslationInfo.pageLanguageState === "translated" &&
  667. new URL(activeTabTranslationInfo.url).host === new URL(details.url).host) {
  668. sitesToAutoTranslate[details.tabId] = new URL(details.url).host
  669. } else {
  670. delete sitesToAutoTranslate[details.tabId]
  671. }
  672. }
  673.  
  674. function webNavigationOnDOMContentLoaded(details) {
  675. if (details.frameId === 0) {
  676. const host = new URL(details.url).host
  677. if (sitesToAutoTranslate[details.tabId] === host) {
  678. setTimeout(() =>
  679. chrome.tabs.sendMessage(details.tabId, {
  680. action: "autoTranslateBecauseClickedALink"
  681. }, {
  682. frameId: 0
  683. }), 700)
  684. }
  685. delete sitesToAutoTranslate[details.tabId]
  686. }
  687. }
  688.  
  689. function enableTranslationOnClickingALink() {
  690. disableTranslationOnClickingALink()
  691. if (!chrome.webNavigation) return;
  692.  
  693. chrome.tabs.onActivated.addListener(tabsOnActivated)
  694. chrome.tabs.onRemoved.addListener(tabsOnRemoved)
  695. chrome.runtime.onMessage.addListener(runtimeOnMessage)
  696. chrome.webNavigation.onCommitted.addListener(webNavigationOnCommitted)
  697. chrome.webNavigation.onDOMContentLoaded.addListener(webNavigationOnDOMContentLoaded)
  698. }
  699.  
  700. function disableTranslationOnClickingALink() {
  701. activeTabTranslationInfo = {}
  702. sitesToAutoTranslate = {}
  703. chrome.tabs.onActivated.removeListener(tabsOnActivated)
  704. chrome.tabs.onRemoved.removeListener(tabsOnRemoved)
  705. chrome.runtime.onMessage.removeListener(runtimeOnMessage)
  706.  
  707. if (chrome.webNavigation) {
  708. chrome.webNavigation.onCommitted.removeListener(webNavigationOnCommitted)
  709. chrome.webNavigation.onDOMContentLoaded.removeListener(webNavigationOnDOMContentLoaded)
  710. } else {
  711. console.warn("No webNavigation permission")
  712. }
  713. }
  714.  
  715. twpConfig.onChanged((name, newvalue) => {
  716. if (name === "autoTranslateWhenClickingALink") {
  717. if (newvalue == "yes") {
  718. enableTranslationOnClickingALink()
  719. } else {
  720. disableTranslationOnClickingALink()
  721. }
  722. }
  723. })
  724.  
  725. chrome.permissions.onRemoved.addListener(permissions => {
  726. if (permissions.permissions.indexOf("webNavigation") !== -1) {
  727. twpConfig.set("autoTranslateWhenClickingALink", "no")
  728. }
  729. })
  730.  
  731. chrome.permissions.contains({
  732. permissions: ["webNavigation"]
  733. }, hasPermissions => {
  734. if (hasPermissions && twpConfig.get("autoTranslateWhenClickingALink") === "yes") {
  735. enableTranslationOnClickingALink()
  736. } else {
  737. twpConfig.set("autoTranslateWhenClickingALink", "no")
  738. }
  739. })
  740. })
  741.  
Add Comment
Please, Sign In to add comment