Send message to content script from service worker

673 Views Asked by At

I am using Plasmo to create google chrome extensions.

My requirement is to invoke a function in a Content Script periodically. I tried to use setInterval() but this was not reliable. I read that using chrome.alarms service in the service worker is a better approach.

So, in my service worker, if I have the following code:

// background/ports/timer.ts
import type { PlasmoMessaging } from "@plasmohq/messaging"

async function registerInitAlarm() {
  // Create an alarm that is invoked a second from now, for every 1.5 seconds
  await chrome.alarms.create("initialize", {
    when: Date.now(),
    periodInMinutes: 1
  })
}

const handler: PlasmoMessaging.PortHandler = async (req, res) => {
  const { type, message } = req.body

  if (type === "register") {
    await registerInitAlarm()
  }
}

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === "initialize") {
    // How do I send a message here to the content script?
  }
})

export default handler

As per the documentation, I need to use ports API but it seems to be a request / response based API so it is not clear how I can send a message to the content script when an alarm triggers.

Alternatively, how do I send a message without the plasmo framework / api - because even the regular chrome extension documentation requires me to identify the tab first and then send a message to it (and there could be multiple tabs having my extension / content script)

0

There are 0 best solutions below