H5端API库,为Taro跨端开发框架提供Web/H5端的API实现
npx @tessl/cli install tessl/npm-tarojs--taro-h5@4.1.0Taro H5 is the Web/H5 implementation layer of the Taro cross-platform development framework, providing browser-compatible APIs that mirror WeChat Mini Program APIs. It serves as the runtime layer that enables Taro applications to run in web browsers by implementing Mini Program APIs using web standards like DOM, fetch, and localStorage.
npm install @tarojs/taro-h5import Taro from "@tarojs/taro-h5";For specific API imports:
import { request, getStorageSync, showToast } from "@tarojs/taro-h5";For CommonJS:
const Taro = require("@tarojs/taro-h5");
const { request, getStorageSync, showToast } = require("@tarojs/taro-h5");import Taro from "@tarojs/taro-h5";
// Storage operations
Taro.setStorageSync('user', { name: 'Alice', age: 25 });
const user = Taro.getStorageSync('user');
// Network requests
const response = await Taro.request({
url: 'https://api.example.com/data',
method: 'GET',
header: { 'Content-Type': 'application/json' }
});
// UI interactions
await Taro.showToast({
title: 'Success!',
icon: 'success',
duration: 2000
});
// Location services
const location = await Taro.getLocation({
type: 'wgs84'
});
// System information
const systemInfo = Taro.getSystemInfoSync();
console.log(`Platform: ${systemInfo.platform}, Width: ${systemInfo.windowWidth}`);Taro H5 is organized around several key architectural components:
Essential framework utilities including the main Taro object, app lifecycle management, and system utilities.
// Main Taro object with core utilities
interface TaroCore {
// Pixel transformation
pxTransform(size: number): string;
initPxTransform(config: PxTransformConfig): void;
// App information
getAppInfo(): AppInfo;
canIUseWebp(): boolean;
// Environment and lifecycle
getEnv(): string;
getCurrentInstance(): ComponentInstance;
getApp<T>(): T;
getCurrentPages(): PageInstance[];
}
interface PxTransformConfig {
designWidth?: number;
deviceRatio?: Record<number, number>;
baseFontSize?: number;
unitPrecision?: number;
targetUnit?: string;
}
interface AppInfo {
platform: string;
taroVersion: string;
designWidth: number;
}Complete localStorage-based storage system compatible with Mini Program storage APIs, supporting both synchronous and asynchronous operations.
// Synchronous storage operations
function setStorageSync(key: string, data: any): void;
function getStorageSync(key: string): any;
function removeStorageSync(key: string): void;
function clearStorageSync(): void;
function getStorageInfoSync(): StorageInfo;
// Asynchronous storage operations
function setStorage(options: SetStorageOption): Promise<void>;
function getStorage<T>(options: GetStorageOption): Promise<T>;
function removeStorage(options: RemoveStorageOption): Promise<void>;
function clearStorage(options?: CallbackOptions): Promise<void>;
function getStorageInfo(options?: CallbackOptions): Promise<StorageInfo>;
interface StorageInfo {
keys: string[];
currentSize: number;
limitSize: number;
}Comprehensive networking capabilities including HTTP requests with interceptor support, designed for web environments.
function request(options: RequestOption): Promise<RequestResult>;
function addInterceptor(interceptor: Interceptor): void;
function cleanInterceptors(): void;
interface RequestOption {
url: string;
data?: any;
header?: Record<string, string>;
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
dataType?: string;
responseType?: 'text' | 'json' | 'arraybuffer';
timeout?: number;
enableHttp2?: boolean;
enableQuic?: boolean;
enableCache?: boolean;
}
interface RequestResult {
data: any;
statusCode: number;
header: Record<string, string>;
cookies?: string[];
}Browser-based system and device information APIs providing comprehensive environment details.
function getSystemInfoSync(): SystemInfo;
function getSystemInfoAsync(options?: CallbackOptions): Promise<SystemInfo>;
function getSystemInfo(options?: CallbackOptions): Promise<SystemInfo>;
function getWindowInfo(): WindowInfo;
function getDeviceInfo(): DeviceInfo;
function getAppBaseInfo(): AppBaseInfo;
interface SystemInfo {
brand: string;
model: string;
system: string;
language: string;
version: string;
platform: string;
fontSizeSetting: number;
SDKVersion: string;
pixelRatio: number;
windowWidth: number;
windowHeight: number;
screenWidth: number;
screenHeight: number;
safeArea: SafeAreaResult;
}Browser-based user interface interaction APIs including toast messages, modals, loading indicators, and action sheets.
function showToast(options: ToastOption): Promise<void>;
function hideToast(options?: CallbackOptions): Promise<void>;
function showLoading(options: LoadingOption): Promise<void>;
function hideLoading(options?: CallbackOptions): Promise<void>;
function showModal(options: ModalOption): Promise<ModalResult>;
function showActionSheet(options: ActionSheetOption): Promise<ActionSheetResult>;
interface ToastOption {
title: string;
icon?: 'success' | 'error' | 'loading' | 'none';
image?: string;
duration?: number;
mask?: boolean;
}
interface ModalOption {
title?: string;
content?: string;
showCancel?: boolean;
cancelText?: string;
cancelColor?: string;
confirmText?: string;
confirmColor?: string;
}Geolocation API integration providing location access and monitoring capabilities for web environments.
function getLocation(options: LocationOption): Promise<LocationResult>;
function chooseLocation(options: ChooseLocationOption): Promise<LocationResult>;
function openLocation(options: OpenLocationOption): Promise<void>;
function onLocationChange(callback: LocationChangeCallback): void;
function offLocationChange(callback: LocationChangeCallback): void;
function startLocationUpdate(options?: LocationUpdateOption): Promise<void>;
function stopLocationUpdate(): Promise<void>;
interface LocationOption {
type?: 'wgs84' | 'gcj02';
altitude?: boolean;
isHighAccuracy?: boolean;
highAccuracyExpireTime?: number;
}
interface LocationResult {
latitude: number;
longitude: number;
speed: number;
accuracy: number;
altitude: number;
verticalAccuracy: number;
horizontalAccuracy: number;
}Page navigation and routing capabilities integrated with @tarojs/router for single-page application navigation.
function navigateTo(options: NavigateOption): Promise<void>;
function redirectTo(options: RedirectOption): Promise<void>;
function navigateBack(options?: NavigateBackOption): Promise<void>;
function switchTab(options: SwitchTabOption): Promise<void>;
function reLaunch(options: ReLaunchOption): Promise<void>;
interface NavigateOption {
url: string;
events?: Record<string, Function>;
}
interface NavigateBackOption {
delta?: number;
}Web-compatible DOM querying and observation APIs for component interaction and layout management.
function createSelectorQuery(): SelectorQuery;
function createIntersectionObserver(
component?: any,
options?: IntersectionObserverInit
): IntersectionObserver;
function createMediaQueryObserver(): MediaQueryObserver;
interface SelectorQuery {
select(selector: string): NodesRef;
selectAll(selector: string): NodesRef;
selectViewport(): NodesRef;
exec(callback?: (res: any[]) => void): void;
}Limited device capability APIs focusing on web-compatible features like clipboard access.
function setClipboardData(options: ClipboardDataOption): Promise<void>;
function getClipboardData(options?: CallbackOptions): Promise<ClipboardDataResult>;
interface ClipboardDataOption {
data: string;
}
interface ClipboardDataResult {
data: string;
}Comprehensive media handling capabilities including image selection, preview, and photo album integration.
function chooseImage(options: ChooseImageOption): Promise<ChooseImageResult>;
function previewImage(options: PreviewImageOption): Promise<void>;
function getImageInfo(options: GetImageInfoOption): Promise<ImageInfoResult>;
function saveImageToPhotosAlbum(options: SaveImageOption): Promise<void>;
interface ChooseImageOption {
count?: number;
sizeType?: ('original' | 'compressed')[];
sourceType?: ('album' | 'camera' | 'user')[];
}
interface ImageInfoResult {
width: number;
height: number;
path: string;
}HTML5 Canvas integration providing 2D graphics capabilities and image manipulation with Mini Program compatibility.
function createCanvasContext(canvasId: string, componentInstance?: any): CanvasContext;
function canvasToTempFilePath(options: CanvasToTempFilePathOption): Promise<CanvasToTempFilePathResult>;
function canvasGetImageData(options: CanvasGetImageDataOption): Promise<CanvasGetImageDataResult>;
function canvasPutImageData(options: CanvasPutImageDataOption): Promise<void>;
interface CanvasContext {
fillRect(x: number, y: number, width: number, height: number): void;
strokeRect(x: number, y: number, width: number, height: number): void;
beginPath(): void;
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number): void;
setFillStyle(color: string): void;
fillText(text: string, x: number, y: number): void;
drawImage(imageResource: string, x: number, y: number): void;
draw(reserve?: boolean, callback?: () => void): void;
}The H5 implementation prioritizes web standards compatibility while providing graceful stubs for platform-specific functionality that cannot be implemented in browser environments.
interface CallbackOptions {
success?: (res: any) => void;
fail?: (err: any) => void;
complete?: (res: any) => void;
}
interface ComponentInstance {
page?: any;
router?: {
params: Record<string, string>;
path: string;
};
scope?: any;
[key: string]: any;
}
interface PageInstance {
route: string;
options: Record<string, string>;
[key: string]: any;
}
interface SafeAreaResult {
left: number;
right: number;
top: number;
bottom: number;
width: number;
height: number;
}
// Environment types
declare const ENV_TYPE: {
WEAPP: 'WEAPP';
WEB: 'WEB';
RN: 'RN';
SWAN: 'SWAN';
ALIPAY: 'ALIPAY';
TT: 'TT';
QQ: 'QQ';
JD: 'JD';
};
type TaroGeneral = {
TDeviceRatio: Record<number, number>;
};