Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lưu trữ file không giới hạn trong Chrome App (bundled app)

Chrome App (packaged/legacy, không còn phát triển từ 2020, thay bằng PWA/Extension MV3) có quyền truy cập file system thật sự qua chrome.fileSystem API.

Cách đạt được "unlimited storage"

  1. Khai báo quyền trong manifest.json:
{
  "name": "My App",
  "permissions": ["fileSystem", "unlimitedStorage"],
  "app": { "background": { "scripts": ["background.js"] } }
}
  1. Yêu cầu người dùng chọn file/thư mục:
chrome.fileSystem.chooseEntry({ type: 'openFile' }, function(entry) {
  if (!entry) return; // User cancelled
  
  // entry là FileEntry hoặc DirectoryEntry
  // Ghi file:
  entry.createWriter(function(writer) {
    writer.write(new Blob(['Hello World'], { type: 'text/plain' }));
  });
  
  // Đọc file:
  entry.file(function(file) {
    var reader = new FileReader();
    reader.onload = function(e) { console.log(e.target.result); };
    reader.readAsText(file);
  });
});

Giải thích

  • chrome.fileSystem.chooseEntry: Mở dialog native cho user chọn file/thư mục. App nhận được FileEntry/DirectoryEntry với quyền đọc/ghi vĩnh viễn (cho đến khi user thu hồi).
  • unlimitedStorage: Cho phép vượt quota 5MB/10MB của IndexedDB/LocalStorage. Dữ liệu ghi ra file system thật (HDD/SSD), không giới hạn quota browser.
  • Nếu không dùng chooseEntry (chỉ dùng File API trong sandbox), vẫn bị giới hạn quota.

⚠️ Lưu quan trọng: Chrome App đã deprecated

  • Chrome App (packaged) **ngừng hỗ trợ** trên Windows/Mac/Linux từ Chrome 72 (2019), Chrome OS từ 2025.
  • Thay thế: PWA (Progressive Web App) + File System Access API (Chrome 86+):
// PWA hiện đại: File System Access API
const handle = await window.showSaveFilePicker({ suggestedName: 'data.txt' });
const writable = await handle.createWritable();
await writable.write('Hello World');
await writable.close();

File System Access API cho phép PWA đọc/ghi file thật với quyền user cho phép, không cần "unlimitedStorage" manifest.