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

webextension-rpc/example/ content-script.ts
21 lines
686 B

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