'Injecting React providers around page with Chrome Extension

I'm writing a Chrome extension that injects some React components into a page. Some of these components need to be wrapped by providers to work properly (for example I am using React Query and Chakra UI). I'm currently doing that by wrapping each component with my providers when injecting them into the page, but I have a feeling that is not ideal:

export async function renderComponent(element: HTMLElement) {
  appendComponent(
    <Providers>
      <Component />
    </Providers>,
    element,
    "id",
  );
}

Is there a way to wrap the entire page with my providers so all injected components will have access to them without needing to wrap them individually? I've tried doing something with a content script, but am not sure how to wrap it around the entire page, nor if that would even work.



Solution 1:[1]

  1. I actually think it's better to wrap the injected components with their own providers, this way you have less interactions with the page. And it sounds the providers you have hold no actual state, so there is no harm in doing so. Unfortunately, @vwos is right and the ChakraProvider does have an overhead
  2. If the components you inject into the page are separate react roots (rendered with ReactDOM.render) you can't wrap them all with one provider
  3. if the app you are injecting your components into is in react, and you have control over its code you can pass it the providers as props. but then the injected components need to be added to the existing app tree as well.. sounds like a mess
  4. you can inject a single app (root component) of your own and render the injected components in portals - here is a very simple example, injecting in each div a counter. Inspired by this post. clone the repo, install local extension and try in google.com

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1