content_20250812171131.ts 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. export default defineContentScript({
  2. matches: ["<all_urls>"],
  3. main(ctx) {
  4. // 监听来自popup的消息
  5. const handleMessage = (request: any, sender: any, sendResponse: any) => {
  6. if (request.action === "getImages") {
  7. try {
  8. // 获取页面上所有图片元素
  9. const imageElements = Array.from(document.querySelectorAll('img'));
  10. // 获取背景图片元素
  11. const allElements = Array.from(document.querySelectorAll('*'));
  12. const backgroundImages: Array<{url: string, element: string, class: string, id: string}> = [];
  13. // 提取<img>标签的图片
  14. const imgSources = imageElements
  15. .map(img => {
  16. let url = img.src;
  17. // 处理相对路径
  18. if (url && !url.startsWith('http') && !url.startsWith('data:')) {
  19. try {
  20. url = new URL(url, window.location.origin).href;
  21. } catch (e) {
  22. console.warn('Failed to resolve relative URL:', url);
  23. }
  24. }
  25. return {
  26. url,
  27. element: 'img',
  28. class: img.className || '',
  29. id: img.id || '',
  30. alt: img.alt || ''
  31. };
  32. })
  33. .filter(img => img.url && (img.url.startsWith('http') || img.url.startsWith('data:')));
  34. // 提取背景图片
  35. allElements.forEach(element => {
  36. const computedStyle = window.getComputedStyle(element);
  37. const backgroundImage = computedStyle.backgroundImage;
  38. // 检查是否有background-image
  39. if (backgroundImage && backgroundImage !== 'none' && backgroundImage.includes('url')) {
  40. // 提取URL
  41. const urlMatch = backgroundImage.match(/url\(["']?(.*?)["']?\)/);
  42. if (urlMatch && urlMatch[1]) {
  43. // 解码HTML实体
  44. const textarea = document.createElement('textarea');
  45. textarea.innerHTML = urlMatch[1];
  46. const decodedUrl = textarea.value;
  47. backgroundImages.push({
  48. url: decodedUrl,
  49. element: element.tagName.toLowerCase(),
  50. class: element.className || '',
  51. id: element.id || ''
  52. });
  53. }
  54. }
  55. });
  56. // 合并所有图片
  57. const allImages = [...imgSources, ...backgroundImages];
  58. sendResponse({ images: allImages });
  59. } catch (error) {
  60. console.error('Error extracting images:', error);
  61. sendResponse({ images: [], error: error.message });
  62. }
  63. return true; // 保持消息通道开放
  64. }
  65. };
  66. // 添加消息监听器
  67. browser.runtime.onMessage.addListener(handleMessage);
  68. // 清理函数
  69. ctx.onInvalidated(() => {
  70. browser.runtime.onMessage.removeListener(handleMessage);
  71. });
  72. console.log('Content script loaded');
  73. }
  74. });