CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tarojs--taro-h5

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

Pending
Overview
Eval results
Files

storage.mddocs/

Storage APIs

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

Capabilities

Synchronous Storage Operations

Direct storage operations that execute immediately and return results synchronously.

/**
 * Store data synchronously in local storage
 * @param key - Storage key identifier
 * @param data - Data to store (any JSON-serializable value)
 */
function setStorageSync(key: string, data: any): void;

/**
 * Retrieve data synchronously from local storage
 * @param key - Storage key identifier
 * @returns Stored data or empty string if key doesn't exist
 */
function getStorageSync(key: string): any;

/**
 * Remove data synchronously from local storage
 * @param key - Storage key identifier to remove
 */
function removeStorageSync(key: string): void;

/**
 * Clear all data synchronously from local storage
 */
function clearStorageSync(): void;

/**
 * Get storage information synchronously
 * @returns Storage statistics and key list
 */
function getStorageInfoSync(): StorageInfo;

Usage Examples:

import { setStorageSync, getStorageSync, removeStorageSync } from "@tarojs/taro-h5";

// Store simple data
setStorageSync('username', 'alice');
setStorageSync('userId', 12345);

// Store complex objects
setStorageSync('user', {
  id: 1,
  name: 'Alice',
  email: 'alice@example.com',
  preferences: {
    theme: 'dark',
    language: 'en'
  }
});

// Retrieve data
const username = getStorageSync('username'); // 'alice'
const user = getStorageSync('user'); // Full user object
const nonExistent = getStorageSync('missing'); // ''

// Remove specific items
removeStorageSync('userId');

// Clear all storage
clearStorageSync();

Asynchronous Storage Operations

Promise-based storage operations for non-blocking data management with callback support.

/**
 * Store data asynchronously in local storage
 * @param options - Storage options with key and data
 * @returns Promise that resolves when storage is complete
 */
function setStorage(options: SetStorageOption): Promise<void>;

/**
 * Retrieve data asynchronously from local storage
 * @param options - Retrieval options with key
 * @returns Promise that resolves with stored data
 */
function getStorage<T = any>(options: GetStorageOption): Promise<T>;

/**
 * Remove data asynchronously from local storage
 * @param options - Removal options with key
 * @returns Promise that resolves when removal is complete
 */
function removeStorage(options: RemoveStorageOption): Promise<void>;

/**
 * Clear all data asynchronously from local storage
 * @param options - Optional callback options
 * @returns Promise that resolves when clearing is complete
 */
function clearStorage(options?: CallbackOptions): Promise<void>;

/**
 * Get storage information asynchronously
 * @param options - Optional callback options
 * @returns Promise that resolves with storage information
 */
function getStorageInfo(options?: CallbackOptions): Promise<StorageInfo>;

interface SetStorageOption extends CallbackOptions {
  /** Storage key identifier */
  key: string;
  /** Data to store (any JSON-serializable value) */
  data: any;
}

interface GetStorageOption extends CallbackOptions {
  /** Storage key identifier */
  key: string;
}

interface RemoveStorageOption extends CallbackOptions {
  /** Storage key identifier to remove */
  key: string;
}

Usage Examples:

import { setStorage, getStorage, removeStorage, clearStorage } from "@tarojs/taro-h5";

// Async/await pattern
async function handleUserData() {
  try {
    // Store user data
    await setStorage({
      key: 'currentUser',
      data: {
        id: 123,
        name: 'Bob',
        lastLogin: new Date().toISOString()
      }
    });

    // Retrieve user data
    const userData = await getStorage<UserData>({
      key: 'currentUser'
    });
    console.log('User:', userData.name);

    // Remove specific data
    await removeStorage({ key: 'tempData' });

    // Clear all storage
    await clearStorage();
    
  } catch (error) {
    console.error('Storage operation failed:', error);
  }
}

// Callback pattern
setStorage({
  key: 'settings',
  data: { theme: 'dark', notifications: true },
  success: (res) => {
    console.log('Settings saved successfully');
  },
  fail: (error) => {
    console.error('Failed to save settings:', error);
  },
  complete: () => {
    console.log('Storage operation completed');
  }
});

Storage Information

Utilities for monitoring storage usage and available keys.

/**
 * Storage information object containing usage statistics
 */
interface StorageInfo {
  /** Array of all storage keys currently in use */
  keys: string[];
  /** Current storage size in KB (approximate) */
  currentSize: number;
  /** Maximum storage limit in KB (browser dependent) */
  limitSize: number;
}

Usage Examples:

import { getStorageInfoSync, getStorageInfo } from "@tarojs/taro-h5";

// Synchronous storage info
const info = getStorageInfoSync();
console.log(`Stored keys: ${info.keys.length}`);
console.log(`Current usage: ${info.currentSize}KB / ${info.limitSize}KB`);
console.log('Keys:', info.keys);

