普通视图

发现新文章,点击刷新页面。
昨天以前首页

别再乱装图片插件了!我手写了一个,能扒光整个网页(含背景/iframe/Shadow DOM)

作者 kyriewen
2026年4月28日 18:47

开场白

我真的受够了,每次想从网页批量保存图片,要么右键被禁用,要么装了五六个插件还漏掉一半的 CSS 背景图,要么好不容易抓到图了,却发现插件在后台偷偷上报我的浏览记录。

于是我自己写了一个 —— Image Harvest。它能把网页里所有图片(包括 <img>、CSS 背景、iframe 内嵌、甚至 Shadow DOM 里的)全部扒出来,一键打包 ZIP,而且本地处理,零追踪。

点击立即体验

hero.gif

这篇文章不讲产品吹水,只说技术实现:MV3 踩坑、深度图片提取、客户端感知哈希去重、Side Panel + Popup 双形态共存。干货 + 代码 + 真实踩坑记录,希望对写 Chrome 插件的朋友有帮助。


一、为什么我要自己写一个图片下载插件?

现有的同类插件,我试过 10+ 个,普遍三个问题:

  1. 抓不全:只能抓 <img>,CSS background-imageiframe、Shadow DOM 里的图基本放弃。
  2. 有隐私风险:manifest 里申请 <all_urls> + webRequest,还往未知服务器发数据。
  3. 体验拉胯:批量下载要么一张张点,要么 ZIP 包里一半是占位图。

所以我决定自己造轮子。核心目标:

  • 不漏图(递归提取所有图片源)
  • 不监守自盗(纯本地,零数据收集)
  • 好用(侧边栏/弹窗双模式、暗色主题、3 档密度)

二、Manifest V3 的几个坑(附解法)

2.1 Service Worker 冷启动

V3 用 service worker 替代 V2 的常驻 background page。它会在几秒无活动后休眠,导致下次调用时变量全丢。

解决方案:用 chrome.storage.session 缓存关键状态。

// 抓取完成后存入 session
await chrome.storage.session.set({ 
  lastExtract: { images, timestamp: Date.now() } 
});

// 下次打开面板时恢复
const cached = await chrome.storage.session.get('lastExtract');
if (cached && Date.now() - cached.timestamp < 60000) {
  return cached.images;
}

collection.jpg

2.2 远程代码被禁止

V3 完全禁止执行从外部下载的脚本。对我没影响:Image Harvest 所有代码本地打包,不依赖任何远程配置。

2.3 webRequestdeclarativeNetRequest 替代

如果你需要修改网络请求(如给图片请求加 header),现在只能用声明式规则,灵活性降低。不过图片下载器不需要这玩意儿。


三、深度图片提取:从 <img> 到 Shadow DOM

3.1 基础提取:<img><picture>

function extractSimpleImages() {
  const urls = [];
  document.querySelectorAll('img').forEach(img => {
    if (img.src) urls.push(img.src);
  });
  document.querySelectorAll('picture source').forEach(source => {
    if (source.srcset) {
      const highest = source.srcset.split(',').pop().trim().split(' ')[0];
      urls.push(highest);
    }
  });
  return urls;
}

3.2 提取 CSS background-image

很多网站的 Banner、图标都用背景图实现,必须挖出来。

function extractBgImages(root = document) {
  const elements = root.querySelectorAll('*');
  const bgUrls = [];
  for (let i = 0; i < Math.min(elements.length, 2000); i++) {
    const bg = getComputedStyle(elements[i]).backgroundImage;
    if (bg && bg !== 'none') {
      const match = bg.match(/url\(["']?([^"')]+)["']?\)/);
      if (match) bgUrls.push(match[1]);
    }
  }
  return bgUrls;
}

batch-download.jpg

3.3 递归 Shadow DOM

现代前端框架(React/Vue)常把图片封装在 Shadow DOM 里,必须递归遍历。

