如何通过Tampermonkey或其他方式,自动为YouTube搜索URL追加指定参数以移除「您可能还关注的视频」板块?
如何通过Tampermonkey或其他方式,自动为YouTube搜索URL追加指定参数以移除「您可能还关注的视频」板块?
我完全懂你的困扰——之前的脚本在直接打开YouTube搜索结果页面时能正常工作,但用站内搜索框搜索内容就失效了,对吧?这是因为现在的YouTube是单页应用(SPA),站内搜索不会触发整页刷新,只是通过前端路由更新URL,原来依赖页面加载事件的脚本自然抓不到这种变化。
下面给你调整后的Tampermonkey脚本,能覆盖初始页面加载、站内搜索提交、前端路由导航(比如前进后退)、动态渲染的搜索表单这所有场景:
// ==UserScript== // @name Youtube - 移除搜索结果中的「您可能还关注的视频」板块 // @namespace http://tampermonkey.net/ // @version 1.2 // @description 自动为YouTube搜索URL追加&sp=CAASAhAB参数,移除「您可能还关注的视频」板块 // @author MattFor | @mattfor // @match *://www.youtube.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 目标参数 const TARGET_PARAM = '&sp=CAASAhAB'; // 检查URL是否已包含目标参数,没有则追加并跳转 function addSearchParam() { const currentUrl = window.location.href; // 只在搜索结果页面生效,避免影响其他页面 if (currentUrl.includes('/results?search_query=') && !currentUrl.includes(TARGET_PARAM)) { // 处理URL已有其他参数的情况,避免重复加& const newUrl = currentUrl + TARGET_PARAM; // 用replaceState避免重复添加历史记录 window.history.replaceState({}, '', newUrl); // 强制页面重新加载(确保YouTube识别新参数) window.location.reload(); } } // 监听搜索表单提交,手动追加参数 function setupSearchFormListener() { const searchForm = document.getElementById('search-form'); if (searchForm) { searchForm.addEventListener('submit', function(e) { e.preventDefault(); // 获取搜索框的值 const searchInput = document.getElementById('search-input'); const query = searchInput.value.trim(); if (query) { // 拼接带参数的搜索URL const searchUrl = `/results?search_query=${encodeURIComponent(query)}${TARGET_PARAM}`; // 跳转页面 window.location.href = searchUrl; } }); } } // 监听页面URL的前端路由变化(YouTube用history API更新URL) function watchForUrlChanges() { let lastUrl = window.location.href; // 用MutationObserver观察页面的URL变化(因为SPA不会触发hashchange或popstate) const observer = new MutationObserver(() => { const currentUrl = window.location.href; if (currentUrl !== lastUrl) { lastUrl = currentUrl; addSearchParam(); } }); // 观察document的URL相关变化 observer.observe(document, { subtree: true, childList: true }); } // 初始化所有监听和检查 function init() { addSearchParam(); setupSearchFormListener(); watchForUrlChanges(); // 监听页面动态渲染(比如搜索框被重新加载的情况) const observer = new MutationObserver(() => { setupSearchFormListener(); }); observer.observe(document.body, { subtree: true, childList: true }); } // 页面加载完成后初始化 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init); } else { init(); } })();
关键改进点说明:
- 扩大匹配范围:把
@match改成*://www.youtube.com/*,确保脚本在YouTube所有页面都能运行,不会漏掉动态渲染的搜索表单 - 处理前端路由变化:用
MutationObserver监听页面内容变化,捕获YouTube通过history API更新URL的行为,及时触发参数追加 - 优化搜索表单处理:不再修改表单的action,而是直接拼接带参数的URL并跳转,避免YouTube的前端逻辑干扰
- 动态监听表单:额外加一个
MutationObserver,确保页面部分刷新后,新渲染的搜索表单依然能被监听 - 避免重复历史记录:用
history.replaceState更新URL,再强制刷新,既保证参数生效,又不会在历史记录里留下多余条目
这样修改后,不管是直接打开搜索链接,还是用站内搜索框搜索,甚至是浏览器前进后退到搜索页面,脚本都能自动为URL追加参数,成功移除「您可能还关注的视频」板块。
备注:内容来源于stack exchange,提问作者MattFor
相关产品推荐
相关产品推荐

