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

Chrome扩展Service Worker注册失败及未定义属性读取问题求助

问题分析与解决

核心错误点

  • 拼写错误触发未定义属性报错:代码中写了chrome.tebs.onUpdated,正确的API是chrome.tabs.onUpdated,tebs是笔误,这直接导致"无法读取未定义属性"的错误。
  • Service Worker注册失败的常见诱因:
    • 检查manifest.json版本:如果用Manifest V3,background配置必须是"service_worker": "background.js",而非V2的"background": {"scripts": ["background.js"]}。
    • 确认background.js路径:文件需和manifest.json在同一目录,或路径配置准确。
    • 环境要求:Chrome版本需在88及以上(Manifest V3最低要求),且已开启扩展管理页面的"开发者模式",正确加载解压后的扩展文件。

代码修正建议

除修正拼写错误,还需优化消息发送时机,避免页面未加载完成就发送消息导致失败,同时处理productId可能为空的情况:

const websites = [
    'desktop.bg/',
    'ozone.bg/product/'
];

// 修正拼写错误:tebs → tabs
chrome.tabs.onUpdated.addListener((tabId, tab) => {
    // 仅在页面完全加载完成后处理
    if (tab.url && tab.status === 'complete') {
        for (const site of websites) {
            if (tab.url.includes(site)) {
                const parts = tab.url.split(site);
                // 确保split后存在有效内容
                if (parts.length > 1 && parts[1]) {
                    const productId = parts[1];
                    // 捕获消息发送失败的异常,避免因content script未注入报错
                    chrome.tabs.sendMessage(tabId, { productId }).catch(err => {
                        console.log("消息发送失败:", err);
                    });
                }
            }
        }
    }
});

额外注意事项

  • 确保manifest.json中声明tabs权限:在"permissions"数组里添加"tabs"。
  • 正确配置content script注入规则:在manifest.json的"content_scripts"字段中匹配目标网站,示例:
    "content_scripts": [
        {
            "matches": ["*://*.desktop.bg/*", "*://*.ozone.bg/product/*"],
            "js": ["content.js"]
        }
    ]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:01:58