function extractFromShadowDOM(root = document) {
  let results = [];
  // 普通图片
  results.push(...extractSimpleImages(root));
  results.push(...extractBgImages(root));
  // 递归 Shadow DOM
  const hosts = root.querySelectorAll('*');
  hosts.forEach(host => {
    if (host.shadowRoot) {
      results.push(...extractFromShadowDOM(host.shadowRoot));
    }
  });
  return results;
}

multi-tab-extract.jpg

3.4 iframe 处理

同源 iframe 可以用 chrome.scripting.executeScript 注入提取函数。需要 webNavigation 权限获取所有 frame。

const frames = await chrome.webNavigation.getAllFrames({ tabId });
for (const frame of frames) {
  if (frame.parentFrameId !== -1) continue; // 只处理顶层 iframe
  const injection = await chrome.scripting.executeScript({
    target: { tabId, frameIds: [frame.frameId] },
    func: extractFromShadowDOM,
  });
  // 合并结果...
}

四、客户端感知哈希(pHash)实现相似图去重

很多用户反馈:“下载 100 张图,里面有 30 张是重复的缩略图”。所以我在 Pro 版中加了相似图检测。

4.1 算法选择:dHash

  • 速度快(纯前端)
  • 对缩放、轻微裁剪不敏感
  • 汉明距离 ≤ 5 判定为相似

4.2 核心代码

async function computeDHash(blob) {
  const img = await createImageBitmap(blob);
  const canvas = new OffscreenCanvas(9, 8);
  const ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0, 9, 8);
  const data = ctx.getImageData(0, 0, 9, 8).data;
  
  // 转灰度
  const gray = [];
  for (let i = 0; i < data.length; i += 4) {
    gray.push(0.299 * data[i] + 0.587 * data[i+1] + 0.114 * data[i+2]);
  }
  
  // 差分哈希
  let hash = 0n;
  for (let row = 0; row < 8; row++) {
    for (let col = 0; col < 7; col++) {
      const left = gray[row * 9 + col];
      const right = gray[row * 9 + col + 1];
      if (right > left) hash |= (1n << BigInt(row * 7 + col));
    }
  }
  return hash;
}

4.3 Worker 中运行,不阻塞 UI

const worker = new Worker('phash-worker.js');
worker.postMessage({ blob });
worker.onmessage = (e) => {
  console.log(`哈希: ${e.data.hash}`);
};

reverse-search.jpg


五、Side Panel + Popup 双模式共存

Chrome 115+ 支持 Side Panel,但老用户习惯 Popup。我两个都要。

实现要点

  • manifest 中配置 side_panel.default_path = "sidepanel.html"
  • action.default_popup 留空,动态控制
chrome.action.onClicked.addListener(async (tab) => {
  const settings = await getAppSettings();
  if (settings.useSidePanel) {
    await chrome.sidePanel.open({ tabId: tab.id });
  } else {
    await chrome.action.setPopup({ tabId: tab.id, popup: 'popup.html' });
    chrome.action.openPopup();
  }
});

同一套 UI 代码,通过 window.location.pathname 判断当前模式,微调布局(弹窗固定 620×600,侧边栏自适应)。

similar-images.jpg


六、上架 Chrome Web Store 的 4 个雷区

  1. 图标尺寸不全:必须 16/32/48/128 px,缺一个直接驳回。
  2. 描述太短:简短描述 ≤132 字符,要包含核心关键词。
  3. 隐私政策缺失:即使不收集数据,也要写一份说明“不收集什么”。
  4. 权限过度:不需要 <all_urls> 就别写,否则审核会问。

我第一次提交被拒就是因为隐私政策链接 404。补上后 2 天过审。

How to Install Google Chrome Web Browser on Ubuntu 26.04

Google Chrome is a fast web browser with built-in Google account sync, automatic updates, password management, and support for modern web applications. It is not included in the standard Ubuntu repositories because it is proprietary software.

