YouTube Chapter Title to Page Title

Displays the current chapter title of a YouTube video in the page title, scrolling if necessary.

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         YouTube Chapter Title to Page Title
// @namespace    https://greasyfork.org/en/users/1413127-tumoxep
// @version      1.0
// @description  Displays the current chapter title of a YouTube video in the page title, scrolling if necessary.
// @match        https://www.youtube.com/watch*
// @license      WTFPL
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    let scrollIndex = 0;
    let currentChapterTitle = '';
    const isScrollingEnabled = true;

    function updateTitle() {
        let chapterElement = document.querySelector('.ytp-chapter-title-content');
        if (!chapterElement?.textContent) {
            chapterElement = document.querySelector("#title yt-formatted-string");
        }
        if (chapterElement) {
            const newTitle = chapterElement.textContent.trim();
            if (newTitle !== currentChapterTitle) {
                currentChapterTitle = newTitle;
                scrollIndex = 0;
            }

            const maxLength = 20; // Adjust based on your preference
            if (currentChapterTitle.length > maxLength && isScrollingEnabled) {
                const displayedTitle = currentChapterTitle.substring(scrollIndex, scrollIndex + maxLength);
                document.title = displayedTitle;

                scrollIndex++;
                if (scrollIndex > currentChapterTitle.length - maxLength) {
                    scrollIndex = 0;
                }
                setTimeout(updateTitle, 600); // this one too
                return;
            } else {
                document.title = currentChapterTitle;
            }
        }
        setTimeout(updateTitle, 2000); // and this one
    }

    updateTitle();
})();