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;
// 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',
});
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,
});
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 />
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.
2 Replies
lab
lab•2y ago
Do you need the port api for this or can you just use the alarm callback directly? apparently, ports are whiped by the bgsw if inactive for 5 minutes or so
nahtnam
nahtnamOP•2y ago
Hmm, for context I am building a timer and I want it to work even if the tab is closed Seems like the only way to do that is set an alarm and then process it in the background script actually youre right, I probably dont need the port
Want results from more Discord servers?
Add your server