Advanced Chrome Extension Message Passing Guide / Tutorial / Template
Recently I began development on a Chrome extension and needed to pass messages between multiple parts of it. I noticed a severe dearth of adequate guides, and while it’s not super difficult, the other guides seemed far too complex to be useful for a beginner.
The data would first be collected by the content script. In my case this is on the click of a button but it could also just run immediately. The data cannot be passed directly to the popup.js script because the popup.js script only runs when the popup is visible while the background.js script runs persistently. The button click also triggers a message to be sent to the background.js. Usually a response function wouldn’t be necessary because the content script would only be collecting data but it could be implemented in the same way as in the popup.js. In the case you wanted to only modify website data, you would be able to skip the background.js entirely. The background.js should only be used to process and store data if it needs to be later used or displayed.
The background determines the type of message, processes the data then stores or returns the data. While the data could be processed in the content.js before being sent, generally it’s a good idea to keep all logic in one location.
To display data in the popup we send a message to the background and then interact with the response data.
The hardest part about getting up and running with Chrome extensions is to figure how and where to store the data. Hopefully this can serve as an template to help you get up and running! Below you can also find a simple version of the manifest.json configuration to make all of these function properly.
Please check out my website at http://zachhardesty.com for more information about myself!