or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

bom.mddom.mdframework-integration.mdindex.mdtypes.mdutilities.md

bom.mddocs/

0

# Browser Object Model (BOM) APIs

1

2

Complete browser API polyfills that enable web-like development on mini-program platforms. The BOM implementation provides familiar browser objects including document, window, history, location, and navigation APIs.

3

4

## Overview

5

6

The BOM module creates a standardized browser environment across all platforms by implementing:

7

8

- **Document API**: DOM document interface with element creation and selection

9

- **Window API**: Global window object with event handling and timing functions

10

- **History API**: Browser navigation history with state management

11

- **Location API**: URL manipulation and navigation control

12

- **Navigator API**: Browser/platform information access

13

- **URL APIs**: URL parsing, manipulation and query parameter handling

14

- **Animation APIs**: RequestAnimationFrame for smooth animations

15

16

## Document API

17

18

### document

19

20

```typescript { .api }

21

import { document, TaroDocument } from '@tarojs/runtime'

22

23

interface TaroDocument extends TaroElement {

24

// Element creation

25

createElement(tagName: string): TaroElement

26

createTextNode(data: string): TaroText

27

createComment(data: string): TaroText

28

29

// Element selection

30

getElementById(id: string): TaroElement | null

31

querySelector(selectors: string): TaroElement | null

32

querySelectorAll(selectors: string): TaroElement[]

33

34

// Properties

35

documentElement: TaroElement // <html> element

36

head: TaroElement // <head> element

37

body: TaroElement // <body> element

38

39

// Event handling

40

addEventListener(type: string, handler: EventListener): void

41

removeEventListener(type: string, handler: EventListener): void

42

}

43

```

44

45

The document creates a standard HTML structure:

46

```

47

<html>

48

<head/>

49

<body>

50

<container>

51

<app/>

52

</container>

53

</body>

54

</html>

55

```

56

57

#### Usage Examples

58

59

```typescript

60

// Create elements

61

const view = document.createElement('view')

62

const text = document.createTextNode('Hello World')

63

view.appendChild(text)

64

65

// Find elements

66

const app = document.getElementById('app')

67

const container = document.querySelector('.container')

68

const views = document.querySelectorAll('view')

69

70

// Modify document

71

document.body.appendChild(view)

72

document.documentElement.className = 'theme-dark'

73

```

74

75

## Window API

76

77

### window

78

79

```typescript { .api }

80

import { window, TaroWindow } from '@tarojs/runtime'

81

82

interface TaroWindow extends Events {

83

// Navigation objects

84

navigator: Navigator

85

location: TaroLocation

86

history: TaroHistory

87

88

// Timing functions

89

setTimeout(handler: TimerHandler, timeout?: number, ...args: any[]): number

90

clearTimeout(handle?: number): void

91

setInterval(handler: TimerHandler, timeout?: number, ...args: any[]): number

92

clearInterval(handle?: number): void

93

94

// Animation

95

requestAnimationFrame(callback: FrameRequestCallback): number

96

cancelAnimationFrame(handle: number): void

97

98

// Styles

99

getComputedStyle(element: Element, pseudoElt?: string | null): CSSStyleDeclaration

100

101

// Standard objects

102

Date: DateConstructor

103

XMLHttpRequest: any

104

105

// Event handling (inherited from Events)

106

addEventListener(type: string, handler: EventListener): void

107

removeEventListener(type: string, handler: EventListener): void

108

109

// Context management (internal)

110

CONTEXT_ACTIONS: typeof CONTEXT_ACTIONS

111

}

112

113

enum CONTEXT_ACTIONS {

114

INIT = '0', // Initialize new page context

115

RESTORE = '1', // Restore existing context

116

RECOVER = '2', // Recover from cached context

117

DESTORY = '3' // Destroy context on page unload

118

}

119

```

120

121

#### Usage Examples

122

123

```typescript

124

// Timer functions

125

const timerId = window.setTimeout(() => {

126

console.log('Delayed execution')

127

}, 1000)

128

129

const intervalId = window.setInterval(() => {

130

console.log('Periodic execution')

131

}, 500)

132

133

window.clearTimeout(timerId)

134

window.clearInterval(intervalId)

135

136

// Animation frame

137

window.requestAnimationFrame((timestamp) => {

138

// Animation logic

139

console.log('Frame at:', timestamp)

140

})

141

142

// Event handling

143

window.addEventListener('resize', () => {

144

console.log('Window resized')

145

})

146

147

// Get computed styles

148

const styles = window.getComputedStyle(element)

149

console.log(styles.color, styles.fontSize)

150

```

