FileAccessAPI demo
// ==UserScript==
// @name FileAccessAPI demo
// @namespace https://bbs.tampermonkey.net.cn/
// @version 0.1.0
// @description try to take over the world!
// @author You
// @match https://bbs.tampermonkey.net.cn/
// ==/UserScript==
(function () {
'use strict';
let dirHandle;
async function getFile() {
// open directory picker
dirHandle = await window.showDirectoryPicker({ mode: "readwrite" });
console.log(dirHandle);
}
const button = document.createElement('button');
button.innerText = "点我授权目录";
document.body.firstChild.after(button);
button.addEventListener('click', async function () {
getFile();
});
getFile();
const button2 = document.createElement('button');
button2.innerText = "点我读取目录&写点东西";
document.body.firstChild.after(button2);
button2.addEventListener('click', async function () {
// 读取目录
for await (const item of dirHandle.values()) {
console.log(item)
}
// 写文件
const fileHandle = await dirHandle.getFileHandle("hello-world.txt", { create: true });
const writable = await fileHandle.createWritable();
await writable.write("Hello World!");
await writable.close();
});
})();