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

Cleans YouTube URL and adds a floating button to copy the short URL, with dynamic updates.

目前為 2025-09-18 提交的版本,檢視 最新版本

// ==UserScript==
// @name         YouTube 右下角放一顆複製短網址
// @namespace    http://tampermonkey.net/
// @version      0.9
// @description  Cleans YouTube URL and adds a floating button to copy the short URL, with dynamic updates.
// @author       You
// @match        https://www.youtube.com/watch*
// @run-at       document-start
// @grant        none
// @license MIT
// ==/UserScript==

(function() {
    'use strict';

    // 處理網址列:每隔 50 毫秒清理一次長網址參數
    function cleanUrl() {
        const url = new URL(window.location.href);
        const videoId = url.searchParams.get('v');

        if (videoId) {
            const cleanUrl = `${url.origin}${url.pathname}?v=${videoId}`;
            if (window.location.href !== cleanUrl) {
                window.history.replaceState({}, '', cleanUrl);
            }
        }
    }
    setInterval(cleanUrl, 50);

    // 建立複製按鈕並將其加入頁面
    function addCopyButton() {
        if (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 () => {
            // 在每次點擊時,重新取得當前的影片 ID
            const videoId = new URL(window.location.href).searchParams.get('v');
            if (!videoId) return;

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

    // 使用 MutationObserver 監聽頁面 DOM 變化,確保按鈕在頁面切換時也能正確顯示
    const observer = new MutationObserver(addCopyButton);
    observer.observe(document.body, { childList: true, subtree: true });

    // 首次載入時也執行一次
    window.addEventListener('load', addCopyButton);

})();

QingJ © 2025

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