151

152

## History API

153

154

### History

155

156

```typescript { .api }

157

import { History, TaroHistory } from '@tarojs/runtime'

158

159

interface TaroHistory extends Events {

160

// Properties

161

readonly length: number

162

readonly state: any

163

164

// Navigation methods

165

back(): void

166

forward(): void

167

go(delta?: number): void

168

169

// State management

170

pushState(stateObj: any, title: string, url?: string | null): void

171

replaceState(stateObj: any, title: string, url?: string | null): void

172

173

// Event handling

174

addEventListener(type: 'popstate', handler: (event: PopStateEvent) => void): void

175

removeEventListener(type: 'popstate', handler: (event: PopStateEvent) => void): void

176

}

177

178

// Global history instance

179

const history: TaroHistory

180

```

181

182

#### Key Features

183

184

- **Multi-page Context**: Maintains separate history stacks for different page contexts

185

- **State Caching**: Preserves navigation state across page switches

186

- **Event Integration**: Fires `popstate` events for navigation changes

187

- **URL Validation**: Validates URLs and handles navigation edge cases

188

189

#### Usage Examples

190

191

```typescript

192

// Navigation

193

history.back() // Go back one step

194

history.forward() // Go forward one step

195

history.go(-2) // Go back 2 steps

196

history.go(1) // Go forward 1 step

197

198

// State management

199

history.pushState({ page: 1 }, 'Page 1', '/page1')

200

history.replaceState({ page: 2 }, 'Page 2', '/page2')

201

202

// Listen for navigation

203

history.addEventListener('popstate', (event) => {

204

console.log('Navigation state:', event.state)

205

console.log('History length:', history.length)

206

})

207

208

// Access current state

209

console.log('Current state:', history.state)

210

console.log('History entries:', history.length)

211

```

212

213

## Location API

214

215

### Location

216

217

```typescript { .api }

218

import { Location, TaroLocation } from '@tarojs/runtime'

219

220

interface TaroLocation {

221

// URL components

222

protocol: string // "https:"

223

host: string // "example.com:8080"

224

hostname: string // "example.com"

225

port: string // "8080"

226

pathname: string // "/path/to/page"

227

search: string // "?param=value"

228

hash: string // "#section"

229

href: string // Full URL

230

origin: string // "https://example.com:8080"

231

232

// Navigation methods

233

assign(url: string): void

234

replace(url: string): void

235

reload(): void

236

toString(): string

237

}

238

239

// Global location instance

240

const location: TaroLocation

241

```

242

243

#### Key Features

244

245

- **URL Parsing**: Automatically parses and validates URLs

246

- **History Integration**: Navigation methods update history appropriately

247

- **Hash Navigation**: Supports hash-based routing with `hashchange` events

248

- **Cross-platform**: Works consistently across web and mini-program platforms

249

250

#### Usage Examples

251

252

```typescript

253

// Read URL components

254

console.log('Current page:', location.pathname)

255

console.log('Query params:', location.search)

256

console.log('Hash fragment:', location.hash)

257

console.log('Full URL:', location.href)

258

259

// Navigation

260

location.assign('/new-page') // Navigate to new page (adds history entry)

261

location.replace('/replacement') // Replace current page (no history entry)

262

location.reload() // Reload current page

263

264

// URL manipulation

265

location.hash = '#new-section' // Update hash

266

location.search = '?param=value' // Update query params

267

268

// Listen for hash changes

269

window.addEventListener('hashchange', () => {

270

console.log('Hash changed to:', location.hash)

271

})

272

```

273

274

## Navigator API

275

276

### navigator

277

278

