Search code examples
typescriptgoogle-chrome-extension

clients.matchAll() gives error "Cannot find name 'clients'" in typescript


Trying to implement the example offered by google here: https://developer.chrome.com/docs/extensions/reference/offscreen/

async function hasOffscreenDocument(path) {
   // Check all windows controlled by the service worker to see if one 
   // of them is the offscreen document with the given path
   const offscreenUrl = chrome.runtime.getURL(path);
   const matchedClients = await clients.matchAll();
   for (const client of matchedClients) {
     if (client.url === offscreenUrl) {
       return true;
     }
   }
   return false;
 }

but I'm getting a typescript error

Cannot find name 'clients'.ts(2304)

I even tried adding "clients" in types in tsconfig.json but nothing happen.


Solution

  • Managed to find a fix for this here: https://github.com/microsoft/TypeScript/issues/14877

    in my case, what worked is:

    declare const self: ServiceWorkerGlobalScope;
    

    in my utils file, where I was calling the function

      const matchedClients = await self.clients.matchAll()
    

    and add webworker in compiler options in tsconfig.json

    {
      "compilerOptions": {
          "lib": ["dom", "es2021", "webworker"]
      }
    }