Installation
MV2 MV3 Chrome Firefox Safari
Overview
@webext-core/proxy-service
provides a simple, type-safe way to execute code in the extension's background.
MathService.ts
import { defineProxyService } from '@webext-core/proxy-service';
// 1. Define your service
class MathService {
async fibonacci(number: number): Promise<number> {
...
}
}
export const [registerMathService, getMathService] = defineProxyService(
'MathService',
() => new MathService(),
);
Installation
NPM
pnpm i @webext-core/proxy-service
import { defineProxyService } from '@webext-core/proxy-service';
CDN
curl -o proxy-service.js https://cdn.jsdelivr.net/npm/@webext-core/proxy-service/lib/index.global.js
<script src="/proxy-service.js"></script>
<script>
const { defineProxyService } = webExtCoreProxyService;
</script>
Usage
Lets look at a more realistic example, IndexedDB! Since the same IndexedDB database is not available in every JS context of an extension, it's common to use the IndexedDB instance in the background script as a database for web extensions.
First, we need to implementat of our service. In this case, the service will contain CRUD operations for todos in the database:
TodosRepo.ts
import { defineProxyService, flattenPromise } from '@webext-core/proxy-service';
import { IDBPDatabase } from 'idb';
function createTodosRepo(idbPromise: Promise<IDBPDatabase>) {
const idb = flattenPromise(idbPromise);
return {
async create(todo: Todo): Promise<void> {
await idb.add('todos', todo);
},
getOne(id: Pick<Todo, 'id'>): Promise<Todo> {
return idb.get('todos', id);
},
getAll(): Promise<Todo[]> {
return idb.getAll('todos');
},
async update(todo: Todo): Promise<void> {
await idb.put('todos', todo);
},
async delete(todo: Todo): Promise<void> {
await idb.delete('todos', todo.id);
},
};
}
In this example, we're using a plain object instead of a class as the service. See the Defining Services docs for examples of all the different ways to create a proxy service.
In the same file, define a proxy service for our TodosRepo
:
TodosRepo.ts
// ...
export const [registerTodosRepo, getTodosRepo] = defineProxyService('TodosRepo', createTodosRepo);
Table of Contents