popup.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. document.addEventListener("DOMContentLoaded", () => {
  2. const modeBtns = {
  3. page: document.getElementById("mode-page"),
  4. paragraph: document.getElementById("mode-paragraph"),
  5. selection: document.getElementById("mode-selection"),
  6. };
  7. const playBtn = document.getElementById("play-btn");
  8. const grammarBtn = document.getElementById("grammar-btn");
  9. const stopBtn = document.getElementById("stop-btn");
  10. const closeBtn = document.getElementById("close-btn");
  11. const statusDiv = document.getElementById("status");
  12. const speedBtn = document.getElementById("speed-btn");
  13. let currentMode = "paragraph";
  14. let currentSpeed = 1.0;
  15. const speedOptions = [1.0, 1.2, 1.5, 2.0];
  16. let audioContext = null;
  17. let currentAudio = null;
  18. let playController = null;
  19. let isPaused = false;
  20. let isPlaying = false;
  21. function initAudioContext() {
  22. if (!audioContext) {
  23. audioContext = new (window.AudioContext || window.webkitAudioContext)();
  24. }
  25. }
  26. function setMode(mode) {
  27. currentMode = mode;
  28. Object.entries(modeBtns).forEach(([key, btn]) => {
  29. btn.classList.toggle("active", key === mode);
  30. });
  31. updateStatus(`Mode: ${mode}`);
  32. }
  33. function setSpeed(speed) {
  34. currentSpeed = speed;
  35. speedBtn.textContent = speed === Math.floor(speed) ? `${speed.toFixed(0)}x` : `${speed}x`;
  36. }
  37. function updatePlayButton() {
  38. if (isPaused) {
  39. playBtn.textContent = "▶";
  40. } else if (isPlaying) {
  41. playBtn.textContent = "⏸";
  42. } else {
  43. playBtn.textContent = "▶";
  44. }
  45. }
  46. function updateStatus(message) {
  47. statusDiv.textContent = message;
  48. }
  49. function handleError(error) {
  50. console.error("Error:", error);
  51. const message = error?.message || "Unknown error";
  52. isPaused = false;
  53. isPlaying = false;
  54. updatePlayButton();
  55. updateStatus(`Error: ${message.replace(/^Error:\s*/i, "")}`);
  56. }
  57. // ---------- Mode Switching ----------
  58. Object.entries(modeBtns).forEach(([key, btn]) => {
  59. btn.addEventListener("click", () => setMode(key));
  60. });
  61. // ---------- Close ----------
  62. closeBtn.addEventListener("click", async () => {
  63. try {
  64. const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  65. if (tab?.id) {
  66. chrome.tabs.sendMessage(tab.id, { action: "deactivatePlayer" }).catch(() => {});
  67. }
  68. } catch (e) {
  69. console.error(e);
  70. }
  71. });
  72. // ---------- Speed ----------
  73. speedBtn.addEventListener("click", () => {
  74. const idx = speedOptions.indexOf(currentSpeed);
  75. const next = speedOptions[(idx + 1) % speedOptions.length];
  76. setSpeed(next);
  77. });
  78. // ---------- Play / Pause / Resume ----------
  79. playBtn.addEventListener("click", async () => {
  80. try {
  81. if (isPaused && currentAudio) {
  82. const resumed = await resumeCurrentAudio();
  83. if (!resumed) {
  84. updateStatus("Nothing to resume");
  85. }
  86. return;
  87. }
  88. if (isPlaying && currentAudio && !currentAudio.paused) {
  89. const paused = pauseCurrentAudio();
  90. if (!paused) {
  91. updateStatus("Nothing is playing");
  92. }
  93. return;
  94. }
  95. initAudioContext();
  96. await getPlayPermission();
  97. const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  98. if (!tab?.id) {
  99. updateStatus("Unable to access current tab");
  100. return;
  101. }
  102. let payload = null;
  103. if (currentMode === "selection") {
  104. const selectedText = await extractSelectedText(tab.id);
  105. if (!selectedText) {
  106. updateStatus("No text is selected");
  107. return;
  108. }
  109. payload = { text: selectedText, scope: "selection" };
  110. } else if (currentMode === "paragraph") {
  111. updateStatus("Finding paragraph near cursor...");
  112. const paragraph = await extractContextualParagraph(tab.id);
  113. if (!paragraph?.text) {
  114. updateStatus("No readable paragraph detected");
  115. return;
  116. }
  117. payload = { ...paragraph, scope: "paragraph" };
  118. } else {
  119. updateStatus("Scanning article body...");
  120. const article = await extractArticleContent(tab.id);
  121. if (!article?.text) {
  122. updateStatus("Could not identify main content");
  123. return;
  124. }
  125. payload = { ...article, scope: "page" };
  126. }
  127. await startConversion(payload);
  128. } catch (error) {
  129. handleError(error);
  130. }
  131. });
  132. // ---------- Grammar ----------
  133. grammarBtn.addEventListener("click", async () => {
  134. try {
  135. const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  136. if (!tab?.id) {
  137. updateStatus("Unable to access current tab");
  138. return;
  139. }
  140. updateStatus("Analyzing grammar...");
  141. grammarBtn.disabled = true;
  142. const response = await new Promise((resolve) => {
  143. chrome.tabs.sendMessage(
  144. tab.id,
  145. { type: "EXECUTE_GRAMMAR", mode: currentMode },
  146. (res) => {
  147. if (chrome.runtime.lastError) {
  148. resolve({ error: chrome.runtime.lastError.message });
  149. return;
  150. }
  151. resolve(res || { error: "No response" });
  152. }
  153. );
  154. });
  155. grammarBtn.disabled = false;
  156. if (response.error) {
  157. updateStatus(`Grammar error: ${response.error}`);
  158. } else {
  159. updateStatus("Grammar highlighted!");
  160. }
  161. } catch (error) {
  162. grammarBtn.disabled = false;
  163. handleError(error);
  164. }
  165. });
  166. // ---------- Stop ----------
  167. stopBtn.addEventListener("click", () => {
  168. stopPlayback();
  169. updateStatus("Playback stopped");
  170. });
  171. // ---------- Text Extraction ----------
  172. async function extractSelectedText(tabId) {
  173. return new Promise((resolve) => {
  174. chrome.scripting.executeScript(
  175. {
  176. target: { tabId },
  177. function: () => {
  178. const selection = window.getSelection();
  179. return selection ? selection.toString().trim() : "";
  180. }
  181. },
  182. (results) => resolve(results?.[0]?.result || "")
  183. );
  184. });
  185. }
  186. async function extractContextualParagraph(tabId) {
  187. return new Promise((resolve) => {
  188. chrome.scripting.executeScript(
  189. {
  190. target: { tabId },
  191. function: () => {
  192. const adLikePattern = /(advert|广告|推广|sponsored|subscribe|buy now|click (here|to)|share this|follow us|免责声明|copyright)/i;
  193. const minLength = 40;
  194. function findParagraphElement(node) {
  195. const blockTags = ["P", "DIV", "ARTICLE", "SECTION", "LI", "BLOCKQUOTE"];
  196. while (node && node !== document.body) {
  197. if (node.nodeType === Node.ELEMENT_NODE && blockTags.includes(node.nodeName)) {
  198. return node;
  199. }
  200. node = node.parentElement;
  201. }
  202. return null;
  203. }
  204. function isVisible(el) {
  205. if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
  206. const rect = el.getBoundingClientRect();
  207. if (!rect || rect.width === 0 || rect.height === 0) return false;
  208. const style = window.getComputedStyle(el);
  209. return style.display !== "none" && style.visibility !== "hidden" && parseFloat(style.opacity) > 0;
  210. }
  211. function cleanText(value) {
  212. return (value || "").replace(/\s+/g, " ").trim();
  213. }
  214. const selection = window.getSelection();
  215. const anchorNode = selection ? selection.anchorNode : null;
  216. if (anchorNode) {
  217. const candidate = findParagraphElement(anchorNode);
  218. if (candidate && isVisible(candidate)) {
  219. const text = cleanText(candidate.innerText);
  220. if (text.length >= minLength && !adLikePattern.test(text)) {
  221. return { text };
  222. }
  223. }
  224. }
  225. const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, {
  226. acceptNode: (node) => {
  227. if (!isVisible(node)) return NodeFilter.FILTER_REJECT;
  228. const validTags = ["P", "DIV", "ARTICLE", "SECTION", "LI", "BLOCKQUOTE"];
  229. if (!validTags.includes(node.nodeName)) return NodeFilter.FILTER_SKIP;
  230. const text = cleanText(node.innerText);
  231. if (text.length < minLength) return NodeFilter.FILTER_SKIP;
  232. if (adLikePattern.test(text)) return NodeFilter.FILTER_SKIP;
  233. return NodeFilter.FILTER_ACCEPT;
  234. }
  235. });
  236. const node = walker.nextNode();
  237. if (node) {
  238. const text = cleanText(node.innerText);
  239. return { text };
  240. }
  241. return null;
  242. }
  243. },
  244. (results) => resolve(results?.[0]?.result || null)
  245. );
  246. });
  247. }
  248. async function extractArticleContent(tabId) {
  249. return new Promise((resolve) => {
  250. chrome.scripting.executeScript(
  251. {
  252. target: { tabId },
  253. function: () => {
  254. const blockedPattern = /(nav|header|footer|aside|breadcrumb|sidebar|advert|promo|sponsor|toolbar|comment|popup|share|related|recommend|subscribe|newsletter)/i;
  255. const adKeywordPattern = /(advertisement|sponsored|promotion|buy now|click here|subscribe|share this|follow us|版权所有|广告|推广)/i;
  256. function cleanText(value) {
  257. return (value || "").replace(/\s+/g, " ").trim();
  258. }
  259. function isVisible(el) {
  260. if (!el || el.nodeType !== Node.ELEMENT_NODE) return false;
  261. const rect = el.getBoundingClientRect();
  262. if (!rect || rect.width === 0 || rect.height === 0) return false;
  263. const style = window.getComputedStyle(el);
  264. if (style.display === "none" || style.visibility === "hidden" || parseFloat(style.opacity) === 0) {
  265. return false;
  266. }
  267. return true;
  268. }
  269. function scoreNode(node) {
  270. const text = cleanText(node.innerText);
  271. if (text.length < 300) return 0;
  272. const links = node.querySelectorAll("a");
  273. let linkTextLength = 0;
  274. links.forEach((link) => {
  275. linkTextLength += cleanText(link.innerText).length;
  276. });
  277. const linkDensity = text.length ? Math.min(linkTextLength / text.length, 1) : 0;
  278. const headingPenalty = node.querySelectorAll("h1,h2,h3").length * 40;
  279. const meta = `${node.className || ""} ${node.id || ""}`;
  280. const adPenalty = blockedPattern.test(meta) ? 200 : 0;
  281. return text.length * (1 - linkDensity) - headingPenalty - adPenalty;
  282. }
  283. let candidates = Array.from(document.querySelectorAll("article, main, section"));
  284. candidates = candidates.filter(
  285. (node) => isVisible(node) && !blockedPattern.test(`${node.className || ""} ${node.id || ""}`)
  286. );
  287. if (!candidates.length) {
  288. candidates = Array.from(document.querySelectorAll("div"));
  289. candidates = candidates.filter(
  290. (node) => isVisible(node) && !blockedPattern.test(`${node.className || ""} ${node.id || ""}`)
  291. );
  292. }
  293. candidates.sort((a, b) => scoreNode(b) - scoreNode(a));
  294. const best = candidates[0] || document.body;
  295. const bannedSelectors = [
  296. "header", "nav", "aside", "footer", "form", "button",
  297. "#header", "#nav", "#footer", "#sidebar",
  298. '[id*="ad" i]', '[class*="ad" i]',
  299. '[id*="promo" i]', '[class*="promo" i]',
  300. '[id*="sponsor" i]', '[class*="sponsor" i]'
  301. ];
  302. const uniqueTexts = new Set();
  303. const chunks = [];
  304. const walker = document.createTreeWalker(best, NodeFilter.SHOW_ELEMENT, {
  305. acceptNode: (node) => {
  306. if (!isVisible(node)) return NodeFilter.FILTER_REJECT;
  307. for (const selector of bannedSelectors) {
  308. if (typeof selector === "string") {
  309. try {
  310. if (node.closest(selector)) {
  311. return NodeFilter.FILTER_REJECT;
  312. }
  313. } catch (error) {
  314. // ignore invalid selectors
  315. }
  316. }
  317. }
  318. if (/^H[1-6]$/i.test(node.nodeName)) {
  319. return NodeFilter.FILTER_REJECT;
  320. }
  321. const allowedTags = ["P", "DIV", "SECTION", "ARTICLE", "LI", "BLOCKQUOTE", "PRE"];
  322. if (!allowedTags.includes(node.nodeName)) {
  323. return NodeFilter.FILTER_SKIP;
  324. }
  325. const text = cleanText(node.innerText);
  326. if (text.length < 40) return NodeFilter.FILTER_SKIP;
  327. if (adKeywordPattern.test(text)) return NodeFilter.FILTER_SKIP;
  328. return NodeFilter.FILTER_ACCEPT;
  329. }
  330. });
  331. while (walker.nextNode()) {
  332. const text = cleanText(walker.currentNode.innerText);
  333. if (!text) continue;
  334. const key = text.slice(0, 120);
  335. if (uniqueTexts.has(key)) continue;
  336. uniqueTexts.add(key);
  337. chunks.push(text);
  338. }
  339. if (!chunks.length) {
  340. const fallback = cleanText(best.innerText);
  341. if (fallback.length < 80) {
  342. return null;
  343. }
  344. return {
  345. text: fallback.slice(0, 8000),
  346. meta: { paragraphCount: 1, charCount: Math.min(8000, fallback.length) }
  347. };
  348. }
  349. const combined = chunks.join("\n\n");
  350. const truncated = combined.length > 8000 ? combined.slice(0, 8000) : combined;
  351. return {
  352. text: truncated,
  353. meta: { paragraphCount: chunks.length, charCount: truncated.length }
  354. };
  355. }
  356. },
  357. (results) => resolve(results?.[0]?.result || null)
  358. );
  359. });
  360. }
  361. // ---------- Audio Helpers ----------
  362. async function getPlayPermission() {
  363. return new Promise((resolve) => {
  364. const dummyAudio = new Audio("data:audio/wav;base64,UklGRl9vT19XQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YU");
  365. dummyAudio
  366. .play()
  367. .then(() => {
  368. dummyAudio.pause();
  369. dummyAudio.remove();
  370. resolve();
  371. })
  372. .catch(() => {
  373. updateStatus("Click again to enable audio playback");
  374. resolve();
  375. });
  376. });
  377. }
  378. function pauseCurrentAudio() {
  379. if (!currentAudio || currentAudio.paused || currentAudio.ended) {
  380. return false;
  381. }
  382. currentAudio.pause();
  383. isPaused = true;
  384. isPlaying = false;
  385. updatePlayButton();
  386. updateStatus("Playback paused");
  387. return true;
  388. }
  389. async function resumeCurrentAudio() {
  390. if (!currentAudio || !currentAudio.paused || currentAudio.ended) {
  391. isPaused = false;
  392. isPlaying = false;
  393. updatePlayButton();
  394. return false;
  395. }
  396. initAudioContext();
  397. if (audioContext.state !== "running") {
  398. await audioContext.resume();
  399. }
  400. await currentAudio.play();
  401. isPaused = false;
  402. isPlaying = true;
  403. updatePlayButton();
  404. updateStatus("Resuming...");
  405. return true;
  406. }
  407. function stopPlayback() {
  408. if (playController) {
  409. playController.abort();
  410. playController = null;
  411. }
  412. if (currentAudio) {
  413. currentAudio.pause();
  414. currentAudio = null;
  415. }
  416. isPaused = false;
  417. isPlaying = false;
  418. updatePlayButton();
  419. }
  420. async function startConversion(payload) {
  421. try {
  422. if (!payload?.text) {
  423. updateStatus("No readable text");
  424. return;
  425. }
  426. stopPlayback();
  427. playController = new AbortController();
  428. isPaused = false;
  429. isPlaying = true;
  430. updatePlayButton();
  431. let message = "Starting playback...";
  432. if (payload.scope === "selection") {
  433. message = "Playing selected text...";
  434. } else if (payload.scope === "paragraph") {
  435. message = "Playing paragraph...";
  436. } else if (payload.scope === "page") {
  437. const count = payload.meta?.paragraphCount;
  438. message = count ? `Playing article (${count} sections)...` : "Playing article...";
  439. }
  440. updateStatus(message);
  441. await streamTTSAndPlay(payload.text, playController.signal);
  442. playController = null;
  443. isPaused = false;
  444. isPlaying = false;
  445. updatePlayButton();
  446. updateStatus("Playback finished");
  447. } catch (error) {
  448. handleError(error);
  449. }
  450. }
  451. async function streamTTSAndPlay(text, signal) {
  452. try {
  453. const port = chrome.runtime.connect({ name: "tts-stream" });
  454. const playQueue = [];
  455. let isPlayingQueue = false;
  456. let streamCompleted = false;
  457. const abortHandler = () => {
  458. playQueue.length = 0;
  459. port.disconnect();
  460. if (currentAudio) {
  461. currentAudio.pause();
  462. currentAudio = null;
  463. }
  464. isPaused = false;
  465. isPlaying = false;
  466. updatePlayButton();
  467. };
  468. signal.addEventListener("abort", abortHandler, { once: true });
  469. port.postMessage({
  470. action: "startStreamTTS",
  471. text,
  472. voice: "af_heart",
  473. speed: currentSpeed
  474. });
  475. port.onMessage.addListener((response) => {
  476. if (signal.aborted) {
  477. return;
  478. }
  479. if (response.error) {
  480. console.error("TTS error:", response.error);
  481. updateStatus(`TTS error: ${response.error}`);
  482. port.disconnect();
  483. if (currentAudio) {
  484. currentAudio.pause();
  485. currentAudio = null;
  486. }
  487. isPaused = false;
  488. isPlaying = false;
  489. updatePlayButton();
  490. return;
  491. }
  492. if (response.audio) {
  493. playQueue.push({
  494. audio: response.audio.startsWith("data:") ? response.audio : `data:audio/wav;base64,${response.audio}`,
  495. index: response.index
  496. });
  497. if (!isPlayingQueue) {
  498. void playFromQueue();
  499. }
  500. }
  501. if (response.completed) {
  502. streamCompleted = true;
  503. port.disconnect();
  504. }
  505. });
  506. function playFromQueue() {
  507. if (signal.aborted || !playQueue.length) {
  508. isPlayingQueue = false;
  509. isPlaying = false;
  510. updatePlayButton();
  511. return Promise.resolve();
  512. }
  513. isPlayingQueue = true;
  514. const chunk = playQueue.shift();
  515. return (async () => {
  516. try {
  517. initAudioContext();
  518. if (audioContext.state !== "running") {
  519. await audioContext.resume();
  520. }
  521. currentAudio = new Audio(chunk.audio);
  522. isPaused = false;
  523. isPlaying = true;
  524. updatePlayButton();
  525. updateStatus(`Playing part ${chunk.index + 1}`);
  526. await playAudio(currentAudio);
  527. currentAudio = null;
  528. updatePlayButton();
  529. return playFromQueue();
  530. } catch (error) {
  531. console.error("Playback error:", error);
  532. isPlayingQueue = false;
  533. }
  534. })();
  535. }
  536. await new Promise((resolve) => {
  537. port.onDisconnect.addListener(() => {
  538. signal.removeEventListener("abort", abortHandler);
  539. const waitForQueue = () => {
  540. if (!playQueue.length && (!isPlayingQueue || signal.aborted || streamCompleted)) {
  541. resolve();
  542. } else {
  543. setTimeout(waitForQueue, 100);
  544. }
  545. };
  546. waitForQueue();
  547. });
  548. });
  549. } catch (error) {
  550. throw error;
  551. }
  552. }
  553. function playAudio(audio) {
  554. return new Promise((resolve, reject) => {
  555. audio
  556. .play()
  557. .then(() => {
  558. audio.onended = resolve;
  559. audio.onerror = reject;
  560. })
  561. .catch(reject);
  562. });
  563. }
  564. // ---------- Init ----------
  565. setMode("paragraph");
  566. setSpeed(1.0);
  567. updatePlayButton();
  568. });