给花瓣的图加上“下载”按钮,方便下载
目前為
// ==UserScript==
// @name 花瓣 - 添加下载按钮
// @namespace http://tampermonkey.net/
// @version 0.4
// @description 给花瓣的图加上“下载”按钮,方便下载
// @author 潘志城_Neo
// @match *://huaban.com/*
// @match *://hbimg.huabanimg.com/*
// @grant GM_download
// @grant GM_notification
// ==/UserScript==
(function () {
'use strict';
// 所有图片
var allImages = []
var interval = null
function main() {
document.addEventListener('scroll', throttle(addDownloadBtn, 300))
interval = setInterval(() => {
if (allImages.length === 0) {
addDownloadBtn()
} else {
clearInterval(interval)
}
}, 1000);
} main()
/**
* 添加下载按钮(如果已有按钮,就不添加)
*/
function addDownloadBtn() {
allImages = document.querySelectorAll('.main .infinite-scroll-component .hb-image')
allImages.forEach(dom => {
// 图片标题和样式
var imgInfo = {
title: dom.getAttribute('alt'),
src: dom.getAttribute('src')
}
// 和包含图片的a标签同级的节点
const tempList = dom.parentNode.parentNode.childNodes
const imgNode = tempList[tempList.length - 1]
const lookNode = tempList[tempList.length - 2]
if (lookNode.querySelectorAll('.neo_add').length === 0) {
var downloadBtn = document.createElement('div')
downloadBtn.className = 'neo_add'
downloadBtn.innerText = '下载'
downloadBtn.addEventListener('click', () => {
downloadImage(imgInfo)
GM_notification({ text: imgInfo.title, title: "图片已添加下载", timeout: 2000 })
})
downloadBtn.style.cssText = 'color:#ffffff ;background-color:#1AB37D;border-radius:8px;padding:3px 12px;cursor:pointer'
lookNode.insertBefore(downloadBtn, null)
}
});
}
/**
* 下载图片
* @param {Object} imgInfo src:图片链接; title:图片标题
*/
function downloadImage(imgInfo) {
//替换文件名中不能有的字符
let sign_list = ["\\*", "\\'", '\\"', "<", ">", "\\?", "\\.", "\\|", "\\/"]
for (let i = 0; i < sign_list.length; i++) {
var reg = "/" + sign_list[i] + "/g";
var title = imgInfo.title
if (title) {
imgInfo.title = imgInfo.title.replace(eval(reg), "_");
} else {
imgInfo.title = '无标题'
}
}
imgInfo.src = imgInfo.src.replace('_fw240/format/webp', '')
//启用油猴的增强下载函数,可跨域
GM_download({
url: imgInfo.src,
name: imgInfo.title,
onload: function () {
//下载完成之后,右下角弹窗通知。
GM_notification({ text: imgInfo.title, title: "图片已完成下载", timeout: 5000 })
},
});
}
function throttle(cb, wait = 300) {
let last = 0;
return function () {
var now = new Date().getTime();;
if (now - last > wait) {
cb.call(this);
last = new Date().getTime();;
}
}
}
})();