javascript - 如何在 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 自动进行这些更改?
解决方案
问题:
YouTube 页面在一个文档中有多个相同的元素
id
,这违反了 HTML 标准,因此document.getElementById("logo")
会找到错误的。你可以document.querySelector('a#logo')
改用。该页面是使用 JavaScript 动态构建的,因此元素可能会在 DOMContentLoaded 事件发生后很长时间才会出现。您可以使用 MutationObserver(可能会消耗资源)或 setTimeout/setInterval(不精确)。
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);
推荐阅读
- flutter - Flutter/Dart + gRPC 流错误:流被对等端终止(错误代码:2)
- asp.net-core - System.NullReferenceException ViewData .net 核心 5
- c - 头文件中结构的未知类型名称
- windows - PyMesh 在 Windows10 上的设置问题和使用 Docker 版本时出错
- javascript - 在 WooCommerce 上监控 JQuery 发出的所有 AJAX 请求
- assembly - 如果 N < width(DST),x86_64 有效地设置寄存器 DST 中的位 N,否则 DST = 0
- javascript - 有没有办法在它所在的组件上更改状态后更改音频播放器的 url?
- python - 将相位角方程从 Matlab 转换为 Python
- node.js - 无法使用 xlsx 在 CSV 文件中写入数据
- python - Django:将变量/参数传递给视图?