I have always wanted to make a bilibili barrage extension. I recently took the opportunity of researching Vite to do it. It took two days to build a Chrome Extension (MV3) development environment based on Vite + React. The core functions are as follows:
-📦️ JS packaged into a single file
-🎨 Automatically introduce CSS
-🔨 Package service worker
-🚀 Hot reload of development environment
Here is a focus on the implementation of the current hot update. Other functions are relatively simple. For details, please refer to yunslove/violet
I watched "Violet Evergarden" at bilibili, which was impressive. Just this time I planned to be a barrage extension of bilibili, and simply took the heroine's name violet 😃
The general process of hot update is shown in the figure below:
Execute three commands simultaneously through
npm run dev:
-tsc compile service worker and monitor changes
-vite compile extension
-The websocket service monitors the changes of the directory /dist after packaging
After the browser page loads the content scripts, a websocket link will be created. After receiving the request, the server will start listening to the
/dist directory. The websocket service will actively initiate a notification after listening to the change of
The content scripts receive the notification that the extension needs to be updated, and trigger the event registered in the service worker by
chrome.runtime.sendMessage, which triggers
chrome.tabs.reload in turn to update Extension and current page. What you write is what you get without any manual intervention 🚀
Readers may have a question, why not listen for notifications from websocket directly in the service worker?
I have been thinking the same way before. The use of service workers under Manifest V3 promotes Thinking with events through
chrome.runtime.onStartup to create a websocket client will be closed unexpectedly, even if the timer polling is used, it will be closed and restarted after multiple executions. Therefore, the best solution currently found is to monitor the
chrome.runtime.onMessage event in the service worker.
In this way, the hot update process will only be triggered when the page loads the current Extension.
Since most of the current Chrome Extension versions are lower than the MV3 version, I have stepped on a lot of pits in the past two days, and I have a certain degree of understanding of browser extension development that I have not touched before. Now it is only for the Chrome Extension scenario. I will continue to improve the current scenario to complete the support for other browser extensions. Finally, it should be possible to encapsulate a tool for browser extension development.
Translate from Chinese, checkout by yunslove