You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chrome扩展中按图片长宽筛选指定图片及代码整合咨询

How to Modify Your Chrome Extension to Download a Specific Image by Dimensions

Hey there! Let's walk through adjusting your extension to target and download only that specific image you need, along with some better filtering strategies to make the process more reliable.

1. Where to Embed the Dimension-Checking Code

Your existing scriptCodeCollect function is the ideal spot to add image dimension filtering—it’s where you’re currently gathering all images from the page. Instead of grabbing every <img> tag, we’ll modify this section to only keep images that match your target width/height criteria.

The core idea is to replace the broad image collection with a targeted check: loop through each image, validate its dimensions, and only add the matching image’s source to your download list.

2. Better Image Filtering Strategies

Your dimension-based approach is a great start, but we can refine it for more accuracy:

  • Use natural dimensions, not rendered ones: image.naturalWidth and image.naturalHeight return the actual pixel size of the image file, not the size it’s displayed at (which might be altered by CSS styles).
  • Wait for images to load: Before checking dimensions, ensure images are fully loaded—otherwise you might get incorrect 0x0 values.
  • Skip base64 images: Filter out data:image/ URLs since you likely don’t need to download embedded base64 images.
  • Flexible matching: Instead of hardcoding exact dimensions, you could check for a minimum size or aspect ratio (e.g., width/height ≈ 0.705 for a 1000x1419 image) if the target image’s size varies slightly.

3. Modified Key Code Snippets

Updated scriptCodeCollect in popup.js

This version filters images by natural dimensions, skips base64, and stops after finding the first matching image (since you only need one):

const scriptCodeCollect = `(function() {
    let imagestodownload = [];
    // Wait for all images to finish loading before checking dimensions
    Promise.all(Array.from(document.images).map(img => {
        if (img.complete) return Promise.resolve(img);
        return new Promise(resolve => img.onload = () => resolve(img));
    })).then(loadedImages => {
        loadedImages.forEach(image => {
            const { naturalWidth: width, naturalHeight: height } = image;
            console.log("Image Size: " + width + "x" + height);
            
            // Replace with your target dimensions or custom criteria
            const isTargetImage = width === 1000 && height === 1419;
            const isNotBase64 = !image.currentSrc.startsWith('data:image/');
            
            if (isTargetImage && isNotBase64) {
                imagestodownload.push(image.currentSrc);
                // Exit early after finding the first match
                return;
            }
        });
        
        chrome.storage.local.set({ savedImages: imagestodownload }, () => {
            console.log("Collected " + imagestodownload.length + " target image(s)");
        });
    });
})();`;

Adjust Background.js for Single Image Download

Since you only need to download one image, modify the message listener to avoid unnecessary loops:

chrome.runtime.onMessage.addListener(function(message, callback) {
    console.log("Received image source(s):", message.savedImages);
    const targetSrc = message.savedImages[0];
    if (targetSrc) {
        chrome.storage.local.get(['foo'], function(items) {
            const urlfilename = items.foo;
            chrome.downloads.download({ url: targetSrc, filename: `${urlfilename}.png` }, () => {
                console.log("Started download for target image");
            });
        });
    }
});

4. Quick Cleanup Tips for Your Existing Code

  • You have nested chrome.tabs.query calls in popup.js—simplify this by reusing the initial tabs variable instead of querying twice.
  • The sleep delays work, but consider using async/await for cleaner asynchronous code instead of chaining then() calls.
  • In background.js, your bkpg variable is scoped inside the chrome.storage.local.get callback, so it won’t be accessible in the message listener as written—adjust the scope if you still need it for page numbering.

内容的提问来源于stack exchange,提问作者smartguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:56:47