Add a button for downloading bing-daily-pictures.添加一个必应每日图片下载按钮。
目前為
// ==UserScript==
// @name Bing Daily Picture Download button|必应每日图片下载按钮
// @namespace https://greasyfork.org/en/users/131965-levinit
// @author levinit
// @description Add a button for downloading bing-daily-pictures.添加一个必应每日图片下载按钮。
// @include *://cn.bing.com/
// @include *://www.bing.com/
// @include *://www.bing.com/?*
// @include *://cn.bing.com/?*
// @run-at document-start
// @version 0.1.6
// @grant none
// ==/UserScript==
//todo 自定义图片名字
//按钮信息
const btnInfo = {
imgUrl: '', //图片地址
imgName: '', //图片名字
btnId: 'download-btn', //按钮id
//按钮样式
btnStyle: 'display: inline-block;padding: 0.25em;border-radius: 0.25em;position: fixed;z-index: 1000;right: 20%;top: 12%;background-color: #c3d1cf94;font-size: 1.5em;',
//按钮文字
btnText: function () {
let text = 'Download Today Bing Picture'
//根据不同语言设置按钮文字
switch (navigator.language) {
case 'zh':
case 'zh-CN':
case 'zh-SG':
text = '下载今日必应图片'
break;
default:
break;
}
return text
}
}
window.addEventListener(
'load',
function () {
//进入bing页面后 图片地址写在了一个id为'bgLink'的a元素的href属性中
const initUrl = document.getElementById('bgLink').href
if (initUrl) {
getImg(initUrl) //获取图片信息
addBtn(btnInfo) //添加按钮
refreshBtn(btnInfo) //绑定更新下载地址和图片名字的事件
}
}, {
once: true
})
//-----获取图片信息
function getImg(url) {
btnInfo.imgUrl = url
// const re = /(?<=id=).+\.(jpg|png)/ //慎用:某些浏览器还不支持向前查找
btnInfo.imgName = /id=.+?\.(jpg|png)/.exec(url)[0].replace('id=', '')
}
//-------添加下载按钮
function addBtn(info) {
const btn = document.createElement('a')
const text = info.btnText()
btn.appendChild(document.createTextNode(text)) //加入下载按钮文字内容
btn.id = info.btnId //添加下载按钮对象的id
btn.style.cssText = info.btnStyle //设置下载按钮的样式
btn.href = info.imgUrl //图片下载地址
btn.download = info.imgName //添加下载按钮下载属性——要下载的图片的名称
document.body.appendChild(btn) //将下载按钮对象注入页面中
}
//-----更新下载按钮
function refreshBtn(info) {
document.getElementById(info.btnId).onmouseover = function () {
//从id为bgDiv的元素上获取图片地址
//点击了前一天或后一天按钮后 新图片地址将写在行内style的background-image属性中
let newUrl = document.getElementById('bgDiv').style.backgroundImage
//提取背景图片url(如果没有点击前一天或后一天按钮 background-image不存在 则newUrl内容是空的)
newUrl = newUrl ? newUrl.substring(5, newUrl.length - 2) : ''
//比较前后两个url确定是否更新下载图片的地址和名字
if (newUrl && this.href != location.origin + newUrl) {
getImg(newUrl) //更新图片信息
this.href = info.imgUrl
this.download = info.imgName
}
}
}