How can I access the browser API in a React firefox extension sidebar?

To save space I’m not going to share the entire manifest code. I’m trying to rewrite an extension I started creating with venilla js.

I want to keep the sidebar open and if I change web pages or change/toggle tab, I need the url of the page to show up on my react (sidebar) app.

Here’s what I have:

import { useEffect, useState } from 'react'
function App() {
  const [url, setUrl] = useState('')
  useEffect(() => {
    document.addEventListener("url", (e) => {
      setUrl(e.detail);
    });

    return () => {
      document.removeEventListener("url", (e) => {
        setUrl(e.detail);
      });
    };
  }, []);
  return ( 
    <pre  >
      {JSON.stringify(url, null, 2)}
    </pre >
  )

}
export default App;

And then on content-script

browser.runtime.sendMessage({
      type: "notification",
      data: { url: "example.com"} 
    });

and on background.js

browser.runtime.onMessage(handleMessage);
function handleMessage(message) {

  console.log("message received");
  console.log(message)        
  window.localStorage.setItem('store', 'Obaseki Nosa');
  document.dispatchEvent(new CustomEvent("url", { detail: message }));
}

As you can see I was trying to also use local storage or the dispatchEvent and nothing works (I don’t even see the console logs.

Is there a way to do this?

In vanilla js I had access to the browser.tabs anywhere.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.