javascript无法直接访问设备存储空间,但可通过间接方法估算。1. 使用navigator.storage api(推荐),通过estimate()方法获取使用量和配额估算值,优点是标准api兼容性好,缺点是估算值不精确;2. 尝试写入大量数据,通过异常判断存储上限,优点是实现简单,缺点是不精确且影响性能;3. 使用indexeddb进行更可靠的大数据存储测试,优点是比localstorage更可靠,缺点是代码复杂且同样不精确;4. filesystem api(已废弃),可获取应用配额,但不推荐使用;5. 结合service worker缓存机制间接检测,优点是便于资源管理,缺点是主要用于缓存。选择方案时应优先考虑兼容性和安全限制,避免阻塞主线程并优化用户体验。
检测设备存储空间,在JS里其实挺重要的,特别是做PWA或者需要大量本地存储的应用。直接告诉你答案吧,JS本身没法直接访问底层的硬件信息,但我们可以通过一些间接的方法来估算或获取存储信息。
这里介绍几种常用的JS检测设备存储空间的方法,各有优缺点,你可以根据实际情况选择:
navigator.storage API (推荐)
这是HTML5 Storage API的一部分,提供了一种更安全、更可靠的方式来管理和查询存储信息。
if (navigator.storage && navigator.storage.estimate) { navigator.storage.estimate().then(estimate => { console.log(`Usage: ${estimate.usage}`); console.log(`Quota: ${estimate.quota}`); console.log(`Percent Used: ${Math.round(estimate.usage / estimate.quota * 100)}%`); }); } else { console.log("Storage estimate API not supported."); }
尝试写入大量数据
这是一种比较“暴力”的方法,通过不断写入数据,直到抛出异常,然后根据写入的数据量来估算可用空间。
function estimateStorage() { let size = 0; try { localStorage.clear(); // 清空之前的数据 const start = Date.now(); while (Date.now() - start < 5000) { // 限制时间,防止无限循环 const key = 'test' + size; const value = 'a'.repeat(1024); // 1KB 的字符串 localStorage.setItem(key, value); size++; } } catch (e) { console.log("Storage full at:", size, "KB"); localStorage.clear(); // 清空测试数据 return size; } localStorage.clear(); console.log("Storage estimate failed: likely unlimited"); return -1; // 无法估算 } estimateStorage();
使用IndexedDB
IndexedDB是一个客户端数据库,可以用来存储大量结构化数据。虽然主要目的是数据存储,但我们也可以利用它来检测存储空间。
function estimateStorageWithIndexedDB() { return new Promise((resolve, reject) => { const dbName = 'storage_test_db'; const objectStoreName = 'test_store'; const request = indexedDB.open(dbName, 1); request.onerror = (event) => { reject('Failed to open database'); }; request.onupgradeneeded = (event) => { const db = event.target.result; const objectStore = db.createObjectStore(objectStoreName); }; request.onsuccess = (event) => { const db = event.target.result; const transaction = db.transaction([objectStoreName], 'readwrite'); const objectStore = transaction.objectStore(objectStoreName); let size = 0; const start = Date.now(); function writeData() { if (Date.now() - start > 5000) { transaction.abort(); // 超时 db.close(); indexedDB.deleteDatabase(dbName); resolve(-1); // 估算失败 return; } const key = 'key' + size; const value = new ArrayBuffer(1024); // 1KB const addRequest = objectStore.add(value, key); addRequest.onsuccess = () => { size++; writeData(); }; addRequest.onerror = () => { transaction.abort(); db.close(); indexedDB.deleteDatabase(dbName); console.log("IndexedDB Storage full at:", size, "KB"); resolve(size); }; } writeData(); transaction.oncomplete = () => { db.close(); indexedDB.deleteDatabase(dbName); }; transaction.onerror = () => { db.close(); indexedDB.deleteDatabase(dbName); reject('Transaction error'); }; }; }); } estimateStorageWithIndexedDB() .then(size => console.log("Estimated storage (IndexedDB):", size, "KB")) .catch(error => console.error(error));
使用FileSystem API (已废弃)
这是一个已废弃的API,不推荐使用。但如果你的应用需要兼容一些老旧的浏览器,可以考虑使用。
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; if (window.requestFileSystem) { window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function(fs) { console.log('Quota in bytes: ' + fs.quota); }, function(e) { console.log('Error getting quota: ' + e.code); }); } else { console.log('FileSystem API not supported'); }
结合Service Worker缓存
Service Worker 可以拦截网络请求并缓存资源。我们可以利用缓存API来间接检测存储空间。
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(registration => { return caches.open('test-cache'); }) .then(cache => { // 尝试缓存大量资源,并监听错误 // ... }) .catch(error => { console.error('Service Worker cache error:', error); }); }
选择哪种方案取决于你的具体需求。如果只需要一个大概的估算值,并且需要兼容性较好的方案,navigator.storage.estimate是首选。如果需要更精确的控制,并且不介意代码复杂度,可以考虑IndexedDB。避免使用已废弃的FileSystem API。
这是出于安全和隐私的考虑。如果网站可以精确地知道设备的存储空间,可能会被用来进行用户追踪。估算值可以提供足够的信息,同时保护用户的隐私。
是的,特别是写入大量数据的方法,会阻塞主线程,影响用户体验。优化方法包括:
在Native应用中(如Android或iOS),可以使用相应的API直接获取设备存储空间信息。这些API提供更精确的数据,并且不会受到浏览器的限制。
以上就是js如何检测设备存储空间 5种存储检测方案掌握设备容量状态的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号