Skip to content

Commit 14ce9dc

Browse files
committed
feat(directory-access): enhance directory handling with explicit write permission checks for Android
1 parent e966f04 commit 14ce9dc

1 file changed

Lines changed: 27 additions & 48 deletions

File tree

index.html

Lines changed: 27 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -125,81 +125,60 @@ <h1>Android File System Demo</h1>
125125
}
126126
});
127127

128-
// 3. OPEN DIRECTORY (Read/Write)
128+
// 3. OPEN DIRECTORY (Fixed for Android)
129129
document.getElementById('btnDir').addEventListener('click', async () => {
130130
try {
131131
log("Requesting directory access...");
132-
// 1. Get the handle (Android often defaults this to Read-Only!)
133132
const dirHandle = await window.showDirectoryPicker({
134133
mode: "readwrite"
135134
});
136135

137136
log(`📂 Directory selected: ${dirHandle.name}`);
138137

139-
// --- THE CRITICAL FIX ---
140-
// We must explicitly verify/request WRITE permission now.
138+
// 1. Verify Directory Permission
141139
const options = { mode: 'readwrite' };
142-
// Check if we already have permission
143140
if ((await dirHandle.queryPermission(options)) !== 'granted') {
144-
log("⚠️ Handle is Read-Only. Requesting Write access...");
145-
// This triggers the browser prompt: "Allow site to edit files?"
146141
if ((await dirHandle.requestPermission(options)) !== 'granted') {
147-
throw new Error("Write permission was denied by the user.");
142+
throw new Error("Directory write permission denied.");
148143
}
149144
}
150-
log("✅ Write permission confirmed!");
151-
// -------------------------
152145

153146
// List contents
154147
const entries = [];
155-
log("--- Listing Files ---");
156148
for await (const entry of dirHandle.values()) {
157149
entries.push(entry);
158-
log(` - ${entry.kind}: ${entry.name}`);
159150
}
160-
if (entries.length === 0) log(" (empty folder)");
151+
log(`Files found: ${entries.length}`);
161152

162-
// Write/append to session log
163-
let existingLog = "";
164-
let visitCount = 1;
153+
// 2. Create/Get the File Handle
154+
const fileName = 'session-log.txt';
155+
let fileHandle;
156+
165157
try {
166-
const existingHandle = await dirHandle.getFileHandle('session-log.txt', { create: false });
167-
const file = await existingHandle.getFile();
168-
existingLog = await file.text();
169-
// Count previous visits
170-
const matches = existingLog.match(/Visit #\d+/g);
171-
visitCount = matches ? matches.length + 1 : 1;
172-
log(`📖 Found existing log (${visitCount - 1} previous visits).`);
173-
} catch {
174-
log("📝 Creating fresh log...");
158+
fileHandle = await dirHandle.getFileHandle(fileName, { create: true });
159+
} catch (e) {
160+
throw new Error(`Could not create file handle: ${e.message}`);
175161
}
176162

177-
const timestamp = new Date().toISOString();
178-
const newEntry = `\n--- Visit #${visitCount} ---\nTimestamp: ${timestamp}\nFiles found: ${entries.length}\n`;
179-
180-
// Get handle for file
181-
const logHandle = await dirHandle.getFileHandle('session-log.txt', { create: true });
182-
183-
// --- SECOND FIX: Verify permission on the FILE handle too ---
184-
// Sometimes the directory has permission, but the new file handle needs it too.
185-
if ((await logHandle.queryPermission(options)) !== 'granted') {
186-
await logHandle.requestPermission(options);
163+
// --- THE FIX: Request Permission on the FILE handle explicitly ---
164+
// Android does not always inherit permission from the parent folder.
165+
if ((await fileHandle.queryPermission(options)) !== 'granted') {
166+
log("⚠️ Requesting permission for the specific file...");
167+
if ((await fileHandle.requestPermission(options)) !== 'granted') {
168+
throw new Error("File write permission denied.");
169+
}
187170
}
171+
// ------------------------------------------------------------------
188172

189-
const logWritable = await logHandle.createWritable();
190-
await logWritable.write(existingLog + newEntry);
191-
await logWritable.close();
192-
log(`✅ Updated session-log.txt (Visit #${visitCount})`);
193-
194-
// Create a unique timestamped file on each visit
195-
const uniqueFileName = `test-${Date.now()}.txt`;
196-
const uniqueHandle = await dirHandle.getFileHandle(uniqueFileName, { create: true });
197-
const uniqueWritable = await uniqueHandle.createWritable();
198-
await uniqueWritable.write(`Created during visit #${visitCount} at ${timestamp}`);
199-
await uniqueWritable.close();
200-
log(`✅ Created '${uniqueFileName}'`);
173+
log("Attempting to write...");
174+
const writable = await fileHandle.createWritable();
175+
176+
// Read existing content if possible to append (optional)
177+
const timestamp = new Date().toISOString();
178+
await writable.write(`\nLog Entry: ${timestamp}`);
179+
await writable.close();
201180

202-
log(`\n🎉 Demo complete! Reload page and select same folder to see persistence.`);
181+
log(`✅ Success! Wrote to ${fileName}`);
203182

204183
} catch (err) {
205184
if (err.name === 'AbortError') log("User cancelled.");

0 commit comments

Comments
 (0)