// ==UserScript== // @name YouTube新标签页打开 // @namespace your_namespace // @version 1.1.0 // @description:zh-cn YouTube视频新标签页打开点击油猴图标可以切换首页非首页模式 // @author YourName // @match *://*.youtube.com/* // @license 无 // @grant GM_registerMenuCommand // @grant GM_getValue // @grant GM_setValue // @grant GM_unregisterMenuCommand // @description Open YouTube videos in new tab with intelligent filtering // @downloadURL none // ==/UserScript== (function() { 'use strict'; // 配置存储 const CONFIG = { globalMode: GM_getValue('globalMode', false) // 默认关闭全局模式 }; // 清理旧菜单项 let currentMenuIds = []; function clearMenu() { currentMenuIds.forEach(id => GM_unregisterMenuCommand(id)); currentMenuIds = []; } // 更新菜单显示 function updateMenu() { clearMenu(); // 添加带状态指示的菜单项 currentMenuIds.push( GM_registerMenuCommand( `${CONFIG.globalMode ? "✅" : " "} 全局模式(所有页面生效)`, () => setMode(true) ) ); currentMenuIds.push( GM_registerMenuCommand( `${!CONFIG.globalMode ? "✅" : " "} 首页模式(仅主页生效)`, () => setMode(false) ) ); } // 模式切换处理 function setMode(global) { CONFIG.globalMode = global; GM_setValue('globalMode', global); location.reload(); // 新增页面刷新 } // 判断是否在首页 function isHomePage() { return window.location.pathname === "/"; } // 主逻辑(根据模式处理点击) function initHandler() { document.addEventListener('click', function handleClick(event) { // 仅在全局模式 或 首页模式+在首页 时生效 if (!CONFIG.globalMode && !isHomePage()) return; let target = event.target; while (target && target.tagName !== 'A') { target = target.parentElement; } if (target && target.href && isVideoLink(target)) { event.preventDefault(); event.stopPropagation(); const isShortLink = target.href.includes('/shorts/'); window.open(target.href, '_blank'); // 修复逻辑:仅当当前在短视频页面时才跳转空白页 if (isShortLink && isShortPage()) { window.location.replace("about:blank"); } } }, true); } // 新增辅助函数 function isShortPage() { return window.location.pathname.startsWith('/shorts/'); } function isVideoLink(aTag) { return /(\/watch\?v=|\/shorts\/)/.test(aTag.href) && !aTag.closest('ytd-channel-name, ytd-playlist-panel-video-renderer'); } // 初始化 updateMenu(); initHandler(); })();