首页 > 解决方案 > 如何在 Greasemonkey 中重定向到我的 youtube 订阅页面?

问题描述

我不想在开始屏幕上看到令人分心的 youtube 推荐,我只想在进入/youtube 路径时被重定向到我的订阅页面。我尝试通过使用 javascript 自动从/路径重定向到路径来重新设计我的 DOM 中的 youtube 页面/feed/subscriptions

我创建了以下脚本,不幸的是它只适用于页面重新加载。

// ==UserScript==
// @name        YT redir /home -> /sub
// @match       https://www.youtube.com/*
// @grant       none
// @run-at      document-start
// @version     1.0
// @author      -
// @description 5/30/2020, 12:16:13 PM
// ==/UserScript==

var current_location = location.pathname;
if(current_location == "/"){
     window.location.replace("https://youtube.com/feed/subscriptions")
}

当我浏览 youtube 并单击主页或 youtube 徽标按钮时,我希望此脚本也能正常工作。但是它仅适用于页面重新加载。

我怎样才能使这个脚本工作而不必重新加载 youtube?

为了解决这个问题以实现相同的目标,我尝试只替换主页按钮和徽标按钮的 href 属性。

// ==UserScript==
// @name        YT test
// @match       https://www.youtube.com/*
// @grant       none
// @run-at      document-start
// @version     1.0
// @author      -
// @description 5/30/2020, 12:16:13 PM
// ==/UserScript==

document.getElementById("endpoint").href="/feed/subscriptions";
document.getElementById("endpoint").removeAttribute('class');
document.getElementById("logo").href="/feed/subscriptions";
document.getElementById("logo").removeAttribute('class');

但是,虽然这些命令在 JS 控制台中有效,但即使我将run-at属性设置为document-end.

如何通过 Greasemonkey 自动进行这些更改?

标签: javascriptgreasemonkeytampermonkey

解决方案


问题:

  1. YouTube 页面在一个文档中有多个相同的元素id,这违反了 HTML 标准,因此document.getElementById("logo")会找到错误的。你可以document.querySelector('a#logo')改用。

  2. 该页面是使用 JavaScript 动态构建的,因此元素可能会在 DOMContentLoaded 事件发生后很长时间才会出现。您可以使用 MutationObserver(可能会消耗资源)或 setTimeout/setInterval(不精确)。

  3. YouTube 网站是一个 SPA(单页应用程序),它使用History API 模拟导航,但用户脚本仅在真实导航时执行。


解决方案:

可以说可能有很多解决方案,但我建议click在捕获阶段使用一个简单的侦听器( addEventListener 的第三个参数是true),这样您就不必依赖元素的确切选择器,这可能会在站点发生不可预测的变化未来的代码更新。

// ==UserScript==
// @name        YT redir /home -> /sub
// @match       https://www.youtube.com/*
// @grant       none
// @run-at      document-start
// ==/UserScript==

if (location.pathname === '/') {
  location.pathname = '/feed/subscriptions';
}
window.addEventListener('click', e => {
  const a = e.target.closest('a');
  if (a && a.href === 'https://www.youtube.com/') {
    a.pathname = '/feed/subscriptions';
    a.className = '';
  }
}, true);

推荐阅读