Chrome扩展使用webRequest拦截谷歌图片搜索页图片遇阻
解决Chrome扩展拦截谷歌图片搜索中base64内嵌图片的问题
你猜的没错,谷歌图片搜索确实会把部分缩略图以base64编码的data:image格式直接嵌入HTML文档里。你的当前代码用webRequest.onBeforeRequest只能拦截独立的图片网络请求,这种内嵌的data URI不会触发网络请求,所以拦不住。下面是具体的解决办法:
核心思路
改用Content Script注入到谷歌图片页面,直接操作DOM:
- 遍历页面中所有包含base64图片的元素(img标签、带背景图的元素)
- 用MutationObserver监听动态加载的内容,实时处理新增的内嵌图片
修改Manifest配置
更新manifest.json,添加Content Script的配置,指定匹配谷歌图片搜索页面:
{ "manifest_version": 2, "name": "My Cool Extension", "version": "1.0", "permissions": [ "<all_urls>", "webRequest", "webRequestBlocking" ], "background": { "scripts": ["background.js"], "persistent": true }, "content_scripts": [ { "matches": ["https://www.google.com/search?tbm=isch*"], "js": ["content.js"], "run_at": "document_start" } ] }
编写Content Script(content.js)
创建content.js文件,实现图片清理和动态监听:
// 清理单个元素的内嵌图片 function clearInlineImage(element) { // 处理img标签的data:image src if (element.tagName === 'IMG' && element.src.startsWith('data:image')) { element.src = ''; element.style.display = 'none'; // 也可替换为自定义占位图 } // 处理元素的背景图(background-image/background) const bgStyle = element.style.backgroundImage || element.style.background; if (bgStyle && bgStyle.startsWith('url("data:image')) { element.style.backgroundImage = 'none'; element.style.background = 'none'; } } // 清理当前页面所有内嵌图片 function clearAllInlineImages() { document.querySelectorAll('img').forEach(clearInlineImage); // 遍历所有可能带背景图的元素(可根据实际情况调整选择器) document.querySelectorAll('div, span, a').forEach(clearInlineImage); } // 初始加载时清理一次 clearAllInlineImages(); // 监听DOM变化,处理动态新增的内容 const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { mutation.addedNodes.forEach((node) => { if (node.nodeType === Node.ELEMENT_NODE) { clearInlineImage(node); // 递归处理子元素 node.querySelectorAll('*').forEach(clearInlineImage); } }); }); }); // 配置监听选项:监听子元素新增和属性变化 observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['src', 'style', 'background-image', 'background'] });
补充说明
run_at: "document_start"确保脚本在页面DOM开始构建时就注入,能更早处理初始内嵌图片- 可以根据需求调整
clearInlineImage的处理逻辑,比如替换为自定义占位图而非直接隐藏 - 若需要拦截其他网站的内嵌图片,只需修改
content_scripts里的matches规则
内容的提问来源于stack exchange,提问作者tilde42
相关产品推荐
相关产品推荐