This guide explains how to install Google Chrome on Ubuntu 26.04 using the official Google .deb package.

Info
The official Google Chrome .deb package is available for 64-bit x86 systems. On ARM devices, use Chromium or another ARM-compatible browser.

Quick Reference

Task Command
Download package wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
Install package sudo apt install ./google-chrome-stable_current_amd64.deb
Start Chrome google-chrome
Set as default browser xdg-settings set default-web-browser google-chrome.desktop
Update Chrome sudo apt update && sudo apt upgrade
Uninstall Chrome sudo apt remove google-chrome-stable
Check repository file cat /etc/apt/sources.list.d/google-chrome.list

Installing Google Chrome on Ubuntu

The official Chrome package installs the browser and configures the Google APT repository so future updates arrive through the normal Ubuntu update process.

Download Google Chrome

Open a terminal and use wget to download the latest stable package:

Terminal
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

Install Google Chrome

Install the package with apt. This command requires sudo privileges :

Terminal
sudo apt install ./google-chrome-stable_current_amd64.deb

When prompted, enter your password and confirm the installation.

Starting Google Chrome

Open the Activities overview, search for “Google Chrome”, and launch it:

Open Google Chrome on Ubuntu 26.04

You can also start Chrome from the terminal:

Terminal
google-chrome

When Chrome starts for the first time, it asks whether you want to set it as the default browser and send crash reports:

Google Chrome default browser prompt on Ubuntu 26.04

Chrome then opens the welcome page:

Google Chrome welcome page on Ubuntu 26.04

From here, you can sign in with your Google account and sync bookmarks, history, passwords, and extensions.

Set Chrome as Default Browser

To set Chrome as the default browser from the command line, run:

Terminal
xdg-settings set default-web-browser google-chrome.desktop

Verify the current default browser:

Terminal
xdg-settings get default-web-browser
output
google-chrome.desktop

Updating Google Chrome

The Chrome package adds the Google repository to your system. Check the repository file with cat :

Terminal
cat /etc/apt/sources.list.d/google-chrome.list

The file should contain a Google Chrome repository entry for the stable channel.

Chrome updates are installed through the standard Ubuntu update workflow:

Terminal
sudo apt update
sudo apt upgrade

Uninstalling Google Chrome

To remove Google Chrome, run:

Terminal
sudo apt remove google-chrome-stable

Remove packages that are no longer needed:

Terminal
sudo apt autoremove

If you also want to remove the Google Chrome repository file, delete it and update the package index:

Terminal
sudo rm /etc/apt/sources.list.d/google-chrome.list
sudo apt update

Troubleshooting

The installation fails with dependency errors
Fix broken dependencies and repeat the installation:

Terminal
sudo apt --fix-broken install
sudo apt install ./google-chrome-stable_current_amd64.deb

Chrome does not start after installation
Close any running Chrome processes and start it again:

Terminal
pkill -f chrome
google-chrome

The repository file is missing
Reinstall the downloaded package so the Chrome repository is recreated:

Terminal
sudo apt install ./google-chrome-stable_current_amd64.deb

FAQ

What is the difference between Chrome and Chromium?
Chromium is the open-source browser project that Chrome is based on. Chrome adds proprietary media codecs, Google account integration, and Google-managed update packaging.

Can I install Chrome Beta or Dev on Ubuntu?
Yes. Download the Beta or Dev .deb package from Google and install it with apt in the same way as the stable package.

Does Chrome update automatically on Ubuntu?
Chrome is updated by Ubuntu’s package manager after the Google repository is added. Run sudo apt update && sudo apt upgrade to install available updates.

Conclusion

Google Chrome installs on Ubuntu 26.04 through the official .deb package. After installation, Chrome receives updates from the Google repository along with your other system packages.

How to Install Google Chrome Web Browser on Ubuntu 24.04

