content.ts 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { OptionScript } from "./content_script/OptionScript";
  2. export default defineContentScript({
  3. matches: ["<all_urls>"],
  4. main() {
  5. // 辅助函数:提取背景图片URL
  6. const extractBackgroundUrl = (element: Element): string | null => {
  7. const computedStyle = window.getComputedStyle(element);
  8. const backgroundImage = computedStyle.backgroundImage;
  9. if (backgroundImage && backgroundImage !== 'none' && backgroundImage.includes('url')) {
  10. // 处理包含转义字符的URL
  11. const urlMatch = backgroundImage.match(/url\(["']?(.*?)["']?\)/);
  12. if (urlMatch && urlMatch[1]) {
  13. // 解码HTML实体
  14. let url = urlMatch[1];
  15. const textarea = document.createElement('textarea');
  16. textarea.innerHTML = url;
  17. return textarea.value;
  18. }
  19. }
  20. return null;
  21. };
  22. // 监听来自popup的消息
  23. browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
  24. if (request.action === "getTbodyData") {
  25. // 获取所有tbody中的数据,包括背景图片
  26. const tables = Array.from(document.querySelectorAll('table')).map((table, tableIndex) => {
  27. const tbodies = Array.from(table.querySelectorAll('tbody'));
  28. return tbodies.map(tbody => {
  29. const rows = Array.from(tbody.querySelectorAll('tr'));
  30. return rows.map((row, rowIndex) => {
  31. const cells = Array.from(row.querySelectorAll('td, th'));
  32. return cells.map((cell, cellIndex) => {
  33. // 获取单元格文本内容
  34. const textContent = cell.textContent?.trim() || '';
  35. // 查找单元格内所有带有背景图片的div元素
  36. const divsWithBackground = Array.from(cell.querySelectorAll('div[style*="background-image"]'))
  37. .map((div, divIndex) => {
  38. const backgroundUrl = extractBackgroundUrl(div);
  39. if (backgroundUrl) {
  40. return {
  41. url: backgroundUrl,
  42. className: div.className || '',
  43. style: div.getAttribute('style') || ''
  44. };
  45. }
  46. return null;
  47. })
  48. .filter(item => item !== null);
  49. // 如果找到带背景图片的div,返回包含这些信息的对象
  50. if (divsWithBackground.length > 0) {
  51. return {
  52. text: textContent,
  53. backgroundImages: divsWithBackground
  54. };
  55. }
  56. // 检查单元格本身是否有背景图片
  57. const cellBackgroundUrl = extractBackgroundUrl(cell);
  58. if (cellBackgroundUrl) {
  59. return {
  60. text: textContent,
  61. cellBackgroundUrl: cellBackgroundUrl
  62. };
  63. }
  64. // 否则返回文本内容
  65. return textContent;
  66. });
  67. });
  68. }).flat();
  69. }).flat();
  70. // 过滤掉空表格
  71. const nonEmptyTables = tables.filter(table => table.length > 0);
  72. sendResponse({ tables: nonEmptyTables });
  73. }
  74. // 模拟用户重复性操作
  75. if (request.action === "autoSendMessages") {
  76. OptionScript(request, sender, sendResponse)
  77. }
  78. });
  79. }
  80. });