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

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

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