0

When I write content-script to send msg to service-worker every X time, should I use chrome.alarms or setInterval?

This is what I wrote:

content-script.js

const send = (async () => {
  try {   
    const response = await chrome.runtime.sendMessage({ msg: "ping" });
    console.log(response)
  } catch {
    console.log("problem")
  }
});

setInterval(send, 1000) // or chrome.alarms... 

background.js

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(request.msg)
    sendResponse({ msg: "pong" })
  }
);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Nati
  • 116
  • 1
  • 5
  • 2
    Is that what you wrote working? if yes, then what's your problem? If no, what's the error? I don't really understand your question? – Sally loves Lightning Jul 14 '23 at 18:12
  • 2
    Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jul 14 '23 at 19:04
  • it looks like it's working, but I'm not sure that using setInterval is the correct way, and maybe it will be a problem with more complex code. – Nati Jul 14 '23 at 19:38
  • @Nati - Like the Community Bot wrote, we need more information about yout extension. We can't tell you if chrome.alarms or setInterval is better suited to your extension because we know nothing about it. Please tell us what your extension does, and why the content script needs to send messages to the service worker. – Thomas Mueller Jul 14 '23 at 20:04
  • 2
    Content scripts can't use chrome.alarms. Note that the web page can clear your interval, so a more reliable method is to use the timer inside the service worker, see also [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm Jul 14 '23 at 20:10
  • thank you @wOxxOm, that was very helpful :) – Nati Jul 15 '23 at 14:40
  • @wOxxOm But how to trigger a function in content script from service worker using chrome.alarms? AFAIK, service worker cannot send a message to content script without getting a message first from it... – callmekatootie Aug 30 '23 at 16:08
  • Use chrome.tabs.sendMessage. – wOxxOm Aug 30 '23 at 16:28

0 Answers0