or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Taro H5

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: @tarojs/taro-h5

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @tarojs/taro-h5`

10

11

## Core Imports

12

13

```typescript

14

import Taro from "@tarojs/taro-h5";

15

```

16

17

For specific API imports:

18

19

```typescript

20

import { request, getStorageSync, showToast } from "@tarojs/taro-h5";

21

```

22

23

For CommonJS:

24

25

```javascript

26

const Taro = require("@tarojs/taro-h5");

27

const { request, getStorageSync, showToast } = require("@tarojs/taro-h5");

28

```

29

30

## Basic Usage

31

32

```typescript

33

import Taro from "@tarojs/taro-h5";

34

35

// Storage operations

36

Taro.setStorageSync('user', { name: 'Alice', age: 25 });

37

const user = Taro.getStorageSync('user');

38

39

// Network requests

40

const response = await Taro.request({

41

url: 'https://api.example.com/data',

42

method: 'GET',

43

header: { 'Content-Type': 'application/json' }

44

});

45

46

// UI interactions

47

await Taro.showToast({

48

title: 'Success!',

49

icon: 'success',

50

duration: 2000

51

});

52

53

// Location services

54

const location = await Taro.getLocation({

55

type: 'wgs84'

56

});

57

58

// System information

59

const systemInfo = Taro.getSystemInfoSync();

60

console.log(`Platform: ${systemInfo.platform}, Width: ${systemInfo.windowWidth}`);

61

```

62

63

## Architecture

64

65

Taro H5 is organized around several key architectural components:

66

67

- **Core Taro Object**: Central API hub providing utilities like pixel transformation, environment detection, and app information

68

- **Web API Adapters**: Browser-compatible implementations of Mini Program APIs using standard web technologies

69

- **Storage Layer**: localStorage-based persistence matching Mini Program storage APIs

70

- **Network Layer**: fetch-based HTTP client with interceptor support

71

- **UI Components**: Browser-based implementations of Mini Program UI interactions

72

- **Device Abstractions**: Web-compatible device capability APIs where possible

73

- **Routing Integration**: @tarojs/router integration for navigation APIs

74

- **Cross-Platform Stubs**: Graceful handling of platform-specific APIs not available in browsers

75

76

## Capabilities

77

78

### Core Framework APIs

79

80

Essential framework utilities including the main Taro object, app lifecycle management, and system utilities.

81

82

```typescript { .api }

83

// Main Taro object with core utilities

84

interface TaroCore {

85

// Pixel transformation

86

pxTransform(size: number): string;

87

initPxTransform(config: PxTransformConfig): void;

88

89

// App information

90

getAppInfo(): AppInfo;

91

canIUseWebp(): boolean;

92

93

// Environment and lifecycle

94

getEnv(): string;

95

getCurrentInstance(): ComponentInstance;

96

getApp<T>(): T;

97

getCurrentPages(): PageInstance[];

98

}

99

100

interface PxTransformConfig {

101

designWidth?: number;

102

deviceRatio?: Record<number, number>;

103

baseFontSize?: number;

104

unitPrecision?: number;

105

targetUnit?: string;

106

}

107

108

interface AppInfo {

109

platform: string;

110

taroVersion: string;

111

designWidth: number;

112

}

113

```

114

115

[Core Framework](./core-framework.md)

116

117

### Storage APIs

118

119

Complete localStorage-based storage system compatible with Mini Program storage APIs, supporting both synchronous and asynchronous operations.

120

121

```typescript { .api }

122

// Synchronous storage operations

123

function setStorageSync(key: string, data: any): void;

124

function getStorageSync(key: string): any;

125

function removeStorageSync(key: string): void;

126

function clearStorageSync(): void;

127

function getStorageInfoSync(): StorageInfo;

128

129

// Asynchronous storage operations

130

function setStorage(options: SetStorageOption): Promise<void>;

131

function getStorage<T>(options: GetStorageOption): Promise<T>;

132

function removeStorage(options: RemoveStorageOption): Promise<void>;

133

function clearStorage(options?: CallbackOptions): Promise<void>;

134

function getStorageInfo(options?: CallbackOptions): Promise<StorageInfo>;

135

136

interface StorageInfo {

137

keys: string[];

138

currentSize: number;

139

limitSize: number;

140

}

141

```

142

143

[Storage](./storage.md)

144

145

### Network APIs

146

147

Comprehensive networking capabilities including HTTP requests with interceptor support, designed for web environments.

148

149

```typescript { .api }

150

function request(options: RequestOption): Promise<RequestResult>;

151

function addInterceptor(interceptor: Interceptor): void;

152

function cleanInterceptors(): void;

153

154

interface RequestOption {

155

url: string;

156

data?: any;

157

header?: Record<string, string>;

158

method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';

159

dataType?: string;

160

responseType?: 'text' | 'json' | 'arraybuffer';

161

timeout?: number;

162

enableHttp2?: boolean;

163

enableQuic?: boolean;

164

enableCache?: boolean;

165

}

