Chrome扩展出现‘invalid invocation’错误,脚本无法运行求助
问题解决:Chrome扩展Manifest V3中background.js的TypeError: Invalid Invocation
错误原因
问题核心在于Manifest V3与V2的API使用差异:
- 回调函数不再支持:Manifest V3的service worker环境中,多数Chrome API改用Promise异步模式,不再接受回调参数,这是触发"Invalid Invocation"的直接原因。
- 参数格式错误:
chrome.declarativeContent.onPageChanged.removeRules在V3中,移除所有规则无需传undefined,直接调用或传空数组即可。 - 废弃API误用:
chrome.declarativeContent.ShowPageAction在V3中已被废弃,需替换为chrome.declarativeContent.ShowAction(V3中pageAction与browserAction已合并为action)。
修正后的background.js代码
使用async/await处理Promise:
(async function() { // 移除所有现有规则 await chrome.declarativeContent.onPageChanged.removeRules(); // 添加新规则 await chrome.declarativeContent.onPageChanged.addRules([{ actions: [new chrome.declarativeContent.ShowAction()] }]); })();
也可以用.then()链式调用:
chrome.declarativeContent.onPageChanged.removeRules() .then(() => { chrome.declarativeContent.onPageChanged.addRules([{ actions: [new chrome.declarativeContent.ShowAction()] }]); });
额外说明
你提到修改内容脚本后出现故障,但实际错误来自background脚本的API调用方式,和内容脚本逻辑无关。修正background.js后,扩展的脚本执行应该能恢复正常。
内容的提问来源于stack exchange,提问作者Nathan
相关产品推荐
相关产品推荐

