Am I using Port Messaging correctly?

I have the following:

background/ports/alarms.ts
// don't need anything from here. The entire goal here is to have background -> foreground comms
import type { PlasmoMessaging } from '@plasmohq/messaging';

const handler: PlasmoMessaging.PortHandler = async (req, res) => {
  console.log('handler is running');
  res.send({});
};

export default handler;


background/index.ts
chrome.alarms.onAlarm.addListener(async (alarm) => {
  const test = getPort('alarms');

  console.log('posting message');
  test.postMessage({
    type: 'test',
  });


foreground/somewhere.ts
chrome.alarms.create(tabToAlarmMap[name], {
    when,
  });


finally in foreground/index.tsx
function Test() {
  const mailPort = usePort('alarms');

  useEffect(() => {
    console.log('adding listener');
    mailPort.listen((msg) => {
      console.log('got message', msg);
    });
  }, [mailPort]);

  console.log(mailPort);
  return null;
}

<Test />


I see adding listener in the console but whenever the alarm is triggered I get this error: checked runtime.lastError: Could not establish connection. Receiving end does not exist.
Was this page helpful?