```typescript { .api }

279

import { navigator } from '@tarojs/runtime'

280

281

interface Navigator {

282

readonly appCodeName: string // "Mozilla"

283

readonly appName: string // "Netscape"

284

readonly appVersion: string // Version string

285

readonly cookieEnabled: boolean // true

286

readonly onLine: boolean // true

287

readonly platform: string // "MacIntel"

288

readonly product: string // "Gecko"

289

readonly productSub: string // "20030107"

290

readonly userAgent: string // User agent string

291

readonly vendor: string // "Google Inc."

292

readonly vendorSub: string // ""

293

}

294

```

295

296

#### Usage Examples

297

298

```typescript

299

// Detect platform/browser

300

console.log('Platform:', navigator.platform)

301

console.log('User Agent:', navigator.userAgent)

302

console.log('Online status:', navigator.onLine)

303

304

// Feature detection

305

if (navigator.cookieEnabled) {

306

// Cookies are supported

307

}

308

309

// App information

310

console.log('App name:', navigator.appName)

311

console.log('App version:', navigator.appVersion)

312

```

313

314

## URL APIs

315

316

### URL

317

318

```typescript { .api }

319

import { URL, TaroURL } from '@tarojs/runtime'

320

321

interface TaroURL {

322

// URL components

323

protocol: string

324

hostname: string

325

host: string

326

port: string

327

pathname: string

328

search: string

329

hash: string

330

href: string

331

origin: string

332

333

// Search parameters

334

searchParams: URLSearchParams

335

336

// Methods

337

toString(): string

338

toJSON(): string

339

340

// Static methods (throw in mini-programs)

341

static createObjectURL(object: any): string

342

static revokeObjectURL(url: string): void

343

}

344

345

// Constructor

346

new URL(url: string, base?: string | URL): TaroURL

347

```

348

349

#### Usage Examples

350

351

```typescript

352

// Parse URL

353

const url = new URL('https://example.com:8080/path?param=value#section')

354

355

console.log('Protocol:', url.protocol) // "https:"

356

console.log('Host:', url.host) // "example.com:8080"

357

console.log('Pathname:', url.pathname) // "/path"

358

console.log('Search:', url.search) // "?param=value"

359

console.log('Hash:', url.hash) // "#section"

360

361

// Manipulate URL

362

url.pathname = '/new-path'

363

url.searchParams.set('newParam', 'newValue')

364

url.hash = '#new-section'

365

366

console.log('Updated URL:', url.toString())

367

368

// Relative URLs

369

const relative = new URL('/relative', 'https://example.com')

370

console.log('Absolute URL:', relative.href)

371

```

372

373

### URLSearchParams

374

375

```typescript { .api }

376

import { URLSearchParams } from '@tarojs/runtime'

377

378

interface URLSearchParams {

379

// Manipulation methods

380

append(name: string, value: string): void

381

delete(name: string): void

382

get(name: string): string | null

383

getAll(name: string): string[]

384

has(name: string): boolean

385

set(name: string, value: string): void

386

387

// Iteration

388

keys(): IterableIterator<string>

389

values(): IterableIterator<string>

390

entries(): IterableIterator<[string, string]>

391

forEach(callback: (value: string, key: string, parent: URLSearchParams) => void): void

392

393

// Serialization

394

toString(): string

395

}

396

397

// Constructor

398

new URLSearchParams(init?: string | URLSearchParams | Record<string, string>): URLSearchParams

399

```

400

401

#### Usage Examples

402

403

```typescript

404

// Create from string

405

const params = new URLSearchParams('?name=John&age=30&hobby=reading&hobby=gaming')

406

407

// Basic operations

408

console.log('Name:', params.get('name')) // "John"

409

console.log('All hobbies:', params.getAll('hobby')) // ["reading", "gaming"]

410

console.log('Has email:', params.has('email')) // false

411

412

// Modify parameters

413

params.set('age', '31') // Update existing

414

params.append('hobby', 'cooking') // Add new value

415

params.delete('name') // Remove parameter

416

417

// Iterate over parameters

418

params.forEach((value, key) => {

419

console.log(`${key}: ${value}`)

420

})

421

422

for (const [key, value] of params.entries()) {

423

console.log(`${key} = ${value}`)

424

}

425

426

// Convert to string

427

console.log('Query string:', params.toString()) // "age=31&hobby=reading&hobby=gaming&hobby=cooking"

428

```

429

430

## Animation APIs

431

432

### requestAnimationFrame / cancelAnimationFrame

433

434

