效果
代码
项目结构:
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);
console.log(location.origin);
const title = [ "必应", "Bing" ];
// 根据 title 判断当前页面是否为必应搜索引擎的首页
if((location.origin === "https://cn.bing.com") && (title.indexOf(document.title) === -1)) {
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", "32px");
button.style.setProperty("letter-spacing", "1px");
button.style.setProperty("line-height", "32px");
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("top", "8px");
// 为按键注册一个点击事件,当用户点击之后,弹出保存背景图片的对话框
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);
}