H5端API库,为Taro跨端开发框架提供Web/H5端的API实现
—
Browser-based system and device information APIs providing comprehensive environment details including device characteristics, window dimensions, and platform information.
Comprehensive system and device information retrieval with both synchronous and asynchronous access patterns.
/**
* Get complete system information synchronously
* @returns Comprehensive system information object
*/
function getSystemInfoSync(): SystemInfo;
/**
* Get complete system information asynchronously
* @param options - Optional callback configuration
* @returns Promise resolving to system information
*/
function getSystemInfoAsync(options?: CallbackOptions): Promise<SystemInfo>;
/**
* Get complete system information (legacy async method)
* @param options - Optional callback configuration
* @returns Promise resolving to system information
*/
function getSystemInfo(options?: CallbackOptions): Promise<SystemInfo>;
interface SystemInfo {
/** Device brand identifier */
brand: string;
/** Device model name */
model: string;
/** Operating system with version */
system: string;
/** System language setting */
language: string;
/** Taro framework version */
version: string;
/** Platform identifier (always 'web' for H5) */
platform: string;
/** Font size setting multiplier */
fontSizeSetting: number;
/** Taro SDK version */
SDKVersion: string;
/** Device pixel ratio */
pixelRatio: number;
/** Window width in pixels */
windowWidth: number;
/** Window height in pixels */
windowHeight: number;
/** Screen width in pixels */
screenWidth: number;
/** Screen height in pixels */
screenHeight: number;
/** Safe area coordinates */
safeArea: SafeAreaResult;
/** Status bar height in pixels */
statusBarHeight: number;
/** Screen top safe area inset */
safeAreaInsets?: SafeAreaInsets;
/** Device orientation */
deviceOrientation?: 'portrait' | 'landscape';
/** Additional platform-specific properties */
[key: string]: any;
}
interface SafeAreaResult {
/** Left safe area boundary */
left: number;
/** Right safe area boundary */
right: number;
/** Top safe area boundary */
top: number;
/** Bottom safe area boundary */
bottom: number;
/** Safe area width */
width: number;
/** Safe area height */
height: number;
}
interface SafeAreaInsets {
/** Top inset in pixels */
top: number;
/** Right inset in pixels */
right: number;
/** Bottom inset in pixels */
bottom: number;
/** Left inset in pixels */
left: number;
}Usage Examples:
import { getSystemInfoSync, getSystemInfo } from "@tarojs/taro-h5";
// Synchronous system info
const systemInfo = getSystemInfoSync();
console.log(`Platform: ${systemInfo.platform}`);
console.log(`Screen: ${systemInfo.screenWidth}x${systemInfo.screenHeight}`);
console.log(`Window: ${systemInfo.windowWidth}x${systemInfo.windowHeight}`);
console.log(`Pixel Ratio: ${systemInfo.pixelRatio}`);
console.log(`Language: ${systemInfo.language}`);
console.log(`System: ${systemInfo.system}`);
// Responsive design based on screen size
if (systemInfo.windowWidth < 768) {
console.log('Mobile layout');
} else if (systemInfo.windowWidth < 1024) {
console.log('Tablet layout');
} else {
console.log('Desktop layout');
}
// Asynchronous system info
const asyncSystemInfo = await getSystemInfo();
console.log('Async system info:', asyncSystemInfo);
// With callbacks
getSystemInfo({
success: (info) => {
console.log('System info loaded:', info.platform);
},
fail: (error) => {
console.error('Failed to get system info:', error);
}
});Specific window and viewport information for layout calculations.
/**
* Get window-specific information
* @returns Window dimensions and properties
*/
function getWindowInfo(): WindowInfo;
interface WindowInfo {
/** Device pixel ratio */
pixelRatio: number;
/** Screen width in pixels */
screenWidth: number;
/** Screen height in pixels */
screenHeight: number;
/** Window width in pixels */
windowWidth: number;
/** Window height in pixels */
windowHeight: number;
/** Status bar height in pixels */
statusBarHeight: number;
/** Safe area coordinates */
safeArea: SafeAreaResult;
/** Screen top position */
screenTop: number;
}Hardware and device-specific information.
/**
* Get device-specific information
* @returns Device characteristics and capabilities
*/
function getDeviceInfo(): DeviceInfo;
interface DeviceInfo {
/** Device brand (detected from user agent) */
brand: string;
/** Device model (detected from user agent) */
model: string;
/** Operating system name and version */
system: string;
/** Device platform identifier */
platform: string;
/** CPU architecture (when available) */
CPUType?: string;
/** Memory information (when available) */
memorySize?: number;
/** Device identifier (browser-generated) */
deviceId?: string;
/** Device orientation capability */
deviceOrientation: string;
/** Device type classification */
deviceType: 'phone' | 'tablet' | 'desktop' | 'unknown';
/** Benchmark performance score (estimated) */
benchmarkLevel?: number;
}Application-specific metadata and configuration details.
/**
* Get application base information
* @returns Application metadata and version details
*/
function getAppBaseInfo(): AppBaseInfo;
interface AppBaseInfo {
/** Taro SDK version */
SDKVersion: string;
/** Application version (from package.json) */
version: string;
/** Enable debug mode flag */
enableDebug: boolean;
/** Host application name */
host: string;
/** Application language setting */
language: string;
/** Theme setting ('light' or 'dark') */
theme: 'light' | 'dark' | 'auto';
/** Application identifier */
appId?: string;
/** Launch scene identifier */
scene?: number;
}Application permission and authorization information.
/**
* Get application authorization settings
* @returns Current permission states for various capabilities
*/
function getAppAuthorizeSetting(): AppAuthorizeSetting;
interface AppAuthorizeSetting {
/** Location access permission */
'scope.userLocation': boolean;
/** Camera access permission */
'scope.camera': boolean;
/** Microphone access permission */
'scope.record': boolean;
/** Photo album access permission */
'scope.writePhotosAlbum': boolean;
/** Address book access permission */
'scope.addressBook': boolean;
/** Invoice access permission */
'scope.invoiceTitle': boolean;
/** Notification permission */
'scope.notification': boolean;
/** Clipboard access permission */
'scope.clipboard': boolean;
/** Additional permissions */
[key: string]: boolean;
}Usage Examples:
import {
getWindowInfo,
getDeviceInfo,
getAppBaseInfo,
getAppAuthorizeSetting
} from "@tarojs/taro-h5";
// Window information for responsive design
const windowInfo = getWindowInfo();
const isLandscape = windowInfo.windowWidth > windowInfo.windowHeight;
const isMobile = windowInfo.windowWidth < 768;
console.log(`Orientation: ${isLandscape ? 'landscape' : 'portrait'}`);
console.log(`Device type: ${isMobile ? 'mobile' : 'desktop'}`);
// Safe area handling for notched devices
const safeAreaPadding = {
top: windowInfo.safeArea.top,
bottom: windowInfo.screenHeight - windowInfo.safeArea.bottom,
left: windowInfo.safeArea.left,
right: windowInfo.screenWidth - windowInfo.safeArea.right
};
// Device information for feature detection
const deviceInfo = getDeviceInfo();
console.log(`Device: ${deviceInfo.brand} ${deviceInfo.model}`);
console.log(`System: ${deviceInfo.system}`);
console.log(`Type: ${deviceInfo.deviceType}`);
// Adaptive features based on device capabilities
if (deviceInfo.deviceType === 'phone' && deviceInfo.memorySize && deviceInfo.memorySize < 4) {
console.log('Low-memory device, enabling performance optimizations');
}
// Application information
const appInfo = getAppBaseInfo();
console.log(`App Version: ${appInfo.version}`);
console.log(`SDK Version: ${appInfo.SDKVersion}`);
console.log(`Theme: ${appInfo.theme}`);
console.log(`Language: ${appInfo.language}`);
// Permission checking
const authSettings = getAppAuthorizeSetting();
if (authSettings['scope.userLocation']) {
console.log('Location permission granted');
} else {
console.log('Location permission not granted');
}
if (authSettings['scope.camera']) {
console.log('Camera access available');
}Complex scenarios and best practices for system information usage.
// Responsive breakpoint system
class ResponsiveBreakpoints {
private windowInfo: WindowInfo;
constructor() {
this.windowInfo = getWindowInfo();
}
get isMobile(): boolean {
return this.windowInfo.windowWidth < 768;
}
get isTablet(): boolean {
return this.windowInfo.windowWidth >= 768 && this.windowInfo.windowWidth < 1024;
}
get isDesktop(): boolean {
return this.windowInfo.windowWidth >= 1024;
}
get orientation(): 'portrait' | 'landscape' {
return this.windowInfo.windowWidth > this.windowInfo.windowHeight
? 'landscape' : 'portrait';
}
// Update on window resize
update(): void {
this.windowInfo = getWindowInfo();
}
}
// Device capability detection
class DeviceCapabilities {
private deviceInfo: DeviceInfo;
private systemInfo: SystemInfo;
constructor() {
this.deviceInfo = getDeviceInfo();
this.systemInfo = getSystemInfoSync();
}
get isHighDPI(): boolean {
return this.systemInfo.pixelRatio >= 2;
}
get isRetina(): boolean {
return this.systemInfo.pixelRatio >= 3;
}
get isLowEndDevice(): boolean {
return this.deviceInfo.benchmarkLevel !== undefined &&
this.deviceInfo.benchmarkLevel < 30;
}
get supportsTouchEvents(): boolean {
return 'ontouchstart' in window;
}
get supportsWebGL(): boolean {
try {
const canvas = document.createElement('canvas');
return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
} catch {
return false;
}
}
getOptimalImageQuality(): 'low' | 'medium' | 'high' {
if (this.isLowEndDevice) return 'low';
if (this.isHighDPI) return 'high';
return 'medium';
}
}
// Safe area layout helper
class SafeAreaLayout {
private windowInfo: WindowInfo;
constructor() {
this.windowInfo = getWindowInfo();
}
getSafeAreaCSS(): Record<string, string> {
const { safeArea, screenWidth, screenHeight } = this.windowInfo;
return {
paddingTop: `${safeArea.top}px`,
paddingBottom: `${screenHeight - safeArea.bottom}px`,
paddingLeft: `${safeArea.left}px`,
paddingRight: `${screenWidth - safeArea.right}px`
};
}
getSafeAreaInsets(): SafeAreaInsets {
const { safeArea, screenWidth, screenHeight } = this.windowInfo;
return {
top: safeArea.top,
bottom: screenHeight - safeArea.bottom,
left: safeArea.left,
right: screenWidth - safeArea.right
};
}
hasNotch(): boolean {
const insets = this.getSafeAreaInsets();
return insets.top > 20 || insets.bottom > 0 || insets.left > 0 || insets.right > 0;
}
}
// Usage examples
const breakpoints = new ResponsiveBreakpoints();
const capabilities = new DeviceCapabilities();
const safeArea = new SafeAreaLayout();
// Apply responsive styles
if (breakpoints.isMobile) {
document.body.className += ' mobile-layout';
}
// Optimize based on device capabilities
const imageQuality = capabilities.getOptimalImageQuality();
console.log(`Using ${imageQuality} quality images`);
// Handle safe areas
if (safeArea.hasNotch()) {
const safeAreaCSS = safeArea.getSafeAreaCSS();
Object.assign(document.body.style, safeAreaCSS);
}
// Listen for orientation changes
window.addEventListener('resize', () => {
breakpoints.update();
console.log(`New orientation: ${breakpoints.orientation}`);
});Efficient caching patterns for system information that rarely changes.
class SystemInfoCache {
private static instance: SystemInfoCache;
private cache: Map<string, { data: any, timestamp: number }> = new Map();
private readonly TTL = 60000; // 1 minute TTL
static getInstance(): SystemInfoCache {
if (!SystemInfoCache.instance) {
SystemInfoCache.instance = new SystemInfoCache();
}
return SystemInfoCache.instance;
}
getSystemInfo(): SystemInfo {
const cached = this.cache.get('systemInfo');
if (cached && Date.now() - cached.timestamp < this.TTL) {
return cached.data;
}
const systemInfo = getSystemInfoSync();
this.cache.set('systemInfo', {
data: systemInfo,
timestamp: Date.now()
});
return systemInfo;
}
getDeviceInfo(): DeviceInfo {
const cached = this.cache.get('deviceInfo');
if (cached && Date.now() - cached.timestamp < this.TTL) {
return cached.data;
}
const deviceInfo = getDeviceInfo();
this.cache.set('deviceInfo', {
data: deviceInfo,
timestamp: Date.now()
});
return deviceInfo;
}
clearCache(): void {
this.cache.clear();
}
}
// Usage
const systemCache = SystemInfoCache.getInstance();
const systemInfo = systemCache.getSystemInfo(); // Cached after first call
const deviceInfo = systemCache.getDeviceInfo(); // Cached after first callinterface CallbackOptions {
success?: (res: any) => void;
fail?: (err: any) => void;
complete?: (res: any) => void;
}
type DeviceType = 'phone' | 'tablet' | 'desktop' | 'unknown';
type ThemeSetting = 'light' | 'dark' | 'auto';
type DeviceOrientation = 'portrait' | 'landscape';
type PermissionScope =
| 'scope.userLocation'
| 'scope.camera'
| 'scope.record'
| 'scope.writePhotosAlbum'
| 'scope.addressBook'
| 'scope.invoiceTitle'
| 'scope.notification'
| 'scope.clipboard';Install with Tessl CLI
npx tessl i tessl/npm-tarojs--taro-h5