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

Readme.md 2.1 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # webextension-rpc
  2. This module provides a *Remote Procedure Call* abstraction around the message passing that is
  3. available to WebExtension (browser extension) scripts. It makes it easier to call a function in the
  4. background script from a tab’s content script, or vice versa.
  5. ## Example use
  6. In `background.js`:
  7. function myFunc(arg) {
  8. return arg * 2
  9. }
  10. makeRemotelyCallable({ myFunc })
  11. In `content_script.js`:
  12. const myRemoteFunc = remoteFunction('myFunc')
  13. myRemoteFunc(21).then(result => { ... result is 42! ... })
  14. Note that the remote function always returns a `Promise`, which resolves with the remote function’s
  15. actual return value (if the return value is itself a Promise, its result is awaited too).
  16. ## Install
  17. ### Using NPM
  18. This module is published [on npm](https://www.npmjs.com/package/webextension-rpc).
  19. Run `npm install webextension-rpc` or equivalent.
  20. ### Standalone
  21. Try one of the magic npm bundlers, for example:
  22. `wget https://wzrd.in/standalone/webextension-rpc -O webextension-rpc.js`
  23. ## API
  24. ### `remoteFunction(functionName, { tabId })`
  25. Create a proxy function that invokes the specified remote function.
  26. - `functionName` (string, required): name of the function as registered on the remote side.
  27. - `options` (object, optional):
  28. - `tabId` (number): The id of the tab whose content script is the remote side. Leave undefined
  29. to call the background script (from a content script).
  30. ### `makeRemotelyCallable(functions, { insertExtraArg })`
  31. Register one or more functions to enable remote scripts to call them. Arguments:
  32. - `functions` (object, required): An object with a `{ functionName: function }` mapping. Each
  33. function will be remotely callable using the given name.
  34. - `options` (object, optional):
  35. - `insertExtraArg` (boolean, default is `false`): If truthy, each executed function also
  36. receives, as its first argument before the arguments it was invoked with, a [Tab][] object,
  37. which contains the details of the tab that sent the message.
  38. [Tab]: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/Tab