谷歌浏览器版本信息:版本 94.0.4606.81(正式版本) (64 位)
获取背景图片的链接的思路
在开发者工具 > Network 选项卡中,选择 Img 过滤器,找到背景图片的链接:
接着,在开发者工具 > Elements 选项卡中,根据背景图片的链接,查找哪一个元素使用了这个链接:
找到这个元素之后,就可以使用 JavaScript 获取背景图片的链接。
谷歌浏览器插件的代码实现
思路
- 根据 title 判断当前页面是否为必应搜索引擎的首页;
- 创建一个按键,并按键注册一个点击事件,当用户点击之后,弹出保存背景图片的对话框;
- 将按键添加到必应搜索引擎的首页的 body 中。
实现
新建一个项目:
manifest.json 文件:
{
"name": "Microsoft Bing",
"version": "1.0.0",
"description": "Microsoft Bing - 保存背景图片",
"content_scripts": [{
"matches": [ "https://cn.bing.com/*" ],
"js": ["content-script.js"]
}],
"manifest_version": 2
}
content-script.js 文件:
// https://developer.chrome.com/docs/extensions/mv2/content_scripts/
window.onload = (event) => {
console.log(event)
// console.log(`The ID of the extension is ${chrome.runtime.id}.`)
main()
}
function main() {
console.dir(location);
// 根据 title 判断当前页面是否为必应搜索引擎的首页
if((location.origin === "https://cn.bing.com") && (document.title !== "必应")) {
return;
}
// 创建一个按键
const button = document.createElement("button");
button.innerText = "保存背景图片";
button.style.setProperty("background", "rgba(34, 34, 34, 0.8)");
button.style.setProperty("border", "1px solid rgba(34, 34, 34, 1)");
button.style.setProperty("border-radius", "6px");
button.style.setProperty("color", "rgba(255, 255, 255, 1)");
button.style.setProperty("cursor", "pointer");
button.style.setProperty("height", "40px");
button.style.setProperty("letter-spacing", "1px");
button.style.setProperty("line-height", "38px");
button.style.setProperty("outline", "none");
button.style.setProperty("padding", "0px 10px 0px 10px");
button.style.setProperty("z-index", "20211206");
button.style.setProperty("position", "fixed");
button.style.setProperty("right", "8px");
button.style.setProperty("bottom", "43px");
// 为按键注册一个点击事件,当用户点击之后,弹出保存背景图片的对话框
button.onclick = (event) => {
const imageContainer = document.querySelector(".img_cont");
if(imageContainer) {
const backgroundImageValue = imageContainer.style.getPropertyValue("background-image");
console.log(backgroundImageValue);
let url;
if(backgroundImageValue && backgroundImageValue.startsWith("url")) {
url = new URL(location.origin + backgroundImageValue.slice(5, -2)); // 背景图片的链接
}
console.log(url);
const anchor = document.createElement("a");
anchor.href = url.toString();
anchor.download = url.searchParams.get("id"); // 文件名称
anchor.click();
}
}
// 将按键添加到必应搜索引擎的首页的 body 中
document.body.appendChild(button);
}
测试
在谷歌浏览器的扩展程序页面中,加载已解压的扩展程序,并启用:
接着,打开一个新的必应搜索引擎的首页(如果已经打开,则需要刷新页面,使扩展程序生效),效果如下: