or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

device.mddocs/

0

# Device APIs

1

2

Limited device capability APIs focusing on web-compatible features like clipboard access, with most hardware-specific functionality not available due to browser security restrictions.

3

4

## Capabilities

5

6

### Clipboard Operations

7

8

Read and write text data to the system clipboard using the browser's Clipboard API.

9

10

```typescript { .api }

11

/**

12

* Set text data to system clipboard

13

* @param options - Clipboard data configuration

14

* @returns Promise that resolves when data is set

15

*/

16

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

17

18

/**

19

* Get text data from system clipboard

20

* @param options - Optional callback configuration

21

* @returns Promise resolving to clipboard text data

22

*/

23

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

24

25

interface ClipboardDataOption extends CallbackOptions {

26

/** Text data to copy to clipboard (required) */

27

data: string;

28

}

29

30

interface ClipboardDataResult {

31

/** Text data from clipboard */

32

data: string;

33

}

34

```

35

36

**Usage Examples:**

37

38

```typescript

39

import { setClipboardData, getClipboardData } from "@tarojs/taro-h5";

40

41

// Copy text to clipboard

42

async function copyToClipboard(text: string) {

43

try {

44

await setClipboardData({

45

data: text

46

});

47

48

await showToast({

49

title: 'Copied to clipboard',

50

icon: 'success'

51

});

52

} catch (error) {

53

console.error('Failed to copy to clipboard:', error);

54

await showToast({

55

title: 'Copy failed',

56

icon: 'error'

57

});

58

}

59

}

60

61

// Read from clipboard

62

async function pasteFromClipboard(): Promise<string | null> {

63

try {

64

const result = await getClipboardData();

65

console.log('Clipboard content:', result.data);

66

return result.data;

67

} catch (error) {

68

console.error('Failed to read from clipboard:', error);

69

await showToast({

70

title: 'Paste failed',

71

icon: 'error'

72

});

73

return null;

74

}

75

}

76

77

// Copy with callbacks

78

setClipboardData({

79

data: 'Hello, World!',

80

success: () => {

81

console.log('Successfully copied to clipboard');

82

},

83

fail: (error) => {

84

console.error('Copy failed:', error);

85

},

86

complete: () => {

87

console.log('Clipboard operation completed');

88

}

89

});

90

91

// Advanced clipboard operations

92

class ClipboardManager {

93

async copyText(text: string): Promise<boolean> {

94

try {

95

await setClipboardData({ data: text });

96

return true;

97

} catch (error) {

98

console.error('Clipboard copy failed:', error);

99

return false;

100

}

101

}

102

103

async pasteText(): Promise<string | null> {

104

try {

105

const result = await getClipboardData();

106

return result.data || null;

107

} catch (error) {

108

console.error('Clipboard paste failed:', error);

109

return null;

110

}

111

}

112

113

async copyWithFeedback(text: string, successMessage = 'Copied!'): Promise<void> {

114

const success = await this.copyText(text);

115

116

if (success) {

117

await showToast({

118

title: successMessage,

119

icon: 'success',

120

duration: 1500

121

});

122

} else {

123

await showToast({

124

title: 'Copy failed',

125

icon: 'error'

126

});

127

}

128

}

129

130

async copyUrl(url: string): Promise<void> {

131

await this.copyWithFeedback(url, 'URL copied!');

132

}

133

134

async copyCode(code: string): Promise<void> {

135

await this.copyWithFeedback(code, 'Code copied!');

136

}

137

}

138

139

// Usage

140

const clipboard = new ClipboardManager();

141

142

// Copy different types of content

143

await clipboard.copyText('Simple text');

144

await clipboard.copyUrl('https://example.com');

145

await clipboard.copyCode('console.log("Hello, World!");');

146

147

// Paste content

148

const pastedText = await clipboard.pasteText();

149

if (pastedText) {

150

console.log('Pasted:', pastedText);

151

}

152

```

153

154

## Not Implemented Device APIs

155

156

The following device APIs are not implemented in the H5 environment due to browser security restrictions and platform limitations:

157

158

### Hardware Access APIs

159

160

These APIs require native platform access and are not available in web environments:

161

162

```typescript

163

// ❌ Not implemented - Hardware device APIs

164

declare function getBluetoothAdapterState(): never;

165

declare function openBluetoothAdapter(): never;

166

declare function startBluetoothDevicesDiscovery(): never;

167

declare function getBluetoothDevices(): never;

168

169

declare function startAccelerometer(): never;

170

declare function stopAccelerometer(): never;

171

declare function onAccelerometerChange(): never;

172

173

declare function startCompass(): never;

174

declare function stopCompass(): never;

175

declare function onCompassChange(): never;

176

177

declare function startGyroscope(): never;

178

declare function stopGyroscope(): never;

179

declare function onGyroscopeChange(): never;

180

181

declare function getBatteryInfo(): never;

182

declare function onBatteryInfoChange(): never;

183

184

declare function getNetworkType(): never;

185

declare function onNetworkStatusChange(): never;

186

187

declare function onMemoryWarning(): never;

188

```

189

190

### Camera and Media APIs

191

192

Camera and advanced media access require specific permissions and native implementations:

193

194

```typescript

195

// ❌ Not implemented - Camera and media APIs

196

declare function chooseImage(): never;

197

declare function previewImage(): never;

198

declare function getImageInfo(): never;

199

declare function saveImageToPhotosAlbum(): never;

200

201

declare function chooseVideo(): never;

202

declare function saveVideoToPhotosAlbum(): never;

203

204

declare function getRecorderManager(): never;

205

declare function startRecord(): never;

206

declare function stopRecord(): never;

207

```

208

209

### File System APIs

210

211

File system access is restricted in web environments:

212

213

```typescript

214

// ❌ Not implemented - File system APIs

215

declare function saveFile(): never;

216

declare function getFileInfo(): never;

217

declare function getSavedFileList(): never;

218

declare function removeSavedFile(): never;

219

declare function openDocument(): never;

220

221

declare function getFileSystemManager(): never;

222

declare function readFile(): never;

223

declare function writeFile(): never;

224

declare function copyFile(): never;

225

declare function renameFile(): never;

226

declare function unlink(): never;

227

declare function mkdir(): never;

228

declare function rmdir(): never;

229

declare function readdir(): never;

230

declare function stat(): never;

231

```

232

233

### Communication APIs

234

235

Advanced communication features require native platform support:

236

237

```typescript

238

// ❌ Not implemented - Communication APIs

239

declare function makePhoneCall(): never;

240

declare function sendSms(): never;

241

242

declare function startWifi(): never;

243

declare function stopWifi(): never;

244

declare function connectWifi(): never;

245

declare function getWifiList(): never;

246

247

declare function startBeaconDiscovery(): never;

248

declare function stopBeaconDiscovery(): never;

249

declare function getBeacons(): never;

250

251

declare function getHCEState(): never;

252

declare function startHCE(): never;

253

declare function stopHCE(): never;

254

declare function onHCEMessage(): never;

255

declare function sendHCEMessage(): never;

256

```

257

258

### Biometric and Security APIs

259

260

Biometric authentication and advanced security features are platform-specific:

261

262

```typescript

263

// ❌ Not implemented - Biometric and security APIs

264

declare function startSoterAuthentication(): never;

265

declare function checkIsSupportSoterAuthentication(): never;

266

declare function checkIsSoterEnrolledInDevice(): never;

267

268

declare function getUserCryptoManager(): never;

269

declare function getRandomValues(): never;

270

```

271

272

### System Integration APIs

273

274

Deep system integration features are not available in browser environments:

275

276

```typescript

277

// ❌ Not implemented - System integration APIs

278

declare function setScreenBrightness(): never;

279

declare function getScreenBrightness(): never;

280

declare function setKeepScreenOn(): never;

281

282

declare function addPhoneContact(): never;

283

declare function addPhoneRepeatCalendar(): never;

284

declare function addPhoneCalendar(): never;

285

286

declare function vibrateLong(): never;

287

declare function vibrateShort(): never;

288

289

declare function setTabBarBadge(): never;

290

declare function removeTabBarBadge(): never;

291

declare function showTabBarRedDot(): never;

292

declare function hideTabBarRedDot(): never;

293

294

declare function scanCode(): never;

295

```

296

297

## Web Alternative Implementations

298

299

For some device APIs, web-based alternatives or workarounds are possible:

300

301

### Vibration Alternative

302

303

```typescript

304

// Web Vibration API (limited support)

305

function vibrateDevice(pattern: number | number[]): boolean {

306

if ('vibrate' in navigator) {

307

return navigator.vibrate(pattern);

308

}

309

console.warn('Vibration not supported');

310

return false;

311

}

312

313

// Usage

314

vibrateDevice(200); // Vibrate for 200ms

315

vibrateDevice([100, 50, 100]); // Pattern: vibrate 100ms, pause 50ms, vibrate 100ms

316

```

317

318

### Network Status Alternative

319

320

```typescript

321

// Network status using Navigator API

322

function getNetworkStatus(): { type: string; effectiveType?: string } {

323

if ('connection' in navigator) {

324

const connection = (navigator as any).connection;

325

return {

326

type: connection.type || 'unknown',

327

effectiveType: connection.effectiveType

328

};

329

}

330

331

return {

332

type: navigator.onLine ? 'online' : 'offline'

333

};

334

}

335

336

// Network change listener

337

function onNetworkChange(callback: (status: any) => void): void {

338

const handleChange = () => {

339

callback(getNetworkStatus());

340

};

341

342

window.addEventListener('online', handleChange);

343

window.addEventListener('offline', handleChange);

344

345

// Listen for connection changes if supported

346

if ('connection' in navigator) {

347

(navigator as any).connection.addEventListener('change', handleChange);

348

}

349

}

350

```

