0

We are in process of upgrading many Chrome extensions to Manifest version 3. Many of them has a background script that use localStorage which is not available in Service Worker. I know chrome.storage or IndexedDB APIs are valid replacement but they are asynchronous and it would takes a lot of effort for some extensions to be changed into async. So my problem can be solved by either:

  • Find a storage API that is NOT async which I am not aware of.

  • Question: Find a pattern that can quickly and reliably upgrade synchronous code in many places into asynchronous.

I believe the 2nd attempt is the most sensible one. However so many places have methods like this (just example) which makes upgrading difficult and also prone to error due to missing Promise/await.

// Background
localStorage["key"] = true;

if (localStorage["key2"]) {
    // Do stuff
}

// Foreground/Popup/Content Script
if (localStorage["key"]) { /* Do Something */ }
if (localStorage["key2"]) { /* Do Something Else */ }
localStorage["key3"] = "My Value";

There are a few nice extensions with these code, which are easy to upgrade:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.method == "getLocalStorage") {
        sendResponse({ data: localStorage[request.key] });
    }
});

Which I simply need to change the message handler to async since the receiving end is already callback-based. Unfortunately, every extension is very different and there is no standard way of doing it.

Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • There's no such storage. You can use async/await syntax to preserve the flow. – wOxxOm Feb 07 '22 at 22:00
  • @wOxxOm Thanks, as I suspected. Changing to `async/await` is prone to error due to missing `await` though because `if (promise) {}` or `if (promise["key"])` is still considered correct even with TypeScript. I was hoping there is a way to prevent such mistake. – Luke Vo Feb 07 '22 at 22:03
  • [Detect missing await in JavaScript methods in VSCode](https://stackoverflow.com/a/70100703) – wOxxOm Feb 07 '22 at 22:11
  • Uhm, actually, in simple cases, you can use just one await at the beginning of the listener, [example](https://developer.chrome.com/docs/extensions/reference/storage/#asynchronous-preload-from-storage). – wOxxOm Feb 07 '22 at 22:14
  • @wOxxOm Thanks. I am aware of that ES Lint option. I was hoping for a solution without it but guess I will resort to it if there is no other way. – Luke Vo Feb 07 '22 at 22:31

0 Answers0