Unsplash 下载文件名修改 Unsplash Change Photo Name

Change the file name of download photo.

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。

您需要先安装用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Unsplash 下载文件名修改 Unsplash Change Photo Name
// @license      MIT License
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  Change the file name of download photo.
// @author       TROJAN
// @match        https://unsplash.com/*
// @require      https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    async function changeName() {
        // 获取下载按钮
        let a = document.querySelector('header > div:last-child > div:last-child > div > a')

        // ----- 图片信息 -----
        // 发布日期
        const date = document.querySelector('time').getAttribute('datetime').slice(0, 10).replace(/-/g, ".");
        // console.log('日期', date)

        // 位置
        let location = document.querySelector('header+div > div > div > div:last-child > div:nth-child(3) > div')
        location = location?.innerText || undefined
        if (location === 'Share') {
            location = document.querySelector('header+div > div > div > div:last-child > div:nth-child(4) > div')
            location = location?.innerText || undefined
        }

        // 摄影师
        const photographer = document.querySelector('body > div > div > div > div > div > div:nth-child(2) > div > header > div > span > div > a')?.href?.replace('https://unsplash.com/', '') || '未知摄影师'
        // console.log('摄影师', photographer)

        // 链接
        let link = document.URL.replace('https://unsplash.com/photos/', '')
        // console.log('链接', link)

        // 图片地址(跨域获取)
        try {
            a.removeAttribute('target')
            let imgUrl = a.href
            const res = await fetch(imgUrl)
            const blob = await res.blob()
            imgUrl = window.URL.createObjectURL(blob)
            console.log('图片实际地址', imgUrl)
            a.href = imgUrl
        } catch(error) {
            console.error('[跨域获取图片 Blob 地址失败] ', error)
        }

        // 修改文件名
        a.download = `${date}${location ? '【' + location + '】' : ''} ${photographer} [${link}].jpg`
        console.log('✅ 可以下载:', a.download)
    }

    window.onload = () => {
        changeName()
    }
})();