<script type='text/javascript'>
//<![CDATA[
setTimeout(function() {
// 1. 保留:处理<img>标签(文章内图片)
const googleImages = document.querySelectorAll('img[src*="googleusercontent.com"], img[src*="ggpht.com"]');
googleImages.forEach(img => {
if (!img.src.includes('images.weserv.nl')) {
img.src = 'https://images.weserv.nl/?url=' + encodeURIComponent(img.src);
img.onerror = () => img.src = 'https://picsum.photos/400/300';
}
});
// 2. 保留:处理<meta>标签(首页预览图)
const googleMetaImages = document.querySelectorAll('meta[content*="googleusercontent.com"], meta[content*="ggpht.com"]');
googleMetaImages.forEach(meta => {
const content = meta.getAttribute('content');
if (content && !content.includes('images.weserv.nl')) {
meta.setAttribute('content', 'https://images.weserv.nl/?url=' + encodeURIComponent(content));
}
});
// 3. 新增:处理CSS背景图(首页轮播图等)
const elementsWithBg = document.querySelectorAll('*'); // 遍历所有元素
elementsWithBg.forEach(el => {
const bgStyle = window.getComputedStyle(el).backgroundImage;
// 匹配包含谷歌图片链接的背景图
if (bgStyle.includes('googleusercontent.com') || bgStyle.includes('ggpht.com')) {
// 提取背景图URL(处理URL引号包裹的情况)
const urlMatch = bgStyle.match(/url\(['"]?(.*?)['"]?\)/);
if (urlMatch && urlMatch[1] && !urlMatch[1].includes('images.weserv.nl')) {
const originalUrl = urlMatch[1];
const proxiedUrl = 'https://images.weserv.nl/?url=' + encodeURIComponent(originalUrl);
// 重新设置背景图
el.style.backgroundImage = `url('${proxiedUrl}')`;
}
}
});
}, 1000); // 延长延迟到1000ms,确保CSS样式完全加载
//]]>
</script>
代码说明:
通过window.getComputedStyle(el)获取元素最终渲染的 CSS 样式,识别包含谷歌图片链接的background-image。
用正则表达式/url\(['"]?(.*?)['"]?\)/提取背景图的原始 URL(兼容带引号 / 不带引号的写法)。
将原始 URL 替换为代理链接后,重新通过el.style.backgroundImage赋值,实现背景图加载。
延迟调整到 1000ms:
首页轮播图等元素可能通过 CSS 文件或后续脚本加载样式,延长延迟确保所有 CSS 背景图样式已生成,避免漏处理。