修改YouTube首页布局

修改YouTube首页每行推荐视频数量

目前为 2025-04-17 提交的版本。查看 最新版本

// ==UserScript==
// @name            修改YouTube首页布局
// @name:en         Modify YouTube Homepage Layout
// @description     修改YouTube首页每行推荐视频数量
// @description:en  Change the number of recommended videos per row on the YouTube homepage
// @version         1.1
// @author          爆菊大师
// @match           https://www.youtube.com/
// @icon            https://www.youtube.com/favicon.ico
// @grant           GM_registerMenuCommand
// @license         MIT
// @namespace https://greasyfork.org/users/929164
// ==/UserScript==

(() => {
    'use strict';
    const CONFIG = {
        columns: 'ytd-items-per-row',
        shorts: 'ytd-shorts-blocked'
    };
    const state = {
        columns: Math.min(10, Math.max(1,
            parseInt(localStorage.getItem(CONFIG.columns)) || 5)),
        shorts: localStorage.getItem(CONFIG.shorts) === 'true'
    };
    const [layoutStyle, shortsStyle] = ['columns', 'shorts'].map(() =>
        document.head.appendChild(document.createElement('style'))
    );
    const updateStyle = () => {
        layoutStyle.textContent = `
            .style-scope.ytd-two-column-browse-results-renderer {
                --ytd-rich-grid-items-per-row: ${state.columns} !important;
            }
        `;
        shortsStyle.textContent = state.shorts ? `
            ytd-rich-section-renderer,
            ytd-reel-shelf-renderer {
                display: none !important;
            }
        ` : '';
    };
    GM_registerMenuCommand('📺 设置每行显示数量', () => {
        const input = prompt('请输入每行显示的视频数量(1-10):', state.columns);
        const value = Math.min(10, Math.max(1, parseInt(input) || state.columns));
        localStorage.setItem(CONFIG.columns, value);
        state.columns = value;
        updateStyle();
        alert(`当前设置:每行显示 ${value} 个视频`);
    });
    GM_registerMenuCommand(state.shorts ? '显示Shorts' : '隐藏Shorts', () => {
        state.shorts = !state.shorts;
        localStorage.setItem(CONFIG.shorts, state.shorts);
        updateStyle();
        window.location.reload();
    });
    updateStyle();
})();