油猴脚本:GitHub 文件夹下载器

分享一个由Gemini制作的GitHub文件夹下载器油猴脚本,再也不需要为了下载一个文件夹而下载整个仓库了。这个脚本经过精心设计,样式完美融入原生页面,让下载过程更加便捷。

脚本源码

// ==UserScript==
// @name                GitHub Folder Downloader
// @name:zh-CN          GitHub 文件夹下载器
// @version             0.7.0.33
// @author              叁月柒
// @match               *://github.com/*
// @grant               none
// @run-at              document-idle
// ==/UserScript==

(function () {
    'use strict';

    const isFolder = () => {
        const path = window.location.pathname.split('/').filter(Boolean);
        return path.length >= 2 && (path.length === 2 || path[2] === 'tree');
    };

    const injectToMenu = () => {
        const portalRoot = document.querySelector('#__primerPortalRoot__');
        if (!portalRoot) return;

        const menu = portalRoot.querySelector('ul[role="menu"]');
        if (!menu || menu.querySelector('.gh-download-integrated')) return;

        const menuText = menu.innerText;
        // 确保是操作菜单
        if (!menuText.includes('Copy path') && !menuText.includes('Delete directory')) return;

        // 1. 分割线
        const dividerHtml = `<li role="none" class="ActionList-sectionDivider gh-download-integrated"></li>`;

        // 2. 标题
        const headerHtml = `<li class="ActionList-sectionHeader gh-download-integrated">
            <span class="ActionList-sectionHeader-label">
                Download folder
            </span>
        </li>`;

        // 3. 子选项
        const createItem = (text, url) => `<li role="none" class="ActionList-item gh-download-integrated">
            <a role="menuitem" class="ActionList-content ActionList-content--visual16" target="_blank" rel="noopener noreferrer" href="${url}">
                <span class="ActionList-item-label">
                    ${text}
                </span>
            </a>
        </li>`;

        const downloadDirUrl = `https://download-directory.github.io?url=${window.location.href}`;
        const downGitUrl = `https://downgit.github.io/#/home?url=${window.location.href}`;

        const fragment = dividerHtml +
                         headerHtml +
                         createItem('by Download-Directory', downloadDirUrl) +
                         createItem('by DownGit', downGitUrl);

        menu.insertAdjacentHTML('beforeend', fragment);
    };

    const observer = new MutationObserver((mutations) => {
        if (!isFolder()) return;
        for (const mutation of mutations) {
            if (mutation.addedNodes.length > 0) {
                injectToMenu();
            }
        }
    });

    observer.observe(document.body, { childList: true, subtree: true });
})();

这个脚本可以在GitHub页面上添加额外的下载选项,使得下载特定文件夹变得非常简单。只需将上述代码复制到油猴脚本管理器中,并安装即可使用。感谢作者叁月柒的辛勤工作,为GitHub用户带来了便利。

标签: none

评论已关闭