谷歌浏览器插件 - 为 Microsoft Bing 搜索引擎首页添加一个【保存背景图片】的按钮(版本 2)

文章目录

效果

在这里插入图片描述

代码

项目结构:

在这里插入图片描述

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);
}

参考

谷歌浏览器插件 - 为 Microsoft Bing 搜索引擎首页添加一个【保存背景图片】的按钮(版本 1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值