// Asynchronous storage info
const storageInfo = await getStorageInfo();
const usagePercent = (storageInfo.currentSize / storageInfo.limitSize) * 100;
console.log(`Storage usage: ${usagePercent.toFixed(1)}%`);

// Check if specific key exists
const hasUserData = info.keys.includes('userData');
if (hasUserData) {
  console.log('User data is stored');
}

Error Handling

Storage operations can fail due to quota limits, invalid data, or browser restrictions.

// Handling storage quota exceeded
try {
  setStorageSync('largeData', new Array(1000000).fill('data'));
} catch (error) {
  if (error.message.includes('quota')) {
    console.log('Storage quota exceeded');
    // Handle quota error - maybe clear old data
    const info = getStorageInfoSync();
    console.log(`Current usage: ${info.currentSize}KB`);
  }
}

// Async error handling
async function safeStorageOperation() {
  try {
    await setStorage({
      key: 'criticalData',
      data: importantUserData
    });
  } catch (error) {
    // Fallback strategies
    console.error('Primary storage failed:', error);
    
    // Try clearing old data and retry
    await clearStorage();
    await setStorage({
      key: 'criticalData',
      data: importantUserData
    });
  }
}

Data Type Handling

Storage automatically serializes and deserializes JSON-compatible data types.

// Supported data types
setStorageSync('string', 'Hello World');
setStorageSync('number', 42);
setStorageSync('boolean', true);
setStorageSync('array', [1, 2, 3, 'four']);
setStorageSync('object', {
  nested: {
    property: 'value'
  },
  array: [1, 2, 3],
  date: new Date().toISOString() // Dates as ISO strings
});
setStorageSync('null', null);

// Unsupported types (functions, undefined, symbols)
// These will be omitted or converted during JSON serialization
const complexObject = {
  validProp: 'This will be stored',
  func: () => {}, // Will be omitted
  undef: undefined, // Will be omitted
  symb: Symbol('test') // Will be omitted
};

setStorageSync('complex', complexObject);
const retrieved = getStorageSync('complex');
// retrieved = { validProp: 'This will be stored' }

Best Practices

// 1. Use descriptive keys with namespacing
setStorageSync('user:profile', userProfile);
setStorageSync('app:settings', appSettings);
setStorageSync('cache:apiData', apiResponse);

// 2. Handle missing data gracefully
function getUserPreferences() {
  const prefs = getStorageSync('user:preferences');
  return prefs || {
    theme: 'light',
    language: 'en',
    notifications: true
  };
}

// 3. Implement data versioning for updates
const DATA_VERSION = '1.2.0';

function saveVersionedData(key: string, data: any) {
  setStorageSync(key, {
    version: DATA_VERSION,
    data: data,
    timestamp: Date.now()
  });
}

function loadVersionedData(key: string) {
  const stored = getStorageSync(key);
  if (!stored || stored.version !== DATA_VERSION) {
    // Handle version mismatch or missing data
    return null;
  }
  return stored.data;
}

// 4. Monitor storage usage
function checkStorageHealth() {
  const info = getStorageInfoSync();
  const usagePercent = (info.currentSize / info.limitSize) * 100;
  
  if (usagePercent > 80) {
    console.warn('Storage usage is high:', usagePercent + '%');
    // Implement cleanup strategy
    cleanupOldCache();
  }
}

function cleanupOldCache() {
  const info = getStorageInfoSync();
  const cacheKeys = info.keys.filter(key => key.startsWith('cache:'));
  
  // Remove old cache entries
  cacheKeys.forEach(key => {
    const data = getStorageSync(key);
    if (data.timestamp < Date.now() - (7 * 24 * 60 * 60 * 1000)) { // 7 days old
      removeStorageSync(key);
    }
  });
}

Batch Storage Operations (Not Supported)

Advanced batch operations for handling multiple storage items simultaneously. These APIs are temporarily not supported in the H5 implementation.

/**
 * Set multiple storage items in a single batch operation
 * Note: Temporarily not supported - returns success stub
 * @param options - Batch set storage options
 * @returns Promise that resolves with success stub
 */
function batchSetStorage(options: BatchSetStorageOption): Promise<void>;

/**
 * Set multiple storage items synchronously in a single batch operation  
 * Note: Temporarily not supported - returns success stub
 * @param kvList - Array of key-value pairs to store
 */
function batchSetStorageSync(kvList: KeyValuePair[]): void;

/**
 * Get multiple storage items in a single batch operation
 * Note: Temporarily not supported - returns success stub
 * @param options - Batch get storage options
 * @returns Promise that resolves with success stub
 */
function batchGetStorage(options: BatchGetStorageOption): Promise<BatchGetStorageResult>;

