chrome-extension-webpack-boilerplate icon indicating copy to clipboard operation
chrome-extension-webpack-boilerplate copied to clipboard

Enabling HMR for content scripts

Open arseneyr opened this issue 4 years ago • 3 comments

I have a change to enable Hot Module Reloading for Chrome extension content scripts:

https://github.com/arseneyr/chrome-extension-webpack-boilerplate/tree/content-hmr

This change includes a new webpack plugin that does the following:

  • Modifies the HMR runtime in content scripts to use fetch() and eval() instead of JSONP for downloading hot update chunks. JSONP does not work for content scripts because adding a script tag to the DOM executes that script in the context of the host site, not the content script.
  • Modifies the webpack/hot/dev-server script to send a message to the background script in case a full reload is needed. The background bundle includes a small script to listen for the message and call chrome.runtime.reload() to reload the entire extension.

There are also some changes to the webpack-dev-server parameters so that the websocket client connects inside content scripts:

  • Use the native WS client instead of sock-js because sock-js has trouble connecting when the host site is HTTPS.
  • Use 127.0.0.1 as the websocket target domain in order to prevent the WS client from using a wss:// protocol.
  • Set the webpack public path to http://127.0.0.1:3000 so any requests for HMR manifests, hot chunks, etc. go to the webpack-dev-server instead of the host site.
  • Modify the manifest to include http://127.0.0.1:3000 in the content_security_policy.

I'm happy to open a PR if you think this change is valuable.

arseneyr avatar Mar 16 '20 05:03 arseneyr

how would you integrate this into the react branch? i'd like to use this in my project. @arseneyr

ShravanSunder avatar Jun 26 '20 18:06 ShravanSunder

I have a branch where I merged the react changes with the content HMR changes: https://github.com/arseneyr/chrome-extension-webpack-boilerplate/tree/react

Haven't tested it thoroughly but you can give it a try.

arseneyr avatar Jun 27 '20 22:06 arseneyr

I created a repo by create-react-app, it uses react-refresh to achieve partial refresh and uses sse to enable HMR for Chrome extension content scripts: cra-crx-boilerplate

Godiswill avatar May 20 '22 05:05 Godiswill