351

352

### Screen Brightness Alternative

353

354

```typescript

355

// Screen Wake Lock API (experimental)

356

async function keepScreenOn(): Promise<boolean> {

357

if ('wakeLock' in navigator) {

358

try {

359

const wakeLock = await (navigator as any).wakeLock.request('screen');

360

console.log('Screen wake lock acquired');

361

362

wakeLock.addEventListener('release', () => {

363

console.log('Screen wake lock released');

364

});

365

366

return true;

367

} catch (error) {

368

console.error('Failed to acquire screen wake lock:', error);

369

}

370

}

371

372

return false;

373

}

374

```

375

376

### File Operations Alternative

377

378

```typescript

379

// File handling using Web APIs

380

class WebFileManager {

381

// File input for selecting files

382

selectFile(accept = '*/*'): Promise<File | null> {

383

return new Promise((resolve) => {

384

const input = document.createElement('input');

385

input.type = 'file';

386

input.accept = accept;

387

388

input.onchange = (event) => {

389

const file = (event.target as HTMLInputElement).files?.[0];

390

resolve(file || null);

391

};

392

393

input.oncancel = () => resolve(null);

394

input.click();

395

});

396

}

397

398

// Read file as text

399

async readFileAsText(file: File): Promise<string> {

400

return new Promise((resolve, reject) => {

401

const reader = new FileReader();

402

reader.onload = () => resolve(reader.result as string);

403

reader.onerror = () => reject(reader.error);

404

reader.readAsText(file);

405

});

406

}

407

408

// Read file as data URL

409

async readFileAsDataURL(file: File): Promise<string> {

410

return new Promise((resolve, reject) => {

411

const reader = new FileReader();

412

reader.onload = () => resolve(reader.result as string);

413

reader.onerror = () => reject(reader.error);

414

reader.readAsDataURL(file);

415

});

416

}

417

418

// Download file

419

downloadFile(data: string | ArrayBuffer, filename: string, mimeType = 'application/octet-stream'): void {

420

const blob = new Blob([data], { type: mimeType });

421

const url = URL.createObjectURL(blob);

422

423

const link = document.createElement('a');

424

link.href = url;

425

link.download = filename;

426

link.click();

427

428

URL.revokeObjectURL(url);

429

}

430

}

431

432

// Usage

433

const fileManager = new WebFileManager();

434

435

// Select and read a text file

436

const textFile = await fileManager.selectFile('text/*');

437

if (textFile) {

438

const content = await fileManager.readFileAsText(textFile);

439

console.log('File content:', content);

440

}

441

442

// Download data as file

443

fileManager.downloadFile('Hello, World!', 'hello.txt', 'text/plain');

444

```

445

446

## Error Handling

447

448

Device API operations can fail due to permissions, browser support, or security restrictions:

449

450

```typescript

451

// Comprehensive device API error handling

452

async function safeDeviceOperation<T>(

453

operation: () => Promise<T>,

454

fallback?: () => T,

455

errorMessage = 'Device operation failed'

456

): Promise<T | null> {

457

try {

458

return await operation();

459

} catch (error: any) {

460

console.error(errorMessage, error);

461

462

// Handle permission errors

463

if (error.name === 'NotAllowedError') {

464

await showModal({

465

title: 'Permission Required',

466

content: 'This feature requires browser permission. Please allow access and try again.',

467

showCancel: false

468

});

469

}

470

// Handle unsupported features

471

else if (error.name === 'NotSupportedError') {

472

await showToast({

473

title: 'Feature not supported',

474

icon: 'error'

475

});

476

}

477

// Generic error handling

478

else {

479

await showToast({

480

title: errorMessage,

481

icon: 'error'

482

});

483

}

484

485

// Use fallback if available

486

if (fallback) {

487

return fallback();

488

}

489

490

return null;

491

}

492

}

493

494

// Usage

495

const clipboardData = await safeDeviceOperation(

496

() => getClipboardData(),

497

() => ({ data: '' }), // Fallback to empty string

498

'Failed to access clipboard'

499

);

500

```

501

502

## Types

503

504

```typescript { .api }

505

interface CallbackOptions {

506

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

507

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

508

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

509

}

510

511

interface DeviceError extends Error {

512

code?: string;

513

type?: 'permission_denied' | 'not_supported' | 'security_error' | 'unknown';

514

}

515

516

// Web API types for alternatives

517

interface NetworkInformation {

518

type?: string;

519

effectiveType?: '2g' | '3g' | '4g' | 'slow-2g';

520

downlink?: number;

521

rtt?: number;

522

saveData?: boolean;

523

}

524

525

interface WakeLock {

526

type: 'screen';

527

released: boolean;

528

release(): Promise<void>;

529

addEventListener(type: 'release', listener: () => void): void;

530

}

531

```