gs-br-ext
v0.1.4
Published
一个基于 TypeScript 开发的 Chrome 浏览器扩展常用 API 封装库,提供简洁、类型安全的浏览器扩展开发接口。
Readme
gs-br-ext
一个基于 TypeScript 开发的 Chrome 浏览器扩展常用 API 封装库,提供简洁、类型安全的浏览器扩展开发接口。
A TypeScript-based Chrome browser extension API wrapper library that provides clean, type-safe interfaces for browser extension development.
功能特性 / Features
TypeScript 支持:提供完整的类型定义,确保类型安全
模块化架构:清晰的模块划分,便于扩展和维护
消息通信 (message):
- 简化扩展组件间的消息传递
- 支持向当前激活标签页、指定ID标签页、URL匹配标签页发送消息
- 支持批量向多个标签页发送消息
连接管理 (connect):
- 封装长连接通信,支持客户端/服务器模式
- 支持连接生命周期管理
- 提供连接方法代理,简化方法调用
存储管理 (storage):
- Promise 化的存储 API 封装
- 支持本地存储和同步存储
- 类型安全的数据存取
标签页控制 (tabs):
- 简化标签页的创建和查找
- 支持基于URL的标签页查找和批量操作
侧边面板 (side-panel):侧边面板功能支持
调试支持:内置调试跟踪功能,便于开发和调试
TypeScript support with complete type definitions for type safety
Modular architecture for easy extension and maintenance
Message communication:
- Simplified message passing between extension components
- Support for sending messages to active tabs, tabs by ID, and URL-matched tabs
- Support for batch messaging to multiple tabs
Connection management:
- Encapsulated long-connection communication with client/server mode support
- Connection lifecycle management
- Connection method proxies for simplified method calls
Storage management:
- Promise-based storage API wrapper
- Support for local and sync storage
- Type-safe data access
Tab control:
- Simplified tab creation and searching
- URL-based tab finding and batch operations
Side panel functionality support
Debug support with built-in debugging and tracing capabilities
技术栈 / Technology Stack
- TypeScript
- Chrome Extension API
- gs-base
安装 / Installation
克隆项目
git clone https://github.com/yourusername/gs-br-ext.git
cd gs-br-ext安装依赖
npm install
# 或
yarn install使用说明 / Usage
作为依赖安装
npm install gs-br-ext
# 或
yarn add gs-br-ext在项目中使用
导入整个库
import * as gsBrExt from 'gs-br-ext';
// 使用存储功能
await gsBrExt.StorageLocal.setValue('key', 'value');
const value = await gsBrExt.StorageLocal.getValue<string>('key');
// 使用消息通信
const messageProxy = gsBrExt.createMsgMethodProxy<{
getData: (id: string) => Promise<any>
}>();导入特定模块
// 导入消息模块
import { createMsgMethodProxy, setMsgMethod } from 'gs-br-ext/message';
// 导入连接模块
import { connect, createConnectMethodsProxy } from 'gs-br-ext/connect';
// 导入存储模块
import { StorageLocal, StorageSync } from 'gs-br-ext/storage';
// 导入标签页模块
import { findTabs } from 'gs-br-ext/tabs';核心模块 / Core Modules
connect
提供扩展各部分之间的通信连接功能。
Provides communication connection functionality between different parts of the extension.
message
处理扩展内外部的消息传递。
Handles message passing within and outside the extension.
storage
封装 Chrome 存储 API,提供便捷的数据存储管理。
Encapsulates Chrome Storage API for convenient data storage management.
tabs
提供标签页的创建、查找和管理功能。
Provides tab creation, finding, and management functionality.
核心模块使用说明 / Core Module Usage
Message 模块
Message 模块提供了简化的消息通信功能,用于扩展组件间的通信。支持向单个标签页或多个标签页发送消息。
基本用法
import { setMsgMethod, createMsgMethodProxy } from 'gs-br-ext';
// 在后台脚本中设置消息处理方法
setMsgMethod('getUserData', async (userId: string) => {
// 获取用户数据的逻辑
return { id: userId, name: 'User Name', email: '[email protected]' };
});
// 在内容脚本或弹出页面中创建消息代理并调用方法
const messageProxy = createMsgMethodProxy<{
getUserData: (userId: string) => Promise<{ id: string; name: string; email: string }>
}>();
// 调用后台脚本中定义的方法
const userData = await messageProxy.getUserData('12345');
console.log(userData);向标签页发送消息
import { createTabMsgMethodProxy } from 'gs-br-ext';
// 创建向当前激活标签页发送消息的代理
const activeTabProxy = createTabMsgMethodProxy<{
updateContent: (content: string) => Promise<boolean>
}>();
// 向当前激活标签页发送消息
await activeTabProxy.updateContent('New content');
// 创建向指定ID标签页发送消息的代理
const tabIdProxy = createTabMsgMethodProxy<{
updateContent: (content: string) => Promise<boolean>
}>(123); // 123是标签页ID
// 向指定ID标签页发送消息
await tabIdProxy.updateContent('New content for tab 123');
// 创建向URL匹配标签页发送消息的代理
const urlProxy = createTabMsgMethodProxy<{
updateContent: (content: string) => Promise<boolean>
}>('https://example.com/*');
// 向URL匹配标签页发送消息
await urlProxy.updateContent('New content for example.com tabs');批量向标签页发送消息
import { createTabsMsgMethodProxy } from 'gs-br-ext';
// 创建向所有匹配URL的标签页发送消息的代理
const tabsProxy = createTabsMsgMethodProxy<{
refreshData: (timestamp: number) => void
}>('https://example.com/*');
// 向所有匹配URL的标签页发送消息
// 注意:此方法没有返回值
tabsProxy.refreshData(Date.now());Connect 模块
Connect 模块提供了长连接通信功能,支持客户端/服务器模式。适合需要持续通信的场景。
服务器端(后台脚本)
import { createConnectServerMethodProxy, setConnectServerMethod, addConnectServerListener, addDisconnectServerListener } from 'gs-br-ext';
// 设置连接服务器的方法
setConnectServerMethod('subscribeToUpdates', async (topic: string) => {
// 订阅更新的逻辑
console.log(`Client subscribed to: ${topic}`);
// 返回初始数据
return { success: true, topic };
});
// 创建服务器方法代理(可选)
const serverProxy = createConnectServerMethodProxy<{
notifyClients: (message: string) => void
}>();
// 使用代理向客户端发送消息
serverProxy.notifyClients('Server notification');
// 添加连接事件监听器
addConnectServerListener((port) => {
console.log('New connection established:', port);
// 可以在这里执行连接建立时的逻辑
});
// 添加断开连接事件监听器
addDisconnectServerListener((port) => {
console.log('Connection disconnected:', port);
// 可以在这里执行连接断开时的逻辑
});客户端(内容脚本或弹出页面)
import { connect, setConnectMethod } from 'gs-br-ext';
// 建立连接
const connection = await connect('my-connection', {
onConnect: (context) => {
console.log('Connection established:', context);
},
onMessage: (message, context) => {
console.log('Received message:', message);
},
onDisconnect: (context) => {
console.log('Connection disconnected:', context);
}
});
// 设置客户端方法(供服务器调用)
setConnectMethod('handleUpdate', (data) => {
console.log('Received update from server:', data);
});
// 调用服务器方法
const result = await connection.subscribeToUpdates('news');
console.log('Subscription result:', result);Storage 模块
Storage 模块提供了 Promise 化的存储 API 封装,支持本地存储和同步存储。
基本用法
import { StorageLocal, StorageSync } from 'gs-br-ext';
// 使用本地存储
// 保存数据
await StorageLocal.setValue('user', { id: '123', name: 'User Name' });
// 获取数据
const user = await StorageLocal.getValue<{ id: string; name: string }>('user');
console.log(user);
// 使用同步存储
// 保存设置
await StorageSync.setValue('settings', { theme: 'dark', language: 'zh-CN' });
// 获取设置
const settings = await StorageSync.getValue<{ theme: string; language: string }>('settings');
console.log(settings);
// 创建自定义存储实例
import { Storage } from 'gs-br-ext';
// 创建本地存储实例
const customStorage = new Storage('local');
await customStorage.setValue('customKey', 'customValue');
const customValue = await customStorage.getValue<string>('customKey');Tabs 模块
Tabs 模块提供了简化的标签页控制功能,包括标签页的创建和查找。
查找标签页
import { findTabs } from 'gs-br-ext';
// 根据URL查找标签页
const tabs = await findTabs('https://example.com/*');
console.log('Found tabs:', tabs);
// 查找多个URL匹配的标签页
const multipleTabs = await findTabs(['https://example.com/*', 'https://test.com/*']);
console.log('Found multiple tabs:', multipleTabs);
// 查找标签页,如果不存在则创建
const tab = await findTabs('https://example.com', {
active: true,
currentWindow: true
});
console.log('Found or created tab:', tab);Side Panel 模块
Side Panel 模块提供了侧边面板功能支持。
import { setOpenPanelOnActionClick } from 'gs-br-ext';
// 设置点击扩展图标时打开侧边栏
setOpenPanelOnActionClick(true);
// 设置点击扩展图标时不打开侧边栏
setOpenPanelOnActionClick(false);构建后的文件将输出到 dist 目录。
许可证 / License
MIT License
