跳到主要内容

为 Web/PWA 实现

在设计插件 API 时我们发现,Web 已经支持屏幕方向功能(当然,移动设备除外)。你可能会问:「既然这样,插件的 Web 实现还有什么意义?我们难道不能在代码里判断用户是否在 Web 环境,是的话就直接用 Screen Orientation Web API,否则才用插件吗?」

Web Native 应用的信条是「一次编写,处处运行」。这同样适用于插件;使用 Napacitor 插件的开发者应当能够使用同一个插件类与同一套方法,并在所有平台上都有对应实现。

因此,我们要做一个有责任感的开发者,把 Screen Orientation Web API 封装进 ScreenOrientation 插件的 Web 实现中。

Web 类​

新建文件 src/plugins/screen-orientation/web.ts。我们将在这里编写 ScreenOrientation 插件的 Web 实现。

与 Capacitor 不同,Napacitor 的 Web 实现是一个普通类——没有需要继承的 WebPlugin 基类。该类只需实现插件接口;registerPlugin 的 web 选项会负责把它接上。

首先声明实现 ScreenOrientationPlugin 的 ScreenOrientationWeb 类:

import type { PluginListenerHandle } from '@napacitor/core';
import type {
ScreenOrientationPlugin,
ScreenOrientationResult,
} from './definitions';

export class ScreenOrientationWeb implements ScreenOrientationPlugin {
async orientation(): Promise<ScreenOrientationResult> {
if (typeof screen === 'undefined' || !screen.orientation) {
throw new Error(
'ScreenOrientation API not available in this browser',
);
}
return { type: this.map(screen.orientation.type) };
}

async addListener(
eventName: 'screenOrientationChange',
listenerFunc: (orientation: ScreenOrientationResult) => void,
): Promise<PluginListenerHandle> {
void eventName;
const handler = () =>
listenerFunc({ type: this.map(window.screen.orientation.type) });
window.screen.orientation.addEventListener('change', handler);
return {
remove: async () =>
window.screen.orientation.removeEventListener('change', handler),
};
}

async removeAllListeners(): Promise<void> {
// 监听器通过各自句柄的 remove() 单独移除。
}

private map(type: string): ScreenOrientationResult['type'] {
return type.includes('portrait') ? 'portrait' : 'landscape';
}
}

几点说明:

  • 因为没有基类,Web 实现需要自己管理监听器。addListener 必须返回一个带异步 remove() 方法的句柄;removeAllListeners 只负责该类自身跟踪的状态。
  • @napacitor/core 会在 Web 平台上把 registerPlugin('ScreenOrientation') 解析到该类。
  • 'screenOrientationChange' 事件名必须与 C# 实现发出的事件名一致。

注册 Web 实现​

要把 ScreenOrientationWeb 注册为插件的 Web 实现,我们需要使用 registerPlugin() 的第二个入参。打开 src/plugins/screen-orientation/index.ts,把 ScreenOrientation 变量的声明改为:

const ScreenOrientation = registerPlugin<ScreenOrientationPlugin>(
'ScreenOrientation',
{
web: () =>
import('./web').then(m => new m.ScreenOrientationWeb()),
},
);

试一试!​

测试一下 Web 实现。用 npm run dev 启动应用,然后利用浏览器开发者工具模拟竖屏与横屏两种屏幕方向的移动设备。当你用开发者工具手动旋转方向时,应该能看到不同的设计。

一个平台完成,还剩一个:运行在 MAUI 宿主内、覆盖 Android、iOS、macOS 与 Windows 的 C# 实现。在深入 C# 代码之前,先看一下 C# 插件指南 了解基础知识。