Remote Procedure Call implementation for WebExtensions, to easily call functions across content scripts and background script.

webextension-rpc/example/ background-script.ts
20 lines
781 B

  1. import { RpcClient, RpcServer } from 'webextension-rpc';
  2. import type { RpcInfo } from 'webextension-rpc';
  3. // Only import the *types* of the remote script’s functions.
  4. import type { contentScriptRpcServer } from './content-script';
  5. // From background to content script.
  6. const contentScriptRpc = new RpcClient<typeof contentScriptRpcServer>({ tabId: 123 });
  7. const setColour = contentScriptRpc.func('setColour');
  8. await setColour('blue');
  9. // From content to background script.
  10. const backgroundScriptRpcServer = new RpcServer({
  11. async duplicateTab(rpcInfo: RpcInfo, active: boolean) {
  12. const newTab = await browser.tabs.duplicate(rpcInfo.tab.id, { active });
  13. return newTab.id;
  14. },
  15. async timesTwo(x: number) { return 2 * x },
  16. });
  17. export type { backgroundScriptRpcServer }