英文:
Chrome extension + webpack - message passing in production mode
问题
我正在使用React和webpack构建Chrome扩展程序。我使用Chrome消息API在后台页面和弹出窗口或内容脚本之间进行通信。在后台脚本中,我使用browser.runtime.onMessage.addListener
,在弹出窗口中,我使用browser.runtime.sendMessage
。
在开发模式下,一切正常。我可以轻松地在后台页面和弹出窗口之间发送消息。但是,当我在生产模式下使用代码拆分捆绑扩展程序时,消息API不起作用。当运行browser.runtime.sendMessage
时,我收到此错误消息:Error: Could not establish connection. Receiving end does not exist.
这里有一个复制存储库:https://github.com/sleaper/extension-error-reproduction
我可以这样使用webpack吗?如果您有更多问题,请随时提问!
英文:
I am building a chrome extension in React and webpack. I use chrome messaging API to communicate between the background page and the popup or content script. In the background script, I use browser.runtime.onMessage.addListener
and in popup, I use browser.runtime.sendMessage
.
In development mode, everything works great. I can easily send messages between the background page and the popup. Sadly when I bundle extension in production mode with code splitting, the messaging API does not work. When browser.runtime.sendMessage
is run I get this error message: Error: Could not establish connection. Receiving end does not exist.
Here is a reproduction repo: https://github.com/sleaper/extension-error-reproduction
Can I use webpack in this way?
If you have more questions feel free to ask!
答案1
得分: 1
这是由代码拆分引起的。
Webpack块只在作为多个脚本标签包含时才真正运行,但在你的重现中,你只加载主块,所以它甚至不会运行你的背景页面代码。
解决方法是使用由Webpack HtmlWebpackPlugin 生成的自定义index.html文件来为背景页面生成。
英文:
This is caused by code splitting.
Webpack chunks only really run when included as multiple script tags, but in your reproduction you only load the main chunk so it never even runs your background page code.
Solution is to use a custom index.html for background page generated from webpack HtmlWebpackPlugin.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论