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

Chrome扩展开发:提取YouTube视频标题失败求解决

解决Chrome扩展提取YouTube视频标题失效的问题

常见问题及修复方案

1. DOM选择器过时

YouTube页面结构会频繁更新,你当前使用的.title.ytd-video-primary-info-renderer选择器大概率已经失效。目前可用的视频标题选择器可以尝试:

  • ytd-watch-metadata #title h1
  • .yt-core-attributed-string.yt-core-attributed-string--white-space-no-wrap

2. 内容脚本执行时机错误

如果脚本在DOM未完全加载时运行,会直接找不到标题元素。可以通过两种方式修正:

  • 在manifest.json中指定脚本执行时机:
    "content_scripts": [
      {
        "matches": ["*://*.youtube.com/watch*"],
        "js": ["content.js"],
        "run_at": "document_idle"
      }
    ]
    
  • 在脚本内监听DOM加载完成事件:
    function extractSongInfo() {
        // 更新标题选择器
        const titleElement = document.querySelector('ytd-watch-metadata #title h1');
        const videoTitle = titleElement ? titleElement.innerText.trim() : '';
    
        // 注意:你原代码中用字幕按钮提取艺术家的逻辑完全错误,字幕按钮的aria-label和艺术家无关
        // 若要获取相关创作者信息,可尝试提取频道名:
        const channelNameElement = document.querySelector('#channel-name yt-formatted-string');
        const artist = channelNameElement ? channelNameElement.innerText : '';
    
        chrome.runtime.sendMessage({ type: 'SONG_INFO', title: videoTitle, artist });
    }
    
    // 确保DOM加载完成后执行提取逻辑
    if (document.readyState === 'complete') {
        extractSongInfo();
    } else {
        window.addEventListener('load', extractSongInfo);
    }
    

3. 适配YouTube单页应用特性

YouTube是单页应用,切换视频时页面不会刷新,需要监听页面变化来重新提取标题:

// 监听URL变化,切换视频时重新提取
let currentUrl = window.location.href;
setInterval(() => {
    if (window.location.href !== currentUrl) {
        currentUrl = window.location.href;
        // 延迟1秒确保DOM更新完成
        setTimeout(extractSongInfo, 1000);
    }
}, 500);

// 或者用MutationObserver监听标题容器的变化
const observer = new MutationObserver(() => extractSongInfo());
const titleContainer = document.querySelector('ytd-watch-metadata');
if (titleContainer) {
    observer.observe(titleContainer, { childList: true, subtree: true });
}

4. 检查扩展权限配置

确保manifest.json中正确配置了匹配规则:

{
  "manifest_version": 3,
  "name": "YouTube Title Extractor",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["*://*.youtube.com/watch*"],
      "js": ["content.js"]
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:12:52