background.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const API_BASE_URL = 'http://117.50.195.224:12012';
  2. async function fetchHighlights(text) {
  3. const response = await fetch(`${API_BASE_URL}/analyze`, {
  4. method: 'POST',
  5. headers: { 'Content-Type': 'application/json' },
  6. body: JSON.stringify({ text })
  7. });
  8. if (!response.ok) {
  9. const detail = await response.text();
  10. throw new Error(detail || '后台服务调用失败。');
  11. }
  12. const data = await response.json();
  13. return data.highlighted_html;
  14. }
  15. async function fetchParagraphHighlights(paragraphs) {
  16. const results = [];
  17. for (const paragraph of paragraphs) {
  18. // Process sequentially to avoid overwhelming the backend.
  19. const highlighted = await fetchHighlights(paragraph);
  20. results.push(highlighted);
  21. }
  22. return results;
  23. }
  24. chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
  25. if (message?.type !== 'GRAMMAR_API_REQUEST') {
  26. return;
  27. }
  28. const { text, paragraphs } = message;
  29. (Array.isArray(paragraphs) && paragraphs.length > 0
  30. ? fetchParagraphHighlights(paragraphs).then((highlightedHtmls) => ({
  31. highlightedHtmls
  32. }))
  33. : fetchHighlights(text).then((highlightedHtml) => ({ highlightedHtml })))
  34. .then((payload) => sendResponse(payload))
  35. .catch((error) => {
  36. sendResponse({ error: error.message || '后台服务调用失败。' });
  37. });
  38. return true; // keep the message channel open for async response
  39. });
  40. chrome.action.onClicked.addListener((tab) => {
  41. if (!tab.id) return;
  42. chrome.tabs.sendMessage(tab.id, { type: 'GRAMMAR_TOGGLE_PANEL' }).catch(() => {});
  43. });