YouTube 右下角放一顆複製短網址

The most robust script for cleaning YouTube URLs and copying short links.

当前为 2025-09-18 提交的版本,查看 最新版本

// ==UserScript==
// @name         YouTube 右下角放一顆複製短網址
// @namespace    http://tampermonkey.net/
// @version      1.1
// @description  The most robust script for cleaning YouTube URLs and copying short links.
// @author       You
// @match        https://www.youtube.com/watch*
// @run-at       document-start
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    function getCleanUrlAndVideoId() {
        const url = new URL(window.location.href);
        let videoId = '';

        if (url.pathname.startsWith('/shorts/')) {
            videoId = url.pathname.split('/')[2];
        } else {
            videoId = url.searchParams.get('v');
        }

        if (videoId) {
            const cleanUrl = `https://www.youtube.com/watch?v=${videoId}`;
            const shortUrl = `https://youtu.be/${videoId}`;
            return { cleanUrl, shortUrl, videoId };
        }

        return null;
    }

    function cleanUrlInAddressBar() {
        const urls = getCleanUrlAndVideoId();
        if (urls && window.location.href !== urls.cleanUrl) {
            window.history.replaceState({}, '', urls.cleanUrl);
        }
    }
    setInterval(cleanUrlInAddressBar, 50);

    function addCopyButton() {
        const urls = getCleanUrlAndVideoId();
        if (!urls || document.getElementById('yt-copy-short-url-btn')) {
            return;
        }

        const button = document.createElement('button');
        button.id = 'yt-copy-short-url-btn';
        button.textContent = '複製短網址';
        button.style.cssText = `
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 9999;
            background-color: #ff0000;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        `;

        // 核心修正:嘗試將按鈕加入一個更穩定的父元素
        document.body.appendChild(button);

        button.onclick = async () => {
            const currentUrls = getCleanUrlAndVideoId();
            if (!currentUrls) return;

            try {
                await navigator.clipboard.writeText(currentUrls.shortUrl);
                button.textContent = '已複製!';
                setTimeout(() => button.textContent = '複製短網址', 2000);
            } catch (err) {
                console.error('無法複製到剪貼簿:', err);
                alert('無法複製短網址,請手動複製: ' + currentUrls.shortUrl);
            }
        };
    }

    // 每隔 500 毫秒檢查一次按鈕是否存在
    setInterval(addCopyButton, 500);

})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址