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

Chrome扩展未在document_start时机执行问题求助

问题:Chrome扩展未按配置在document_start时机执行内容脚本

我开发的Chrome扩展在manifest.json中配置了内容脚本run-at: document_start,但页面自身脚本的日志却先于我的内容脚本日志输出。

Manifest.json配置

{
    "manifest_version": 3,
    "name": "Lift Web Restrictions",
    "description": "Simple extension that removes most ads, web restrictions, adds mods to MooMoo.io / Krunker.io / and more!",
    "version": "0.0.5",
    "icons": {
        "16": "logo/sw16.png",
        "48": "logo/sw48.png",
        "128": "logo/sw128.png"
    },
    "permissions": [],
    "host_permissions": [
        "*://*/*"
    ],
    "background": {
        "service_worker": "service-worker.js"
    },
    "web_accessible_resources": [
        {
          "resources": ["modules/script.js"],
          "matches": ["*://*/*"]
        }
    ],     
    "content_scripts": [{
        "js": [
            "modules/transfer.js"
        ],
        "matches": ["http://*/*", "https://*/*"],
        "all_frames": true,
        "run-at": "document_start"
    }]
}

日志输出顺序

Launching egAps
index.bf049c93.js?52f6f7bb66295262766e:2 Downloading d.js...

index.bf049c93.js?52f6f7bb66295262766e:2 Loading WASM c66eb3cbd8fdc1325900.wasm
^^^^ 这些日志在我的脚本运行前输出

index.bf049c93.js?52f6f7bb66295262766e:2 1 dependencies left
transfer.js:1 fireAt <--- 我的脚本在这里运行
index.bf049c93.js?52f6f7bb66295262766e:2 0 dependencies left
index.bf049c93.js?52f6f7bb66295262766e:2 Running...
index.bf049c93.js?52f6f7bb66295262766e:2 

解决方案

  • 强制刷新扩展排除缓存:开启扩展管理页的开发者模式,点击"更新"按钮,强制Chrome重新加载扩展,避免延迟加载的情况。
  • 确保内容脚本是纯同步代码:检查transfer.js内部是否有异步逻辑(比如fetch、setTimeout、监听DOMContentLoaded等),这些会延后执行时机。把所有需要在document_start执行的代码写成同步逻辑。
  • 尝试指定MAIN世界(Manifest V3):在content_scripts配置中添加"world": "MAIN",让内容脚本运行在页面的主世界(注意这会和页面全局环境共享,可能引发变量冲突):
    "content_scripts": [{
        "js": ["modules/transfer.js"],
        "matches": ["http://*/*", "https://*/*"],
        "all_frames": true,
        "run-at": "document_start",
        "world": "MAIN"
    }]
    
  • 验证执行时机的时间戳:在transfer.js第一行添加同步代码记录时间,对比页面脚本的执行时间,确认是否真的是扩展延迟:
    // transfer.js 第一行
    console.log('扩展脚本执行时间:', performance.now());
    document.documentElement.setAttribute('data-extension-loaded', 'true');
    
    同时在页面源码最顶部加内联脚本对比:
    <script>console.log('页面脚本执行时间:', performance.now());</script>
    
  • 检查匹配规则:确认matches和host_permissions的规则覆盖了目标页面,避免因匹配失败导致脚本未及时注入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:40:39