Blog
Contact

Persisting State in Chrome Extension Service Workers

The official documentation from Google Chrome says "Any global variables you set will be lost if the service worker shuts down." But, I believe, a better way to put it would be this: "Any variables created during the execution of the service worker context will be lost when the service worker shuts down." because variables that were created in function contexts will also be lost, not only "global" variables.

Global variables are killed when service worker restarts

  • Don’t rely on temporary variables to persist inside of the background service worker of your chrome extension.
  • Always use chrome.storage.local or chrome.storage.sync to access the state of your plugin.
  • chrome.storage.local and chrome.storage.sync are not the same, so be sure to only use one of them.
  • Calling chrome.storage.local.get before calling chrome.sidePanel.open will result in an error in Chrome 131.

Example

For example, let’s say that our extension needs to track the number of user clicks on the extension icon.

  • Clicking on the icon activates our background service worker.
  • The worker can store the number of clicks in a global variable and in chrome.storage.local
  • After 30 seconds the worker will become inactive.
  • When it becomes active again - information in the global variable will be gone, but data stored in chrome.storage.local will be saved.

References