You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

YouTube站内跳转视频时Tampermonkey日期替换脚本失效求助

YouTube视频上传日期显示修复脚本优化

问题背景

我编写了一个Tampermonkey脚本,用于将YouTube视频描述中的“X天/月/年前”字段替换为实际上传日期,还原旧版显示样式。该脚本在直接通过https://www.youtube.com/watch?v=打开视频URL时运行正常,但在YouTube网站内点击视频链接(如搜索结果、首页推荐)时无法执行。

原脚本代码:

// ==UserScript==
// @name         YouTube Date Changer
// @namespace    http://tampermonkey.net/
// @version      2024-01-13
// @description  Replaces the "___ days/months/years ago" with the actual upload date in the video description
// @match        https://www.youtube.com/watch?*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';
    function run () {
        var longdate = document.querySelector("div#info-strings yt-formatted-string");
        if (longdate) {
            var str = longdate.innerHTML;
            var shortdate = document.getElementsByClassName("style-scope yt-formatted-string bold")[2];
            shortdate.innerHTML = str;
        } else {
            setTimeout(run,250);
        }
    }
    run();
})();

问题原因

YouTube站内跳转视频时采用单页应用内部加载机制,不会发起新的URL请求(跳转时顶部会显示进度条),而Tampermonkey的@match规则仅在页面初始加载时触发,因此站内跳转后脚本不会重新执行。

临时解决方案是通过新窗口打开链接,但并非根本办法。我更倾向于不依赖URL变化,改用检测视频加载完成的方式触发脚本,寻求技术实现方案。

优化方案(适配站内跳转)

针对YouTube的单页应用特性,以下两种方案可确保脚本在站内跳转后正常执行:

方案1:定时检测URL变化

YouTube站内跳转时会修改浏览器地址栏URL,通过定时检查URL变化来触发脚本:

// ==UserScript==
// @name         YouTube Date Changer (Fixed)
// @namespace    http://tampermonkey.net/
// @version      2024-01-13
// @description  Replaces the "___ days/months/years ago" with the actual upload date (works for in-site navigation)
// @match        https://www.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    function replaceUploadDate() {
        const longdate = document.querySelector("div#info-strings yt-formatted-string");
        if (longdate) {
            const str = longdate.textContent;
            // 用精准选择器替代索引取值,避免页面结构变化失效
            const shortdate = document.querySelector("yt-formatted-string#info-text span.bold");
            if (shortdate) {
                shortdate.textContent = str;
            }
        } else {
            setTimeout(replaceUploadDate, 250);
        }
    }

    // 初始加载执行
    replaceUploadDate();

    // 定时检查URL变化,站内跳转后重新执行
    let lastUrl = window.location.href;
    setInterval(() => {
        const currentUrl = window.location.href;
        if (currentUrl !== lastUrl && currentUrl.includes("/watch?v=")) {
            lastUrl = currentUrl;
            replaceUploadDate();
        }
    }, 100);
})();

方案2:使用MutationObserver监听DOM变化

直接监听视频主内容区域的DOM变化,当新视频信息加载完成时触发替换逻辑:

// ==UserScript==
// @name         YouTube Date Changer (Fixed)
// @namespace    http://tampermonkey.net/
// @version      2024-01-13
// @description  Replaces the "___ days/months/years ago" with the actual upload date (works for in-site navigation)
// @match        https://www.youtube.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @grant        none
// @run-at       document-end
// ==/UserScript==

(function() {
    'use strict';

    function replaceUploadDate() {
        const longdate = document.querySelector("div#info-strings yt-formatted-string");
        if (longdate) {
            const str = longdate.textContent;
            const shortdate = document.querySelector("yt-formatted-string#info-text span.bold");
            if (shortdate) {
                shortdate.textContent = str;
            }
        }
    }

    // 初始执行
    replaceUploadDate();

    // 监听视频主内容区域的DOM变化
    const targetNode = document.getElementById("primary");
    if (targetNode) {
        const observerOptions = {
            childList: true,
            subtree: true
        };

        const observer = new MutationObserver(() => replaceUploadDate());
        observer.observe(targetNode, observerOptions);
    }
})();

关键优化说明

  • 调整@match规则为https://www.youtube.com/*,确保脚本在全站加载
  • 替换原脚本中通过索引获取元素的方式,改用稳定的CSS选择器,避免页面结构变化导致脚本失效
  • 使用textContent替代innerHTML,提升安全性,避免潜在注入风险
  • 新增页面变化监听机制,确保站内跳转视频后脚本自动重新执行

内容的提问来源于stack exchange,提问作者higrafey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 13:38:12