0.0.4 • Published 18 days ago

@webext-pegasus/rpc v0.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
18 days ago

webext-pegasus Logo

@webext-pegasus/rpc

License GitHub Actions Workflow Status Package version

RPC Messaging in Web Extensions made easy and type safe. Out of the box. It provides a simple type-safe wrapper around the web extension messaging APIs that lets you call a function/class from anywhere, but execute it in the target runtime context.

Supports

  • Runtime contexts: window (injected script), popup, devtools, content script, background, options, sidepanel (planned)
  • Browsers: Chrome, Firefox, Safari, Opera, Edge + others supported by webextension-polyfill

🚀 Quick Start

npm install -S @webext-pegasus/transport @webext-pegasus/rpc
  • Create service in a form of a class or function that implements IPegasusRPCService<YourService>
  • Export TypeScript interface for it
  • Register interface via registerRPCService('serviceName', yourService) in the target runtime context (ex: background)
  • Acquire service wrapper via getRPCService<YourServiceType>('serviceName', 'background')
    • That's it! Now you can call it from any other place in your extension!

MathService.ts

import {IPegasusRPCService, PegasusRPCMessage} from '@webext-pegasus/rpc';

export type IMathService = InstanceType<
  typeof MathService
>;

export class MathService
  implements IPegasusRPCService<MathService>
{
  fibonacci(num: number): number {
    return (num <= 1) ? 1 : this.fibonacci(num - 1) + this.fibonacci(num - 2);
  }
}

background.ts

import {registerRPCService} from '@webext-pegasus/rpc';
import {initPegasusTransport} from '@webext-pegasus/transport/background';

import {MathService} from './MathService.ts';

// Done once in every runtime context to init transport layer
initPegasusTransport();

registerRPCService(
  'MathService',
  new MathService(),
);

injected.ts

// Important to import type only as we don't want to cause any errors by injecting
// code that expects web extension runtime to be loaded on target webpag
import type {IMathService} from './MathService.ts';

import {getRPCService} from '@webext-pegasus/rpc';
import {initPegasusTransport} from '@webext-pegasus/transport/window';

// Done once in every runtime context to init transport layer
initPegasusTransport();

const mathService = getRPCService<IMathService>(
  // Same ID that was used for registration
  // We may have multiple instances of the same service executed independently
  'MathService',
  // Where sevice was registered
  'background',
);

// Note that now mathService.fibonacci() returns Promise
mathService.fibonacci(10).then(console.log);
// Output: 89