/** * 平台和环境检测工具 * 统一管理所有平台相关的判断逻辑 */ export enum Platform { ELECTRON = 'electron', CORDOVA = 'cordova', BROWSER = 'browser', UNKNOWN = 'unknown' } export interface PlatformInfo { platform: Platform; isElectron: boolean; isCordova: boolean; isBrowser: boolean; isRenderer: boolean; isMain: boolean; } /** * 环境检测函数 */ const env = { isElectron: () => { // 多个条件检测,确保在不同环境下都能正确识别 return ( // 渲染进程检测 (typeof window !== 'undefined' && typeof window.process === 'object' && (window.process as any).type === 'renderer') || // 主进程检测 (typeof process !== 'undefined' && typeof process.versions === 'object' && !!(process.versions as any).electron) || // User Agent 检测(兜底方案) (typeof navigator !== 'undefined' && navigator.userAgent.toLowerCase().includes('electron')) ); }, isCordova: () => { return typeof window !== 'undefined' && !!window.cordova; }, isAndroid: () => { if (env.isCordova()) { // Cordova 环境使用 device.platform return typeof device !== 'undefined' && device.platform === 'Android'; } // 浏览器环境使用 navigator.userAgent return typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent); }, isIOS: () => { if (env.isCordova()) { // Cordova 环境使用 device.platform return typeof device !== 'undefined' && /iOS/i.test(device.platform); } // 浏览器环境使用 navigator.userAgent return typeof navigator !== 'undefined' && /iPhone|iPad|iPod/i.test(navigator.userAgent); }, isBrowser: () => { return !env.isElectron() && !env.isCordova(); } }; /** * 获取当前平台信息 */ export function getPlatformInfo(): PlatformInfo { const isElectron = env.isElectron(); const isCordova = env.isCordova(); const isBrowser = env.isBrowser(); // 主进程/渲染进程检测(Electron) const isRenderer = isElectron && typeof window !== 'undefined' && typeof window.process === 'object' && (window.process as any).type === 'renderer'; const isMain = typeof process !== 'undefined' && (process as any).type === 'browser'; // 确定主要平台 let platform: Platform; if (isElectron) { platform = Platform.ELECTRON; } else if (isCordova) { platform = Platform.CORDOVA; } else if (isBrowser) { platform = Platform.BROWSER; } else { platform = Platform.UNKNOWN; } return { platform, isElectron, isCordova, isBrowser, isRenderer, isMain }; } /** * 便捷的平台检测函数 * 导出一个单例,避免重复计算 */ export const platform = getPlatformInfo(); /** * 导出环境检测函数,供其他地方使用 */ export const { isElectron, isCordova, isAndroid, isIOS, isBrowser } = env; /** * 是否支持持久化存储 * Electron 和 Cordova 支持文件系统存储,浏览器不支持 */ export function supportsPersistentStorage(): boolean { return platform.isElectron || platform.isCordova; } /** * 是否支持动态配置 * 所有平台都支持动态配置,但存储方式不同 */ export function supportsDynamicConfig(): boolean { return true; // 所有平台都支持 } /** * 获取平台名称(用于显示) */ export function getPlatformDisplayName(): string { switch (platform.platform) { case Platform.ELECTRON: return 'Electron 桌面应用'; case Platform.CORDOVA: return 'Cordova 移动应用'; case Platform.BROWSER: return '浏览器'; default: return '未知平台'; } }