content_20250812173708.ts 3.3 KB

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