文件系统访问 API createWritable() 方法在控制台内有效,但在脚本中无效

The File System Access API createWritable() method works inside console, but not in script

我目前正在为未来的项目处理文件系统访问 API,但我在以下行中使用 createWritable() 方法时遇到困难:

const writable = await fileHandle.createWritable();

当我触发它时,它给我错误:

TypeError: fileHandle.createWritable is not a function

然而,当我在控制台中 运行 这个确切的命令时,它完美地工作。

我使用的是 windows 10 如果相关的话。感谢您的帮助。

我将在下面包含我的相关 HTML 和 JS:

HTML:

<body>
    <h1>Hello There</h1>
    <button class="read-btn">Read</button>
    <textarea id="txt"></textarea>
    <button class="create-btn">Create</button>
    <button class="write-btn">Write</button>
</body>
<script src="./index.js"></script>

JS:

const readBtn = document.querySelector(".read-btn");
const createBtn = document.querySelector(".create-btn")
const writeBtn = document.querySelector(".write-btn");
const txt = document.querySelector("#txt");

// Store a ref to file handle
let fileHandle;
let contents;

// === READ FROM A FILE SYSTEM ===
readBtn.addEventListener("click", async () => {
    // open filepicker
    [fileHandle] = await window.showOpenFilePicker();
    // Returns a file object
    const file = await fileHandle.getFile();
    // Runs text method on returned file object to access text
    contents = await file.text();
    // Inputs contents into txt
    txt.value = contents;
});

// === WRITE TO FILESYSTEM ===

// Create a new file
async function getNewFileHandle() {
    const options = {
        types: [
            {
                description: 'Text Files',
                accept: {
                    'text/plain': ['.txt'],
                },
            },
        ],
    };
    const handle = await window.showSaveFilePicker(options);
    return handle;
}

// Save changes to disk
async function writeFile(fileHandle) {
    contents = txt.value;
    // Create a FileSystemWritableFileStream to write to.
    const writable = await fileHandle.createWritable();
    // Write the contents of the file to the stream.
    await writable.write(contents);
    // Close the file and write the contents to disk.
    await writable.close();
}

createBtn.addEventListener("click", getNewFileHandle)

writeBtn.addEventListener("click", writeFile)

根据 MDN 文档,window.showOpenFilePicker, FileSystemFileHandle, and FileSystemWritableFileStream 仅在安全上下文中受支持:

Secure context

This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

据我了解,VS Code 的“实时服务器”扩展无法满足此要求,但开发人员控制台可以。