web-ipc
v1.3.0
Published
A TypeScript library for IPC communication in web applications and browser extensions
Downloads
13
Maintainers
Readme
Web IPC
A TypeScript library for IPC (Inter-Process Communication) between different contexts (e.g. chrome extension's content.js and background.js) in web. It provides a native-like calling experience between different contexts.
Features
- Native-like method invocation between different contexts
- Full TypeScript support ensuring type safety
- Promise-based async method call support
- Context-based service registration and invocation
Installation
npm install web-ipcUsage
1. define an interface
export interface BackgroundNotificationInterface {
// must return a Promise
notify(title: string, message: string): Promise<string>
}2. implement the interface in background script and register it
class BackgroundNotification implements BackgroundNotificationInterface {
async notify(title: string, message: string): Promise<string> {
let notificationId = `notification-${Date.now()}`;
chrome.notifications.create(notificationId, {
type: 'basic',
title: title,
message: message
});
return notificationId;
}
}
import {chromeRuntimeMessageIpcProviderRegister} from "web-ipc";
chromeRuntimeMessageIpcProviderRegister("BackgroundNotificationInterface", new BackgroundNotification())3. call the interface in content script or popup script by creating a proxy
import {chromeRuntimeIpcInvoker} from "web-ipc";
const backgroundNotification = chromeRuntimeIpcInvoker.createProxy<BackgroundNotificationInterface>("BackgroundNotificationInterface")
let notificationId = await backgroundNotification.notify("hello", "this is a notification from content script")
console.log(notificationId)The examples above use chrome.runtime for communication
For communication via window.postMessage, use windowMessageIpcProviderRegister and windowMessageIpcInvoker.
Advanced Usage
Access Raw Communication Info with $rawInfos
You can access the raw communication information (such as sender info in Chrome extensions) by adding a parameter named $rawInfos to your method. This parameter will be automatically injected with the underlying communication details.
export interface BackgroundNotificationInterface {
notify(title: string, message: string, $rawInfos?: any): Promise<string>
}
class BackgroundNotification implements BackgroundNotificationInterface {
async notify(title: string, message: string, $rawInfos?: any): Promise<string> {
// For chrome.runtime, $rawInfos contains the sender object
console.log('Sender tab ID:', $rawInfos?.sender?.tab?.id);
console.log('Sender URL:', $rawInfos?.sender?.url);
let notificationId = `notification-${Date.now()}`;
chrome.notifications.create(notificationId, {
type: 'basic',
title: title,
message: message
});
return notificationId;
}
}Note: The $rawInfos parameter is optional and will be automatically injected by the framework. You don't need to pass it when calling the method from the client side.
License
MIT