Google Chrome is a fast and secure web browser built for the modern web. It is available for all major operating systems and allows you to sync bookmarks, history, and passwords across devices.

This guide explains how to install Google Chrome on Ubuntu 24.04 using the official Google package and repository.

Info
The official Google Chrome .deb package is available for 64-bit x86 (amd64) systems only. On ARM devices, use Chromium or another ARM-compatible browser.

Quick Reference

Task Command
Download package wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
Install package sudo apt install ./google-chrome-stable_current_amd64.deb
Start Chrome google-chrome
Set as default browser xdg-settings set default-web-browser google-chrome.desktop
Update Chrome sudo apt update && sudo apt upgrade
Uninstall Chrome sudo apt remove google-chrome-stable
Verify repo file cat /etc/apt/sources.list.d/google-chrome.list

Installing Google Chrome on Ubuntu

Chrome is not open source and is not included in the standard Ubuntu repositories. The official .deb package adds the Google signing key and repository so Chrome stays updated automatically.

Download Google Chrome

Open a terminal and use wget to download the latest stable package:

Terminal
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

Install Google Chrome

Install the package with apt. Running this command requires sudo privileges :

Terminal
sudo apt install ./google-chrome-stable_current_amd64.deb

When prompted, enter your password to complete the installation.

Starting Google Chrome

Open the Activities overview by pressing the Super key, search for “Google Chrome”, and launch it:

Open Google Chrome on Ubuntu 24.04

You can also start Chrome from the terminal:

Terminal
google-chrome

When you start Chrome for the first time, you will be asked whether you want to set it as the default browser and enable crash reports:

Google Chrome default browser prompt on Ubuntu 24.04

Chrome then opens the welcome page:

Google Chrome welcome page on Ubuntu 24.04

From here, you can sign in with your Google account and sync your settings.

Set Chrome as Default Browser

To set Chrome as the default browser from the command line, run:

Terminal
xdg-settings set default-web-browser google-chrome.desktop

To verify the current default browser:

Terminal
xdg-settings get default-web-browser
output
google-chrome.desktop

Updating Google Chrome

During installation, the official Google repository is added to your system. Verify the repository file with cat :

Terminal
cat /etc/apt/sources.list.d/google-chrome.list

Example output:

output
### THIS FILE IS AUTOMATICALLY CONFIGURED ###
# You may comment out this entry, but any other modifications may be lost.
deb [arch=amd64] https://dl.google.com/linux/chrome/deb/ stable main

Chrome updates are delivered through the standard Ubuntu update process:

Terminal
sudo apt update && sudo apt upgrade

Uninstalling Google Chrome

To remove Google Chrome from your system, run:

Terminal
sudo apt remove google-chrome-stable

Then clean up unused dependencies:

Terminal
sudo apt autoremove

Troubleshooting

The installation fails with dependency errors
Fix broken dependencies and re-run the install:

Terminal
sudo apt --fix-broken install
sudo apt install ./google-chrome-stable_current_amd64.deb

Chrome does not start after installation
Close any running Chrome processes and start it again:

Terminal
pkill -f chrome
google-chrome

Repository file is missing
Reinstall the package to recreate the repository file:

Terminal
sudo apt install ./google-chrome-stable_current_amd64.deb

FAQ

What is the difference between Chrome and Chromium?
Chromium is the open-source project that Chrome is built on. Chrome adds proprietary features such as automatic updates, licensed media codecs (AAC, H.264), and tighter Google account integration.

How do I import bookmarks from another browser?
Open Chrome, go to Settings > Import bookmarks and settings, and select the browser you want to import from.

Can I install Chrome Beta or Dev channels?
Yes. Replace google-chrome-stable with google-chrome-beta or google-chrome-unstable in the download URL and install command.

Conclusion

Google Chrome installs on Ubuntu 24.04 using the official .deb package, which also configures the Google repository for automatic updates.

If you have any questions, feel free to leave a comment below.

❌
❌