| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- export default defineContentScript({
- matches: ["<all_urls>"],
- runAt: "document_idle", // 确保在页面加载完成后运行
-
- main(ctx) {
- console.log('Content script loaded on:', window.location.href);
-
- // 监听来自popup的消息
- const handleMessage = (request: any, sender: any, sendResponse: any) => {
- console.log('Received message:', request);
-
- // 处理测试消息
- if (request.action === "test") {
- sendResponse({ status: "success", message: "Content script is running" });
- return true;
- }
-
- if (request.action === "getImages") {
- try {
- // 获取页面上所有图片元素
- const imageElements = Array.from(document.querySelectorAll('img'));
-
- // 获取背景图片元素
- const allElements = Array.from(document.querySelectorAll('*'));
- const backgroundImages: Array<{url: string, element: string, class: string, id: string}> = [];
-
- // 提取<img>标签的图片
- const imgSources = imageElements
- .map(img => {
- let url = img.src;
- // 处理相对路径
- if (url && !url.startsWith('http') && !url.startsWith('data:')) {
- try {
- url = new URL(url, window.location.origin).href;
- } catch (e) {
- console.warn('Failed to resolve relative URL:', url);
- }
- }
- return {
- url,
- element: 'img',
- class: img.className || '',
- id: img.id || '',
- alt: img.alt || ''
- };
- })
- .filter(img => img.url && (img.url.startsWith('http') || img.url.startsWith('data:')));
-
- // 提取背景图片
- allElements.forEach(element => {
- const computedStyle = window.getComputedStyle(element);
- const backgroundImage = computedStyle.backgroundImage;
-
- // 检查是否有background-image
- if (backgroundImage && backgroundImage !== 'none' && backgroundImage.includes('url')) {
- // 提取URL
- const urlMatch = backgroundImage.match(/url\(["']?(.*?)["']?\)/);
- if (urlMatch && urlMatch[1]) {
- // 解码HTML实体
- const textarea = document.createElement('textarea');
- textarea.innerHTML = urlMatch[1];
- const decodedUrl = textarea.value;
-
- backgroundImages.push({
- url: decodedUrl,
- element: element.tagName.toLowerCase(),
- class: element.className || '',
- id: element.id || ''
- });
- }
- }
- });
-
- // 合并所有图片
- const allImages = [...imgSources, ...backgroundImages];
-
- console.log('Found images:', allImages);
- sendResponse({ images: allImages });
- } catch (error: any) {
- console.error('Error extracting images:', error);
- sendResponse({ images: [], error: error.message });
- }
- return true; // 保持消息通道开放
- }
- };
-
- // 添加消息监听器
- browser.runtime.onMessage.addListener(handleMessage);
-
- // 清理函数
- ctx.onInvalidated(() => {
- browser.runtime.onMessage.removeListener(handleMessage);
- });
- }
- });
|