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

webextension-rpc/example/ content-script.ts
23 lines
713 B

  1. import {
  2. remoteFunction,
  3. makeRemotelyCallable,
  4. injectRpcInfo,
  5. } from 'webextension-rpc';
  6. // Only import the *types* of the remote script’s functions.
  7. import type { backgroundScriptRemoteFunctions } from './background-script';
  8. // From background to content script.
  9. export const contentScriptRemoteFunctions = makeRemotelyCallable({
  10. async setColour(colour: string) {
  11. document.body.style.backgroundColor = colour;
  12. },
  13. });
  14. // From content to background script.
  15. const duplicateMe =
  16. remoteFunction<typeof backgroundScriptRemoteFunctions.duplicateTab>(
  17. 'duplicateTab',
  18. );
  19. // The injectRpcInfo placeholder will be replaced by actual info.
  20. const newTabId = await duplicateMe(injectRpcInfo, true);