跳到主要内容

Web/PWA 插件指南

Napacitor 提供了 Web/原生兼容层,因此很容易构建既能以原生方式运行、也能在浏览器中运行的插件。Web 实现就是一个实现你插件接口的普通类——无需继承任何基类。

Web 实现​

src/web.ts:

import type { EchoPlugin } from './definitions';

export class EchoWeb implements EchoPlugin {
async echo(options: { value: string }) {
console.log('ECHO', options);
return options;
}
}

src/index.ts 通过 registerPlugin 的 web 选项接入该类(动态 import 可让 Web 代码不进入原生包):

import { registerPlugin } from '@napacitor/core';
import type { EchoPlugin } from './definitions';

const Echo = registerPlugin<EchoPlugin>('Echo', {
web: () => import('./web').then((m) => new m.EchoWeb()),
});

export * from './definitions';
export { Echo };

当应用运行在浏览器中时,Echo.echo(...) 会分发到 EchoWeb;在 MAUI 宿主中,则会跨桥接层调用你的 C# 实现。

调用其他 Web API​

对于仅浏览器可用的功能,请直接在 EchoWeb 中使用标准 Web API 实现(Battery Status、Screen Orientation、Clipboard 等)。例如 Battery 插件的 Web 实现封装了 navigator.getBattery(),并在该 API 缺失时以一个普通的 Error 拒绝。

仅原生可用的方法​

如果某个方法没有有意义的 Web 实现,请不要在 Web 类中定义它——或者直接抛出异常。到达原生桥接层却找不到实现的调用,会以一个错误码为 NOT_IMPLEMENTED 的 NapacitorException 拒绝。应用可以通过 Napacitor.isPluginAvailable() 或 try/catch 做防护(参见 Web API 参考)。

权限​

如果你的插件需要浏览器权限,请在 EchoWeb 中使用标准 Web 权限流程(navigator.permissions、navigator.geolocation 等)。Napacitor 核心并不提供自己的权限抽象;请把权限 API 放在接口上,以便原生侧与 Web 侧保持同步:

export interface PermissionStatus {
location: 'prompt' | 'granted' | 'denied';
}

export interface EchoPlugin {
checkPermissions(): Promise<PermissionStatus>;
requestPermissions(): Promise<PermissionStatus>;
}