Greasy Fork is available in English.

Bing Daily Picture Download button|必应每日图片下载按钮

Add a button for downloading bing-daily-pictures.添加一个必应每日图片下载按钮。

As of 03.02.2018. See ბოლო ვერსია.

// ==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.4
// @grant       none
// ==/UserScript==

//定时器周期行检测今日必应图片是否加载成功
let timer = setInterval(function() {
  //获取到今日必应图片信息后添加按钮 停止周期检测
  if (getImg()) {
    addBtn(getImg()) //添加下载按钮
    const downloadBtn = document.querySelector('#download-btn') //获取下载按钮对象
    //在下载按钮对象上绑定事件:用户前后切换了必应图片 图片地址和名称会发生改变 当用户移动鼠标到图片上时进行检测
    downloadBtn.onmouseover = function() {
      const newInfo = getImg() //获取图片地址
      if (this.href != newInfo.picUrl) {
        //如果新获取的下载地址与下载按钮的地址不同 就更改下载按钮上的地址及下载图片的名字(download属性)
        this.href = newInfo.picUrl
        this.download = newInfo.picName
      }
    }

    clearInterval(timer) //清除定时器
  }
}, 233)

//获取图片地址
function getImg() {
  // 从行内css属性background-image中获取今日必应图片的url()
  let picUrl = document.querySelector('#bgDiv').style.backgroundImage

  //如果css属性background-image写在外部css或者style标签中
  if (picUrl === '') {
    const style0 = document.styleSheets[0] //获取外部css样式文件对象
    const rules = style0.cssRules.length //获取该css文件中的样式数量
    for (let i = 0; i < rules; i++) {
      //遍历所有样式 找到选择器为#bgDiv的样式的背景图片属性(包含url)
      if (style0.cssRules[i].selectorText === '#bgDiv') {
        picUrl = style0.cssRules[i].style.backgroundImage
      }
    }
  }
  //从背景图片属性中取出图片地址(去掉 前引号url前括号 和 后括号后引号 等字符)
  picUrl = picUrl.substring(5, picUrl.length - 2)
  //从url中取出图片名称
  let picName = picUrl.substring(picUrl.lastIndexOf('/') + 1, picUrl.length)
  return { picUrl, picName }
}

//添加下载按钮
function addBtn(imgInfo) {
  //在必应首页添加下载按钮
  const btn = document.createElement('a')
  let text = null

  //根据不同语言设置下载按钮的文字内容
  if (navigator.language.indexOf('zh') >= 0) {
    text = document.createTextNode('下载今日必应图片')
  } else {
    text = document.createTextNode('Download Today Bing Picture')
  }

  btn.appendChild(text) //加入下载按钮文字内容
  btn.id = 'download-btn'  //添加下载按钮对象的id
   //设置下载按钮对象的样式
  btn.style.cssText =
    '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;'
  btn.download = imgInfo.picName  //添加下载按钮对象的下载属性及下载名称
  btn.href = imgInfo.picUrl  //加入下载地址
  document.body.appendChild(btn)  //将下载按钮对象注入文档中
}