or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

canvas.mdcore-framework.mddevice.mddom-query.mdindex.mdlocation.mdmedia.mdnavigation.mdnetwork.mdstorage.mdsystem-info.mdui-interactions.md
tile.json

tessl/npm-tarojs--taro-h5

H5端API库,为Taro跨端开发框架提供Web/H5端的API实现

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@tarojs/taro-h5@4.1.x

To install, run

npx @tessl/cli install tessl/npm-tarojs--taro-h5@4.1.0

index.mddocs/

Taro H5

Taro 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.

Package Information

  • Package Name: @tarojs/taro-h5
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @tarojs/taro-h5

Core Imports

import 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");

Basic Usage

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}`);

Architecture

Taro H5 is organized around several key architectural components:

  • Core Taro Object: Central API hub providing utilities like pixel transformation, environment detection, and app information
  • Web API Adapters: Browser-compatible implementations of Mini Program APIs using standard web technologies
  • Storage Layer: localStorage-based persistence matching Mini Program storage APIs
  • Network Layer: fetch-based HTTP client with interceptor support
  • UI Components: Browser-based implementations of Mini Program UI interactions
  • Device Abstractions: Web-compatible device capability APIs where possible
  • Routing Integration: @tarojs/router integration for navigation APIs
  • Cross-Platform Stubs: Graceful handling of platform-specific APIs not available in browsers

Capabilities

Core Framework APIs

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;
}

Core Framework

Storage APIs

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;
}

Storage

Network APIs

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[];
}

Network

System Information APIs

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;
}

System Information

UI Interaction APIs

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;
}

UI Interactions

Location Services

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;
}

Location Services

Route Navigation APIs

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;
}

Route Navigation

DOM Query APIs

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;
}

DOM Query

Device APIs

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;
}

Device APIs

Media APIs

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;
}

Media APIs

Canvas APIs

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;
}

Canvas APIs

Implementation Status

✅ Fully Implemented (Web-Compatible)

  • Core Framework APIs: Complete Taro object with utilities
  • Storage APIs: Full localStorage integration
  • Network APIs: Complete fetch-based implementation with download/upload/WebSocket support
  • System Information: Comprehensive browser environment detection
  • UI Interactions: Toast, modal, loading, action sheet
  • Location Services: Geolocation API integration
  • Route Navigation: @tarojs/router integration
  • DOM Query: Web-compatible selector and observer APIs
  • Basic Device APIs: Clipboard access
  • Media APIs: Image selection, preview, information retrieval, and album saving
  • Canvas APIs: Basic 2D graphics and image operations

⚠️ Partially Implemented

  • Advanced Device APIs: Most hardware features not available in browsers
  • Advanced Media APIs: Video/audio processing and platform-specific media features

❌ Not Implemented (Platform Limitations)

  • Mini Program Specific: WeChat, Alipay, Baidu platform APIs
  • Native Features: File system, advanced hardware access, payments
  • Platform Services: Cloud functions, analytics, advertising
  • Advanced Media: Camera, microphone, Bluetooth, NFC

The H5 implementation prioritizes web standards compatibility while providing graceful stubs for platform-specific functionality that cannot be implemented in browser environments.

Types

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>;
};