运行时架构 #
一、架构概览 #
1.1 整体架构 #
Capacitor采用分层架构设计,将Web应用与原生平台解耦:
text
┌─────────────────────────────────────────────────────────────┐
│ Web Application │
│ (React / Vue / Angular / Vanilla) │
├─────────────────────────────────────────────────────────────┤
│ Capacitor Runtime │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ Plugin Layer │ │ Bridge Layer │ │ Config Layer │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ Platform Bridge │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ iOS Bridge │ │Android Bridge │ │ Web Bridge │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
├─────────────────────────────────────────────────────────────┤
│ Native Runtime │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │
│ │ iOS Runtime │ │Android Runtime│ │ Web Runtime │ │
│ │ (WKWebView) │ │ (WebView) │ │ (Browser) │ │
│ └───────────────┘ └───────────────┘ └───────────────┘ │
└─────────────────────────────────────────────────────────────┘
1.2 核心组件 #
| 组件 | 职责 |
|---|---|
| Web Application | 前端应用代码 |
| Capacitor Runtime | JavaScript运行时环境 |
| Plugin Layer | 插件管理与加载 |
| Bridge Layer | JS与原生通信桥接 |
| Platform Bridge | 平台特定桥接实现 |
| Native Runtime | 原生WebView容器 |
二、Web层架构 #
2.1 WebView容器 #
Capacitor在不同平台使用不同的WebView实现:
| 平台 | WebView实现 | 说明 |
|---|---|---|
| iOS | WKWebView | iOS 8+,现代高性能WebView |
| Android | System WebView | Android 5+,系统WebView |
| Web | Browser | 现代浏览器环境 |
2.2 JavaScript运行时 #
javascript
// Capacitor全局对象
window.Capacitor = {
// 核心方法
registerPlugin,
isNative,
addEventListener,
removeEventListener,
// 平台信息
platform: 'ios' | 'android' | 'web',
// 插件实例
Plugins: {
Camera: {...},
Geolocation: {...},
// ...
}
};
2.3 插件加载机制 #
javascript
// 插件注册流程
class PluginRegistry {
private plugins = new Map();
registerPlugin(name: string, impl: any) {
this.plugins.set(name, impl);
}
getPlugin(name: string) {
return this.plugins.get(name);
}
}
// 插件加载
const Capacitor = {
registerPlugin(pluginName: string, options?: any) {
// 检查是否已注册
if (this.Plugins[pluginName]) {
return this.Plugins[pluginName];
}
// 创建代理对象
const plugin = new Proxy({}, {
get: (target, prop) => {
return async (...args) => {
return this.nativeCallback(pluginName, prop, args[0]);
};
}
});
this.Plugins[pluginName] = plugin;
return plugin;
}
};
三、桥接层架构 #
3.1 桥接通信流程 #
text
JavaScript Bridge Native
│ │ │
│ 1. 调用插件方法 │ │
│ ───────────────────────▶ │ │
│ │ 2. 序列化参数 │
│ │ ───────────────────────▶ │
│ │ │
│ │ 3. 执行原生代码 │
│ │ ◀─────────────────────── │
│ │ │
│ │ 4. 返回结果/回调 │
│ 5. 解析结果 │ │
│ ◀─────────────────────── │ │
│ │ │
3.2 iOS桥接实现 #
swift
// CapacitorBridge.swift
class CapacitorBridge: NSObject {
private var webView: WKWebView?
private var plugins: [String: Plugin] = [:]
func callPluginMethod(
pluginName: String,
methodName: String,
options: JSObject,
callback: @escaping (JSObject?) -> Void
) {
guard let plugin = plugins[pluginName] else {
callback(["error": "Plugin not found"])
return
}
plugin.execute(methodName, options: options) { result in
callback(result)
}
}
func sendToJS(pluginName: String, methodName: String, data: JSObject) {
let js = """
window.Capacitor.triggerEvent('\(pluginName)', '\(methodName)', \(data));
"""
webView?.evaluateJavaScript(js)
}
}
3.3 Android桥接实现 #
java
// CapacitorBridge.java
public class CapacitorBridge {
private WebView webView;
private Map<String, Plugin> plugins = new HashMap<>();
@JavascriptInterface
public String callPluginMethod(
String pluginName,
String methodName,
String options
) {
Plugin plugin = plugins.get(pluginName);
if (plugin == null) {
return "{\"error\": \"Plugin not found\"}";
}
JSObject result = plugin.execute(methodName, new JSObject(options));
return result.toString();
}
public void sendToJS(String pluginName, String methodName, JSObject data) {
String js = String.format(
"window.Capacitor.triggerEvent('%s', '%s', %s);",
pluginName, methodName, data.toString()
);
webView.post(() -> webView.evaluateJavascript(js, null));
}
}
3.4 Web桥接实现 #
javascript
// Web平台桥接
class WebBridge {
constructor() {
this.plugins = new Map();
}
async callPluginMethod(pluginName, methodName, options) {
const plugin = this.plugins.get(pluginName);
if (!plugin) {
throw new Error(`Plugin ${pluginName} not found`);
}
const method = plugin[methodName];
if (!method) {
throw new Error(`Method ${methodName} not found`);
}
return await method.call(plugin, options);
}
triggerEvent(pluginName, eventName, data) {
const event = new CustomEvent(
`capacitor:${pluginName}:${eventName}`,
{ detail: data }
);
window.dispatchEvent(event);
}
}
四、插件系统架构 #
4.1 插件接口定义 #
typescript
// 插件基础接口
interface Plugin {
// 插件名称
readonly name: string;
// 初始化
load?(): void;
// 清理
unload?(): void;
// 方法调用
execute(methodName: string, options: any): Promise<any>;
}
// 插件方法装饰器
interface PluginMethod {
name: string;
returnType: 'promise' | 'callback' | 'event';
paramType?: any;
}
4.2 插件生命周期 #
text
┌──────────────────────────────────────────────────────────┐
│ Plugin Lifecycle │
├──────────────────────────────────────────────────────────┤
│ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Load │───▶│ Register│───▶│ Ready │ │
│ └─────────┘ └─────────┘ └─────────┘ │
│ │ │ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────┐ ┌─────────────┐ │
│ │ Error │ │ Execute │ │
│ └─────────┘ │ Methods │ │
│ └─────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ Unload │ │
│ └─────────────┘ │
│ │
└──────────────────────────────────────────────────────────┘
4.3 插件注册机制 #
typescript
// 插件注册
import { registerPlugin } from '@capacitor/core';
const MyPlugin = registerPlugin<MyPluginInterface>('MyPlugin', {
web: () => import('./web').then(m => new m.MyPluginWeb()),
ios: () => import('./ios').then(m => new m.MyPluginIOS()),
android: () => import('./android').then(m => new m.MyPluginAndroid())
});
// 使用插件
await MyPlugin.doSomething();
五、配置系统架构 #
5.1 配置加载流程 #
text
┌──────────────────────────────────────────────────────────┐
│ Configuration Loading │
├──────────────────────────────────────────────────────────┤
│ │
│ capacitor.config.json │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Parse Config │ │
│ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Merge Defaults │───▶│ Validate │ │
│ └─────────────────┘ └─────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Apply to │ │
│ │ Native Projects│ │
│ └─────────────────┘ │
│ │
└──────────────────────────────────────────────────────────┘
5.2 配置继承 #
typescript
interface CapacitorConfig {
appId: string;
appName: string;
webDir: string;
// 平台特定配置继承基础配置
ios?: IOSConfig;
android?: AndroidConfig;
// 插件配置
plugins?: {
[pluginName: string]: any;
};
}
// 配置合并
const finalConfig = {
...baseConfig,
...platformConfig,
plugins: {
...baseConfig.plugins,
...platformConfig.plugins
}
};
六、事件系统架构 #
6.1 事件流 #
text
Native Event Bridge JavaScript
│ │ │
│ 1. 原生事件触发 │ │
│ ───────────────────────▶│ │
│ │ 2. 转换为JS事件 │
│ │ ───────────────────────▶ │
│ │ │
│ │ │ 3. 触发监听器
│ │ │ ───────────▶
│ │ │
│ │ │ 4. 执行回调
│ │ │ ◀───────────
6.2 事件监听 #
typescript
// 事件监听接口
interface PluginListenerHandle {
remove(): void;
}
// 事件监听实现
class EventEmitter {
private listeners = new Map<string, Set<Function>>();
addEventListener(eventName: string, callback: Function): PluginListenerHandle {
if (!this.listeners.has(eventName)) {
this.listeners.set(eventName, new Set());
}
this.listeners.get(eventName)!.add(callback);
return {
remove: () => {
this.listeners.get(eventName)?.delete(callback);
}
};
}
emit(eventName: string, data: any) {
const callbacks = this.listeners.get(eventName);
callbacks?.forEach(cb => cb(data));
}
}
6.3 原生事件示例 #
typescript
// 监听网络状态变化
import { Network } from '@capacitor/network';
Network.addListener('networkStatusChange', (status) => {
console.log('Network status changed', status);
});
// 监听键盘事件
import { Keyboard } from '@capacitor/keyboard';
Keyboard.addListener('keyboardWillShow', (info) => {
console.log('Keyboard will show', info.keyboardHeight);
});
七、安全架构 #
7.1 安全模型 #
text
┌──────────────────────────────────────────────────────────┐
│ Security Model │
├──────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Application Sandbox │ │
│ │ ┌─────────────────────────────────────────┐ │ │
│ │ │ WebView Sandbox │ │ │
│ │ │ ┌─────────────────────────────────┐ │ │ │
│ │ │ │ JavaScript Runtime │ │ │ │
│ │ │ └─────────────────────────────────┘ │ │ │
│ │ └─────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ Bridge Layer (Controlled Access) │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Plugin Permission System │ │
│ │ - Method Whitelist │ │
│ │ - Parameter Validation │ │
│ │ - Rate Limiting │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ Native Layer (OS Security) │
│ ┌─────────────────────────────────────────────────┐ │
│ │ OS Permission System │ │
│ │ - Runtime Permissions │ │
│ │ - App Sandbox │ │
│ │ - Data Protection │ │
│ └─────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────┘
7.2 权限控制 #
typescript
// 权限检查
interface PermissionStatus {
state: 'granted' | 'denied' | 'prompt';
}
// 插件权限声明
interface PluginPermissions {
ios?: string[]; // iOS权限
android?: string[]; // Android权限
}
// 权限请求
async function requestPermission(permission: string): Promise<PermissionStatus> {
const result = await Capacitor.nativeCallback('Permissions', 'request', {
permission
});
return result;
}
八、性能架构 #
8.1 性能优化策略 #
| 策略 | 说明 |
|---|---|
| 延迟加载 | 按需加载插件 |
| 批量调用 | 合并多个桥接调用 |
| 缓存机制 | 缓存原生数据 |
| 异步执行 | 非阻塞桥接调用 |
8.2 桥接优化 #
typescript
// 批量调用优化
class BatchBridge {
private queue: Array<{
plugin: string;
method: string;
options: any;
resolve: Function;
}> = [];
private flushScheduled = false;
call(plugin: string, method: string, options: any): Promise<any> {
return new Promise(resolve => {
this.queue.push({ plugin, method, options, resolve });
this.scheduleFlush();
});
}
private scheduleFlush() {
if (!this.flushScheduled) {
this.flushScheduled = true;
requestAnimationFrame(() => this.flush());
}
}
private flush() {
const batch = [...this.queue];
this.queue = [];
this.flushScheduled = false;
// 批量发送到原生层
this.sendBatch(batch);
}
}
九、调试架构 #
9.1 调试工具 #
text
┌──────────────────────────────────────────────────────────┐
│ Debug Architecture │
├──────────────────────────────────────────────────────────┤
│ │
│ JavaScript Debug │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Chrome DevTools / Safari Web Inspector │ │
│ │ - Console Logs │ │
│ │ - Network Requests │ │
│ │ - Source Maps │ │
│ │ - Performance Profiling │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ Native Debug │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Xcode Debugger / Android Studio Debugger │ │
│ │ - Breakpoints │ │
│ │ - Native Variables │ │
│ │ - Memory Profiling │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ Bridge Debug │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Capacitor Logger │ │
│ │ - Bridge Calls │ │
│ │ - Plugin Lifecycle │ │
│ │ - Event Flow │ │
│ └─────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────┘
9.2 日志系统 #
typescript
// 日志配置
Capacitor.Logger = {
level: 'debug' | 'info' | 'warn' | 'error',
log(plugin: string, method: string, data: any) {
if (this.shouldLog('debug')) {
console.log(`[${plugin}] ${method}:`, data);
}
}
};
十、总结 #
10.1 架构要点 #
| 层级 | 职责 |
|---|---|
| Web层 | 应用代码运行 |
| 桥接层 | JS与原生通信 |
| 插件层 | 功能扩展 |
| 原生层 | 平台能力提供 |
10.2 核心流程 #
text
Web调用 → 桥接层 → 原生执行 → 返回结果
10.3 下一步 #
了解架构后,让我们深入学习 桥接机制!
最后更新:2026-03-28