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

Chrome扩展JSON脚本仅首次进入URL时生效问题求助

问题

我正在开发一款Chrome扩展,用CSS屏蔽YouTube页面的特定元素。现在遇到的问题是:内容脚本仅在首次进入对应URL时加载CSS文件,后续页面跳转或重定向后,必须强制刷新才能让脚本再次生效。比如:进入www.youtube.com时,homepage.css能正常生效;但从搜索页跳转进入频道页(需要加载channel.css)时,页面没有变化,channel.css未生效。

我用Chrome的「加载已解压的扩展程序」加载该扩展,以下是我的manifest.json配置及文件目录结构(所有CSS文件功能本身正常):

manifest.json 配置

{
  "manifest_version": 3,
  "name": "Locked In for YouTube - Productivity & Focus",
  "version": "1.0",
  "description": "Stay 'locked in' by removing distracting elements that keep you away from your work such as recommended, Shorts, trending tab, etc.",
  "permissions": ["activeTab"],
  "content_scripts": [
    {
      "matches": ["*://www.youtube.com/*"],
      "css": ["homepage.css"]
    },
    {
      "matches": ["*://www.youtube.com/feed*"],
      "css": ["feed.css"]
    },
    {
      "matches": ["*://www.youtube.com/results*"],
      "css": ["results.css"]
    },
    {
      "matches": ["*://www.youtube.com/watch*"],
      "css": ["watch.css"]
    },
    {
      "matches": ["*://www.youtube.com/@*"],
      "css": ["channel.css"]
    }
  ]
}

文件目录结构

core/
|
├──manifest.json
├──channel.css
├──feed.css
├──homepage.css
├──results.css
├──watch.css
解决方案

问题根源是YouTube属于单页应用(SPA),页面跳转时不会重新加载整个页面,仅更新DOM和URL。而Chrome的内容脚本默认只在页面首次加载时匹配URL并注入资源,路由跳转后不会重新检查匹配规则。

下面提供两种解决方法,推荐结合使用:

方法1:调整注入时机与匹配优先级

修改manifest.json里的content_scripts配置,给每个规则加上run_at: "document_start",同时把更具体的URL匹配规则放在前面(确保高优先级的CSS先注入,避免被通用规则覆盖):

{
  "manifest_version": 3,
  "name": "Locked In for YouTube - Productivity & Focus",
  "version": "1.0",
  "description": "Stay 'locked in' by removing distracting elements that keep you away from your work such as recommended, Shorts, trending tab, etc.",
  "permissions": ["activeTab"],
  "content_scripts": [
    {
      "matches": ["*://www.youtube.com/@*"],
      "css": ["channel.css"],
      "run_at": "document_start"
    },
    {
      "matches": ["*://www.youtube.com/watch*"],
      "css": ["watch.css"],
      "run_at": "document_start"
    },
    {
      "matches": ["*://www.youtube.com/results*"],
      "css": ["results.css"],
      "run_at": "document_start"
    },
    {
      "matches": ["*://www.youtube.com/feed*"],
      "css": ["feed.css"],
      "run_at": "document_start"
    },
    {
      "matches": ["*://www.youtube.com/*"],
      "css": ["homepage.css"],
      "run_at": "document_start"
    }
  ]
}

这种调整能让Chrome在文档开始加载时就注入对应CSS,适配SPA的初始加载逻辑。

方法2:监听URL变化,动态注入CSS

如果方法1不够稳定,可通过监听URL变化事件,手动控制CSS的注入与移除:

  1. 在core目录下新建content.js文件,内容如下:
// 处理URL变化逻辑
function handleUrlChange() {
  const currentUrl = window.location.href;
  
  // 移除所有扩展注入的CSS,避免重复加载
  document.querySelectorAll('[data-yt-lockin-css]').forEach(el => el.remove());
  
  // 根据当前URL匹配对应CSS文件
  let cssFile = '';
  if (currentUrl.includes('/@')) {
    cssFile = 'channel.css';
  } else if (currentUrl.includes('/watch')) {
    cssFile = 'watch.css';
  } else if (currentUrl.includes('/results')) {
    cssFile = 'results.css';
  } else if (currentUrl.includes('/feed')) {
    cssFile = 'feed.css';
  } else {
    cssFile = 'homepage.css';
  }
  
  // 注入目标CSS文件
  if (cssFile) {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = chrome.runtime.getURL(cssFile);
    link.dataset.ytLockinCss = 'true'; // 标记扩展注入的CSS,方便后续移除
    document.head.appendChild(link);
  }
}

// 页面初始化时执行一次
handleUrlChange();

// 监听SPA路由跳转(YouTube用history.pushState实现)
const originalPushState = history.pushState;
history.pushState = function(...args) {
  originalPushState.apply(this, args);
  handleUrlChange();
};

// 监听浏览器前进后退事件
window.addEventListener('popstate', handleUrlChange);
  1. 修改manifest.json,添加这个脚本并声明可访问的资源:
{
  "manifest_version": 3,
  "name": "Locked In for YouTube - Productivity & Focus",
  "version": "1.0",
  "description": "Stay 'locked in' by removing distracting elements that keep you away from your work such as recommended, Shorts, trending tab, etc.",
  "permissions": ["activeTab"],
  "content_scripts": [
    {
      "matches": ["*://www.youtube.com/*"],
      "js": ["content.js"],
      "run_at": "document_start"
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["channel.css", "feed.css", "homepage.css", "results.css", "watch.css"],
      "matches": ["*://www.youtube.com/*"]
    }
  ]
}

这种方法通过主动监听URL变化,动态注入对应CSS,完全适配SPA的跳转逻辑,确保每次路由切换都能加载正确样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 11:16:02