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

MV3中onMessage处理器无需return true仍可异步回调,原因何在?

Chrome扩展MV3中onMessage异步回调无需return true的原因

Chrome扩展MV3官方文档指出,异步调用onMessage事件监听器的回调函数时,需要从监听器中返回return true,但实际测试发现,不添加该语句的代码在MV3中依然能正常运行:

/*contentScript.js*/
chrome.runtime.sendMessage({msg:'getglobals'}, function(response) {
  console.log('The globals are ' + response);//response printed which shouldn't be
})


/*background.js(service worker)*/
chrome.runtime.onMessage.addListener(function(request, sender, callback){
    if (request.msg === 'getglobals') {
        chrome.storage.local.get(['globals'], function(storage) {
            callback(JSON.stringify(storage.globals));
        });
    }
    // return true; Working without this
});

而同样的代码在MV2中如果不添加return true,就会报错:Unchecked runtime.lastError: The message port closed before a response was received.

现象原因

这是因为MV3的Service Worker环境和MV2的背景页机制存在本质差异:

  • MV2的背景页是长期运行的页面实例,消息通道的生命周期与背景页直接绑定。当onMessage监听器执行完毕且未返回true时,Chrome会判定不会有异步响应,直接关闭消息端口,后续调用callback时就会因端口已关闭触发报错。
  • MV3的Service Worker是事件驱动的临时运行环境,Chrome会自动延长其存活时间,直到所有关联的异步操作(包括消息回调)完成。即使监听器没有返回true,Chrome也会等待异步任务执行结束后再回收Service Worker,消息端口会保持开放直到callback被调用,因此不会报错。

注意事项

虽然MV3中不返回true也能正常工作,但仍然建议遵循官方文档要求返回true——这是明确的语义声明,可避免未来Chrome对Service Worker存活逻辑调整带来的兼容性风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:18:18