166

167

interface RequestResult {

168

data: any;

169

statusCode: number;

170

header: Record<string, string>;

171

cookies?: string[];

172

}

173

```

174

175

[Network](./network.md)

176

177

### System Information APIs

178

179

Browser-based system and device information APIs providing comprehensive environment details.

180

181

```typescript { .api }

182

function getSystemInfoSync(): SystemInfo;

183

function getSystemInfoAsync(options?: CallbackOptions): Promise<SystemInfo>;

184

function getSystemInfo(options?: CallbackOptions): Promise<SystemInfo>;

185

function getWindowInfo(): WindowInfo;

186

function getDeviceInfo(): DeviceInfo;

187

function getAppBaseInfo(): AppBaseInfo;

188

189

interface SystemInfo {

190

brand: string;

191

model: string;

192

system: string;

193

language: string;

194

version: string;

195

platform: string;

196

fontSizeSetting: number;

197

SDKVersion: string;

198

pixelRatio: number;

199

windowWidth: number;

200

windowHeight: number;

201

screenWidth: number;

202

screenHeight: number;

203

safeArea: SafeAreaResult;

204

}

205

```

206

207

[System Information](./system-info.md)

208

209

### UI Interaction APIs

210

211

Browser-based user interface interaction APIs including toast messages, modals, loading indicators, and action sheets.

212

213

```typescript { .api }

214

function showToast(options: ToastOption): Promise<void>;

215

function hideToast(options?: CallbackOptions): Promise<void>;

216

function showLoading(options: LoadingOption): Promise<void>;

217

function hideLoading(options?: CallbackOptions): Promise<void>;

218

function showModal(options: ModalOption): Promise<ModalResult>;

219

function showActionSheet(options: ActionSheetOption): Promise<ActionSheetResult>;

220

221

interface ToastOption {

222

title: string;

223

icon?: 'success' | 'error' | 'loading' | 'none';

224

image?: string;

225

duration?: number;

226

mask?: boolean;

227

}

228

229

interface ModalOption {

230

title?: string;

231

content?: string;

232

showCancel?: boolean;

233

cancelText?: string;

234

cancelColor?: string;

235

confirmText?: string;

236

confirmColor?: string;

237

}

238

```

239

240

[UI Interactions](./ui-interactions.md)

241

242

### Location Services

243

244

Geolocation API integration providing location access and monitoring capabilities for web environments.

245

246

```typescript { .api }

247

function getLocation(options: LocationOption): Promise<LocationResult>;

248

function chooseLocation(options: ChooseLocationOption): Promise<LocationResult>;

249

function openLocation(options: OpenLocationOption): Promise<void>;

250

function onLocationChange(callback: LocationChangeCallback): void;

251

function offLocationChange(callback: LocationChangeCallback): void;

252

function startLocationUpdate(options?: LocationUpdateOption): Promise<void>;

253

function stopLocationUpdate(): Promise<void>;

254

255

interface LocationOption {

256

type?: 'wgs84' | 'gcj02';

257

altitude?: boolean;

258

isHighAccuracy?: boolean;

259

highAccuracyExpireTime?: number;

260

}

261

262

interface LocationResult {

263

latitude: number;

264

longitude: number;

265

speed: number;

266

accuracy: number;

267

altitude: number;

268

verticalAccuracy: number;

269

horizontalAccuracy: number;

270

}

271

```

272

273

[Location Services](./location.md)

274

275

### Route Navigation APIs

276

277

Page navigation and routing capabilities integrated with @tarojs/router for single-page application navigation.

278

279

```typescript { .api }

280

function navigateTo(options: NavigateOption): Promise<void>;

281

function redirectTo(options: RedirectOption): Promise<void>;

282

function navigateBack(options?: NavigateBackOption): Promise<void>;

283

function switchTab(options: SwitchTabOption): Promise<void>;

284

function reLaunch(options: ReLaunchOption): Promise<void>;

285

286

interface NavigateOption {

287

url: string;

288

events?: Record<string, Function>;

289

}

290

291

interface NavigateBackOption {

292

delta?: number;

293

}

294

```

295

296

[Route Navigation](./navigation.md)

297

298

### DOM Query APIs

299

300

Web-compatible DOM querying and observation APIs for component interaction and layout management.

301

302

```typescript { .api }

303

function createSelectorQuery(): SelectorQuery;

304

function createIntersectionObserver(

305

component?: any,

306

options?: IntersectionObserverInit

307

): IntersectionObserver;

308

function createMediaQueryObserver(): MediaQueryObserver;

309

310

interface SelectorQuery {

311

select(selector: string): NodesRef;

312

selectAll(selector: string): NodesRef;

313

selectViewport(): NodesRef;

314

exec(callback?: (res: any[]) => void): void;

315

}

316

```

317

318

[DOM Query](./dom-query.md)

319

320

### Device APIs

321

322

Limited device capability APIs focusing on web-compatible features like clipboard access.

323

324

```typescript { .api }