/**
 * Get multiple storage items synchronously in a single batch operation
 * Note: Temporarily not supported - returns empty result
 * @param keyList - Array of keys to retrieve
 * @returns Empty result object
 */
function batchGetStorageSync(keyList: string[]): BatchGetStorageResult;

interface KeyValuePair {
  /** Storage key identifier */
  key: string;
  /** Data to store */
  data: any;
}

interface BatchSetStorageOption extends CallbackOptions {
  /** Array of key-value pairs to store */
  kvList: KeyValuePair[];
}

interface BatchGetStorageOption extends CallbackOptions {
  /** Array of keys to retrieve */
  keyList: string[];
}

interface BatchGetStorageResult {
  /** Retrieved key-value pairs */
  kvList: KeyValuePair[];
}

Alternative Implementation:

Since batch operations are not natively supported, you can implement them using individual storage operations:

// Alternative batch set implementation
async function customBatchSetStorage(kvList: KeyValuePair[]): Promise<void> {
  const promises = kvList.map(({ key, data }) => 
    setStorage({ key, data }).catch(error => ({ key, error }))
  );
  
  const results = await Promise.all(promises);
  const errors = results.filter(result => result && 'error' in result);
  
  if (errors.length > 0) {
    console.warn('Some batch set operations failed:', errors);
  }
  
  console.log(`Batch set completed: ${kvList.length - errors.length}/${kvList.length} successful`);
}

// Alternative batch get implementation
async function customBatchGetStorage(keyList: string[]): Promise<BatchGetStorageResult> {
  const promises = keyList.map(async (key) => {
    try {
      const data = await getStorage({ key });
      return { key, data };
    } catch (error) {
      console.warn(`Failed to get key "${key}":`, error);
      return null;
    }
  });
  
  const results = await Promise.all(promises);
  const kvList = results.filter(result => result !== null) as KeyValuePair[];
  
  return { kvList };
}

// Usage example
async function demonstrateBatchOperations() {
  // Batch set data
  const dataToSet = [
    { key: 'user:profile', data: { name: 'Alice', age: 25 } },
    { key: 'user:settings', data: { theme: 'dark', language: 'en' } },
    { key: 'app:version', data: '1.2.0' }
  ];
  
  await customBatchSetStorage(dataToSet);
  
  // Batch get data
  const keysToGet = ['user:profile', 'user:settings', 'app:version'];
  const result = await customBatchGetStorage(keysToGet);
  
  console.log('Retrieved data:', result.kvList);
}

Buffer Storage Operations (Not Supported)

Buffer URL creation and management for handling binary data. These APIs are temporarily not supported in the H5 implementation.

/**
 * Create buffer URL for binary data handling
 * Note: Temporarily not supported - returns stub
 * @param buffer - Binary data buffer
 * @returns Placeholder buffer URL
 */
function createBufferURL(buffer: ArrayBuffer): string;

/**
 * Revoke previously created buffer URL
 * Note: Temporarily not supported - returns stub
 * @param bufferUrl - Buffer URL to revoke
 */
function revokeBufferURL(bufferUrl: string): void;

Alternative Implementation:

Use standard Web APIs for buffer handling:

// Alternative buffer URL implementation using Web APIs
function createWebBufferURL(data: ArrayBuffer, mimeType: string = 'application/octet-stream'): string {
  const blob = new Blob([data], { type: mimeType });
  return URL.createObjectURL(blob);
}

function revokeWebBufferURL(bufferUrl: string): void {
  URL.revokeObjectURL(bufferUrl);
}

// Usage example
function handleBinaryData(arrayBuffer: ArrayBuffer) {
  // Create buffer URL
  const bufferUrl = createWebBufferURL(arrayBuffer, 'image/jpeg');
  
  // Use the buffer URL (e.g., display image)
  const img = document.createElement('img');
  img.src = bufferUrl;
  document.body.appendChild(img);
  
  // Clean up when done
  img.onload = () => {
    setTimeout(() => {
      revokeWebBufferURL(bufferUrl);
    }, 1000);
  };
}

Types

interface CallbackOptions {
  /** Success callback function */
  success?: (res: any) => void;
  /** Failure callback function */
  fail?: (err: any) => void;
  /** Completion callback function (called regardless of success/failure) */
  complete?: (res: any) => void;
}

interface UserData {
  id: number;
  name: string;
  email?: string;
  lastLogin: string;
  preferences?: {
    theme: 'light' | 'dark';
    language: string;
    notifications: boolean;
  };
}

Install with Tessl CLI

npx tessl i tessl/npm-tarojs--taro-h5

docs

canvas.md

core-framework.md

device.md

dom-query.md

index.md

location.md

media.md

navigation.md

network.md

storage.md

system-info.md

ui-interactions.md

tile.json