Goal
I am trying to build a chrome extension that adds UI components to an existing third-party website which uses Next.js for its frontend.
Approach
The content script is in charge of injecting the UI components into the website. For the current version of the extension, I add the UI components once when the website has newly loaded (e.g. initial load, refresh, etc.) and when the DOM tree is extended with new containers on the website. For this purpose, I am using an anonymus function that gets invoked at the end of the content script which injects the UI components at the respective positions in the DOM tree. Additionally, a MutationObserver
looks for changes in the DOM tree in order to inject the UI components on dynamically and newly created nodes in the DOM tree.
When the content script is first loaded, the anonymus function also passes a message to the service worker of the extension, to let it know that the receiving end exists and it is ready to receive messages from the service worker.
The website uses client-side routing for subsequent updates of the page contents. For this case, I create an EventListener in the service worker via the chrome.webNavigation.onHistoryStateUpdated
API that passes a message to my content script whenever client-side routing occurs so I can retrigger the UI component injection.
Problem
The problem is that the service worker sometimes sends messages on tabs that are active, but are not the website that I want the chrome extension to be restricted to. In the manifest.json
, I set the "matches" field to match the pattern of the website URL that I want my extension to be restricted to. How can I ensure that the content script only sends messages on when a tab is active and the domain is the one of the website? Is there a message passing concept for ensuring that messages are only passed between "valid" tabs and the service worker?
Proposed Solution
I am thinking of implementing a TabRegistry
function as a class in the service worker that much like a Service Registry takes care of tabs belonging to the targeted third-party website and their states. Is this an approach worth pursuing? Do you have better or simpler ideas, or experience with avoiding "Receiving end does not exist"
errors in chrome extension restricted to a certain "match pattern"
?
I am happy to hear your thoughts and be pointed to any resources on how to understand message passing and the best practices associated with it!