H5端API库,为Taro跨端开发框架提供Web/H5端的API实现
—
Limited device capability APIs focusing on web-compatible features like clipboard access, with most hardware-specific functionality not available due to browser security restrictions.
Read and write text data to the system clipboard using the browser's Clipboard API.
/**
* Set text data to system clipboard
* @param options - Clipboard data configuration
* @returns Promise that resolves when data is set
*/
function setClipboardData(options: ClipboardDataOption): Promise<void>;
/**
* Get text data from system clipboard
* @param options - Optional callback configuration
* @returns Promise resolving to clipboard text data
*/
function getClipboardData(options?: CallbackOptions): Promise<ClipboardDataResult>;
interface ClipboardDataOption extends CallbackOptions {
/** Text data to copy to clipboard (required) */
data: string;
}
interface ClipboardDataResult {
/** Text data from clipboard */
data: string;
}Usage Examples:
import { setClipboardData, getClipboardData } from "@tarojs/taro-h5";
// Copy text to clipboard
async function copyToClipboard(text: string) {
try {
await setClipboardData({
data: text
});
await showToast({
title: 'Copied to clipboard',
icon: 'success'
});
} catch (error) {
console.error('Failed to copy to clipboard:', error);
await showToast({
title: 'Copy failed',
icon: 'error'
});
}
}
// Read from clipboard
async function pasteFromClipboard(): Promise<string | null> {
try {
const result = await getClipboardData();
console.log('Clipboard content:', result.data);
return result.data;
} catch (error) {
console.error('Failed to read from clipboard:', error);
await showToast({
title: 'Paste failed',
icon: 'error'
});
return null;
}
}
// Copy with callbacks
setClipboardData({
data: 'Hello, World!',
success: () => {
console.log('Successfully copied to clipboard');
},
fail: (error) => {
console.error('Copy failed:', error);
},
complete: () => {
console.log('Clipboard operation completed');
}
});
// Advanced clipboard operations
class ClipboardManager {
async copyText(text: string): Promise<boolean> {
try {
await setClipboardData({ data: text });
return true;
} catch (error) {
console.error('Clipboard copy failed:', error);
return false;
}
}
async pasteText(): Promise<string | null> {
try {
const result = await getClipboardData();
return result.data || null;
} catch (error) {
console.error('Clipboard paste failed:', error);
return null;
}
}
async copyWithFeedback(text: string, successMessage = 'Copied!'): Promise<void> {
const success = await this.copyText(text);
if (success) {
await showToast({
title: successMessage,
icon: 'success',
duration: 1500
});
} else {
await showToast({
title: 'Copy failed',
icon: 'error'
});
}
}
async copyUrl(url: string): Promise<void> {
await this.copyWithFeedback(url, 'URL copied!');
}
async copyCode(code: string): Promise<void> {
await this.copyWithFeedback(code, 'Code copied!');
}
}
// Usage
const clipboard = new ClipboardManager();
// Copy different types of content
await clipboard.copyText('Simple text');
await clipboard.copyUrl('https://example.com');
await clipboard.copyCode('console.log("Hello, World!");');
// Paste content
const pastedText = await clipboard.pasteText();
if (pastedText) {
console.log('Pasted:', pastedText);
}The following device APIs are not implemented in the H5 environment due to browser security restrictions and platform limitations:
These APIs require native platform access and are not available in web environments:
// ❌ Not implemented - Hardware device APIs
declare function getBluetoothAdapterState(): never;
declare function openBluetoothAdapter(): never;
declare function startBluetoothDevicesDiscovery(): never;
declare function getBluetoothDevices(): never;
declare function startAccelerometer(): never;
declare function stopAccelerometer(): never;
declare function onAccelerometerChange(): never;
declare function startCompass(): never;
declare function stopCompass(): never;
declare function onCompassChange(): never;
declare function startGyroscope(): never;
declare function stopGyroscope(): never;
declare function onGyroscopeChange(): never;
declare function getBatteryInfo(): never;
declare function onBatteryInfoChange(): never;
declare function getNetworkType(): never;
declare function onNetworkStatusChange(): never;
declare function onMemoryWarning(): never;Camera and advanced media access require specific permissions and native implementations:
// ❌ Not implemented - Camera and media APIs
declare function chooseImage(): never;
declare function previewImage(): never;
declare function getImageInfo(): never;
declare function saveImageToPhotosAlbum(): never;
declare function chooseVideo(): never;
declare function saveVideoToPhotosAlbum(): never;
declare function getRecorderManager(): never;
declare function startRecord(): never;
declare function stopRecord(): never;File system access is restricted in web environments:
// ❌ Not implemented - File system APIs
declare function saveFile(): never;
declare function getFileInfo(): never;
declare function getSavedFileList(): never;
declare function removeSavedFile(): never;
declare function openDocument(): never;
declare function getFileSystemManager(): never;
declare function readFile(): never;
declare function writeFile(): never;
declare function copyFile(): never;
declare function renameFile(): never;
declare function unlink(): never;
declare function mkdir(): never;
declare function rmdir(): never;
declare function readdir(): never;
declare function stat(): never;Advanced communication features require native platform support:
// ❌ Not implemented - Communication APIs
declare function makePhoneCall(): never;
declare function sendSms(): never;
declare function startWifi(): never;
declare function stopWifi(): never;
declare function connectWifi(): never;
declare function getWifiList(): never;
declare function startBeaconDiscovery(): never;
declare function stopBeaconDiscovery(): never;
declare function getBeacons(): never;
declare function getHCEState(): never;
declare function startHCE(): never;
declare function stopHCE(): never;
declare function onHCEMessage(): never;
declare function sendHCEMessage(): never;Biometric authentication and advanced security features are platform-specific:
// ❌ Not implemented - Biometric and security APIs
declare function startSoterAuthentication(): never;
declare function checkIsSupportSoterAuthentication(): never;
declare function checkIsSoterEnrolledInDevice(): never;
declare function getUserCryptoManager(): never;
declare function getRandomValues(): never;Deep system integration features are not available in browser environments:
// ❌ Not implemented - System integration APIs
declare function setScreenBrightness(): never;
declare function getScreenBrightness(): never;
declare function setKeepScreenOn(): never;
declare function addPhoneContact(): never;
declare function addPhoneRepeatCalendar(): never;
declare function addPhoneCalendar(): never;
declare function vibrateLong(): never;
declare function vibrateShort(): never;
declare function setTabBarBadge(): never;
declare function removeTabBarBadge(): never;
declare function showTabBarRedDot(): never;
declare function hideTabBarRedDot(): never;
declare function scanCode(): never;For some device APIs, web-based alternatives or workarounds are possible:
// Web Vibration API (limited support)
function vibrateDevice(pattern: number | number[]): boolean {
if ('vibrate' in navigator) {
return navigator.vibrate(pattern);
}
console.warn('Vibration not supported');
return false;
}
// Usage
vibrateDevice(200); // Vibrate for 200ms
vibrateDevice([100, 50, 100]); // Pattern: vibrate 100ms, pause 50ms, vibrate 100ms// Network status using Navigator API
function getNetworkStatus(): { type: string; effectiveType?: string } {
if ('connection' in navigator) {
const connection = (navigator as any).connection;
return {
type: connection.type || 'unknown',
effectiveType: connection.effectiveType
};
}
return {
type: navigator.onLine ? 'online' : 'offline'
};
}
// Network change listener
function onNetworkChange(callback: (status: any) => void): void {
const handleChange = () => {
callback(getNetworkStatus());
};
window.addEventListener('online', handleChange);
window.addEventListener('offline', handleChange);
// Listen for connection changes if supported
if ('connection' in navigator) {
(navigator as any).connection.addEventListener('change', handleChange);
}
}// Screen Wake Lock API (experimental)
async function keepScreenOn(): Promise<boolean> {
if ('wakeLock' in navigator) {
try {
const wakeLock = await (navigator as any).wakeLock.request('screen');
console.log('Screen wake lock acquired');
wakeLock.addEventListener('release', () => {
console.log('Screen wake lock released');
});
return true;
} catch (error) {
console.error('Failed to acquire screen wake lock:', error);
}
}
return false;
}// File handling using Web APIs
class WebFileManager {
// File input for selecting files
selectFile(accept = '*/*'): Promise<File | null> {
return new Promise((resolve) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = accept;
input.onchange = (event) => {
const file = (event.target as HTMLInputElement).files?.[0];
resolve(file || null);
};
input.oncancel = () => resolve(null);
input.click();
});
}
// Read file as text
async readFileAsText(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsText(file);
});
}
// Read file as data URL
async readFileAsDataURL(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
// Download file
downloadFile(data: string | ArrayBuffer, filename: string, mimeType = 'application/octet-stream'): void {
const blob = new Blob([data], { type: mimeType });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = filename;
link.click();
URL.revokeObjectURL(url);
}
}
// Usage
const fileManager = new WebFileManager();
// Select and read a text file
const textFile = await fileManager.selectFile('text/*');
if (textFile) {
const content = await fileManager.readFileAsText(textFile);
console.log('File content:', content);
}
// Download data as file
fileManager.downloadFile('Hello, World!', 'hello.txt', 'text/plain');Device API operations can fail due to permissions, browser support, or security restrictions:
// Comprehensive device API error handling
async function safeDeviceOperation<T>(
operation: () => Promise<T>,
fallback?: () => T,
errorMessage = 'Device operation failed'
): Promise<T | null> {
try {
return await operation();
} catch (error: any) {
console.error(errorMessage, error);
// Handle permission errors
if (error.name === 'NotAllowedError') {
await showModal({
title: 'Permission Required',
content: 'This feature requires browser permission. Please allow access and try again.',
showCancel: false
});
}
// Handle unsupported features
else if (error.name === 'NotSupportedError') {
await showToast({
title: 'Feature not supported',
icon: 'error'
});
}
// Generic error handling
else {
await showToast({
title: errorMessage,
icon: 'error'
});
}
// Use fallback if available
if (fallback) {
return fallback();
}
return null;
}
}
// Usage
const clipboardData = await safeDeviceOperation(
() => getClipboardData(),
() => ({ data: '' }), // Fallback to empty string
'Failed to access clipboard'
);interface CallbackOptions {
success?: (res: any) => void;
fail?: (err: any) => void;
complete?: (res: any) => void;
}
interface DeviceError extends Error {
code?: string;
type?: 'permission_denied' | 'not_supported' | 'security_error' | 'unknown';
}
// Web API types for alternatives
interface NetworkInformation {
type?: string;
effectiveType?: '2g' | '3g' | '4g' | 'slow-2g';
downlink?: number;
rtt?: number;
saveData?: boolean;
}
interface WakeLock {
type: 'screen';
released: boolean;
release(): Promise<void>;
addEventListener(type: 'release', listener: () => void): void;
}Install with Tessl CLI
npx tessl i tessl/npm-tarojs--taro-h5