```typescript { .api }

435

import { requestAnimationFrame, cancelAnimationFrame, now } from '@tarojs/runtime'

436

437

// Animation frame scheduling

438

function requestAnimationFrame(callback: FrameRequestCallback): number

439

function cancelAnimationFrame(handle: number): void

440

441

// High-resolution timestamp

442

function now(): number

443

444

type FrameRequestCallback = (timestamp: number) => void

445

```

446

447

#### Key Features

448

449

- **Cross-platform**: Uses native `requestAnimationFrame` on web, `setTimeout` fallback on mini-programs

450

- **Performance Timing**: Provides high-resolution timestamps via `now()`

451

- **Throttling**: Automatically throttles to ~60fps (16ms intervals) on platforms without native support

452

453

#### Usage Examples

454

455

```typescript

456

// Basic animation

457

function animate(timestamp: number) {

458

// Animation logic here

459

console.log('Frame at:', timestamp)

460

461

// Continue animation

462

requestAnimationFrame(animate)

463

}

464

465

// Start animation

466

const animationId = requestAnimationFrame(animate)

467

468

// Cancel animation

469

cancelAnimationFrame(animationId)

470

471

// Performance timing

472

const start = now()

473

// ... some work

474

const duration = now() - start

475

console.log('Operation took:', duration, 'ms')

476

477

// Smooth animation with timing

478

let startTime: number | null = null

479

480

function step(timestamp: number) {

481

if (!startTime) startTime = timestamp

482

483

const progress = (timestamp - startTime) / 1000 // 1 second animation

484

485

if (progress < 1) {

486

// Update animation state based on progress

487

updateAnimation(progress)

488

requestAnimationFrame(step)

489

} else {

490

// Animation complete

491

finishAnimation()

492

}

493

}

494

495

requestAnimationFrame(step)

496

```

497

498

## GetComputedStyle

499

500

### getComputedStyle

501

502

```typescript { .api }

503

import { getComputedStyle } from '@tarojs/runtime'

504

505

function getComputedStyle(

506

element: Element,

507

pseudoElement?: string | null

508

): CSSStyleDeclaration

509

510

interface CSSStyleDeclaration {

511

[property: string]: string

512

cssText: string

513

length: number

514

515

// Property access methods

516

getPropertyValue(property: string): string

517

setProperty(property: string, value: string, priority?: string): void

518

removeProperty(property: string): string

519

}

520

```

521

522

#### Usage Examples

523

524

```typescript

525

// Get computed styles

526

const element = document.getElementById('my-element')

527

const styles = getComputedStyle(element)

528

529

// Access individual properties

530

console.log('Color:', styles.color)

531

console.log('Font size:', styles.fontSize)

532

console.log('Display:', styles.display)

533

534

// Access via getPropertyValue

535

console.log('Background:', styles.getPropertyValue('background-color'))

536

537

// Get all CSS text

538

console.log('All styles:', styles.cssText)

539

540

// Pseudo-element styles (web only)

541

const beforeStyles = getComputedStyle(element, '::before')

542

console.log('Before content:', beforeStyles.content)

543

```

544

545

## Platform Considerations

546

547

### Mini-Program Limitations

548

549

Some browser APIs have limitations on mini-program platforms:

550

551

```typescript

552

// These throw errors on mini-programs

553

try {

554

URL.createObjectURL(blob) // Not supported

555

URL.revokeObjectURL(url) // Not supported

556

} catch (error) {

557

console.log('Not available on mini-programs')

558

}

559

560

// Fallback implementations

561

const styles = getComputedStyle(element) // Falls back to element.style

562

const timestamp = now() // Uses Date.now() if performance API unavailable

563

```

564

565

### Context Switching

566

567

The window object manages page contexts automatically:

568

569

```typescript

570

// Context actions (internal use)

571

window.CONTEXT_ACTIONS.INIT // Initialize new page

572

window.CONTEXT_ACTIONS.RESTORE // Restore cached page

573

window.CONTEXT_ACTIONS.RECOVER // Recover from cache

574

window.CONTEXT_ACTIONS.DESTORY // Clean up page context

575

```

576

577

The BOM APIs provide a complete browser environment that enables seamless cross-platform development while maintaining optimal performance on each target platform.