reactjswebpackgoogle-chrome-extensionbundling-and-minificationdev-to-production

Chrome extension + webpack - message passing in production mode


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!


Solution

  • 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.