325

function setClipboardData(options: ClipboardDataOption): Promise<void>;

326

function getClipboardData(options?: CallbackOptions): Promise<ClipboardDataResult>;

327

328

interface ClipboardDataOption {

329

data: string;

330

}

331

332

interface ClipboardDataResult {

333

data: string;

334

}

335

```

336

337

[Device APIs](./device.md)

338

339

### Media APIs

340

341

Comprehensive media handling capabilities including image selection, preview, and photo album integration.

342

343

```typescript { .api }

344

function chooseImage(options: ChooseImageOption): Promise<ChooseImageResult>;

345

function previewImage(options: PreviewImageOption): Promise<void>;

346

function getImageInfo(options: GetImageInfoOption): Promise<ImageInfoResult>;

347

function saveImageToPhotosAlbum(options: SaveImageOption): Promise<void>;

348

349

interface ChooseImageOption {

350

count?: number;

351

sizeType?: ('original' | 'compressed')[];

352

sourceType?: ('album' | 'camera' | 'user')[];

353

}

354

355

interface ImageInfoResult {

356

width: number;

357

height: number;

358

path: string;

359

}

360

```

361

362

[Media APIs](./media.md)

363

364

### Canvas APIs

365

366

HTML5 Canvas integration providing 2D graphics capabilities and image manipulation with Mini Program compatibility.

367

368

```typescript { .api }

369

function createCanvasContext(canvasId: string, componentInstance?: any): CanvasContext;

370

function canvasToTempFilePath(options: CanvasToTempFilePathOption): Promise<CanvasToTempFilePathResult>;

371

function canvasGetImageData(options: CanvasGetImageDataOption): Promise<CanvasGetImageDataResult>;

372

function canvasPutImageData(options: CanvasPutImageDataOption): Promise<void>;

373

374

interface CanvasContext {

375

fillRect(x: number, y: number, width: number, height: number): void;

376

strokeRect(x: number, y: number, width: number, height: number): void;

377

beginPath(): void;

378

arc(x: number, y: number, radius: number, startAngle: number, endAngle: number): void;

379

setFillStyle(color: string): void;

380

fillText(text: string, x: number, y: number): void;

381

drawImage(imageResource: string, x: number, y: number): void;

382

draw(reserve?: boolean, callback?: () => void): void;

383

}

384

```

385

386

[Canvas APIs](./canvas.md)

387

388

## Implementation Status

389

390

### ✅ Fully Implemented (Web-Compatible)

391

- **Core Framework APIs**: Complete Taro object with utilities

392

- **Storage APIs**: Full localStorage integration

393

- **Network APIs**: Complete fetch-based implementation with download/upload/WebSocket support

394

- **System Information**: Comprehensive browser environment detection

395

- **UI Interactions**: Toast, modal, loading, action sheet

396

- **Location Services**: Geolocation API integration

397

- **Route Navigation**: @tarojs/router integration

398

- **DOM Query**: Web-compatible selector and observer APIs

399

- **Basic Device APIs**: Clipboard access

400

- **Media APIs**: Image selection, preview, information retrieval, and album saving

401

- **Canvas APIs**: Basic 2D graphics and image operations

402

403

### ⚠️ Partially Implemented

404

- **Advanced Device APIs**: Most hardware features not available in browsers

405

- **Advanced Media APIs**: Video/audio processing and platform-specific media features

406

407

### ❌ Not Implemented (Platform Limitations)

408

- **Mini Program Specific**: WeChat, Alipay, Baidu platform APIs

409

- **Native Features**: File system, advanced hardware access, payments

410

- **Platform Services**: Cloud functions, analytics, advertising

411

- **Advanced Media**: Camera, microphone, Bluetooth, NFC

412

413

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

414

415

## Types

416

417

```typescript { .api }

418

interface CallbackOptions {

419

success?: (res: any) => void;

420

fail?: (err: any) => void;

421

complete?: (res: any) => void;

422

}

423

424

interface ComponentInstance {

425

page?: any;

426

router?: {

427

params: Record<string, string>;

428

path: string;

429

};

430

scope?: any;

431

[key: string]: any;

432

}

433

434

interface PageInstance {

435

route: string;

436

options: Record<string, string>;

437

[key: string]: any;

438

}

439

440

interface SafeAreaResult {

441

left: number;

442

right: number;

443

top: number;

444

bottom: number;

445

width: number;

446

height: number;

447

}

448

449

// Environment types

450

declare const ENV_TYPE: {

451

WEAPP: 'WEAPP';

452

WEB: 'WEB';

453

RN: 'RN';

454

SWAN: 'SWAN';

455

ALIPAY: 'ALIPAY';

456

TT: 'TT';

457

QQ: 'QQ';

458

JD: 'JD';

459

};

460

461

type TaroGeneral = {

462

TDeviceRatio: Record<number, number>;

463

};

464

```