3

Migrating my extension from MV2 has been a real pain for me. How do I prevent my extension SW from dying before a certain event (like onMessage or onStorageChanged) is triggered? this is the scenario:

1 - Send a message to contentScript from SW

2 - Wait for the contentScript to complete an operation

3 - contentScript sends a message back to SW when it's done

Unfortunately, the SW dies between steps 2 and 3. How can I prevent that?

Armin E
  • 53
  • 7

1 Answers1

4

Don't send separate messages, but use a single message cycle.

  • background service worker:

    chrome.tabs.sendMessage(tabId, {foo: 'bar'}, response => {
      // process the response
    });
    
  • content script:

    chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
      doSomethingAsynchronous(msg).then(sendResponse);
      return true; // keep the channel open
    });
    

This will keep the worker running for up to five minutes. If you need more than that or if you really want to send separate messages then open a new connection via chrome.runtime.connect (documentation) from your content script at the start of the cycle and repeat it every five minutes until the work is done.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • For persistence via serviceWorker messaging see [this repo](https://github.com/guest271314/persistent-serviceworker). – wOxxOm Jan 10 '23 at 13:04