Youtube Error fix

Forces YouTube links to load with a real page navigation instead of SPA routing.

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.sleazyfork.org/scripts/579644/1834066/Youtube%20Error%20fix.js

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Youtube Error fix
// @version      1.0
// @description  Forces YouTube links to load with a real page navigation instead of SPA routing.
// @match        https://www.youtube.com/*
// @grant        none
// ==/UserScript==

(function () {
  'use strict';

  function isYouTubeLink(url) {
    try {
      const u = new URL(url, location.href);
      return u.hostname.endsWith('youtube.com') || u.hostname.endsWith('youtu.be');
    } catch {
      return false;
    }
  }

  function hardNavigate(url) {
    if (!url) return;
    location.href = url;
  }

  document.addEventListener(
    'click',
    (e) => {
      const a = e.target.closest && e.target.closest('a[href]');
      if (!a) return;

      const url = a.href;
      if (!isYouTubeLink(url)) return;

      // Let modified clicks behave normally
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;

      e.preventDefault();
      e.stopPropagation();
      hardNavigate(url);
    },
    true
  );

  // Also catch YouTube's SPA-style navigation attempts
  window.addEventListener('yt-navigate-start', (e) => {
    const url = e && e.detail && e.detail.url;
    if (url && isYouTubeLink(url)) {
      hardNavigate(url);
    }
  });
})();