YouTube community image forced original image

Make Youtube community post images fully displayed without cropping

// ==UserScript==
// @name   YouTube 社区图片强制原图
// @name:en YouTube community image forced original image
// @description 使Youtube社区帖子图片无裁剪完全显示
// @description:en Make Youtube community post images fully displayed without cropping
// @version        1.1.0
// @author         kaesinol
// @match          https://*.youtube.com/*/posts
// @match          https://*.youtube.com/post/*
// @match          https://*.youtube.com/@*
// @match          https://*.youtube.com/channel/*/posts
// @grant          GM_download
// @license        MIT
// @namespace https://greasyforks.org/users/1243515
// @grant        none
// ==/UserScript==

(function() {
  'use strict';

  console.log('[YouTubeImgFix] 脚本启动');

  // 匹配需要“还原原图”的 URL 片段
  const MATCH_RE = /-c-fcrop64=|=s\d+/;

  function fixImg(img) {
    const src = img.getAttribute('src');
    if (!src || !MATCH_RE.test(src)) return;      // 只有真正匹配到才处理
    if (img.dataset.processed) return;          // 已处理过的跳过

    console.info('[YouTubeImgFix] 原图替换前 src:', src);
    let newSrc = src
      .replace(/-c-fcrop64=[^=]*/g, '')          // 去掉裁剪参数
      .replace(/=s\d+/g, '=s0');                // 强制最大尺寸
    console.info('[YouTubeImgFix] 原图替换后 src:', newSrc);

    img.setAttribute('src', newSrc);
    img.setAttribute('loading', 'lazy');         // 添加 lazyload 属性
    img.dataset.processed = '1';
  }

  // 1. 初次对已有图片做一次尝试(不会标记未匹配的)
  for (const img of document.images) {
    fixImg(img);
  }

  // 2. 监听新插入的节点
  const observer = new MutationObserver(records => {
    for (const rec of records) {
      // 新节点加入
      for (const node of rec.addedNodes) {
        if (node.nodeType !== 1) continue;
        if (node.tagName === 'IMG') {
          fixImg(node);
        } else if (node.querySelectorAll) {
          for (const img of node.querySelectorAll('img')) {
            fixImg(img);
          }
        }
      }
      // 属性变更
      if (rec.type === 'attributes' && rec.target.tagName === 'IMG') {
        fixImg(rec.target);
      }
    }
  });

  observer.observe(document.documentElement, {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['src']
  });

  console.log('[YouTubeImgFix] Observer 已启动,监听插入 & src 变更');
})();
长期地址
遇到问题?请前往 GitHub 提 Issues。