When utilizing the File System Access API, the createWritable() method functions perfectly within the console environment but encounters issues when executed

I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code:

const writable = await fileHandle.createWritable();

Every time I try to execute it, I keep getting this error message:

TypeError: fileHandle.createWritable is not a function

Oddly enough, when I run the same command in the console, it works without any problems.

Just to provide some context, I'm working on Windows 10. Any assistance would be greatly appreciated. Thank you!

Below are the relevant snippets of my HTML and 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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting a misformatted JSON string that lacks proper double quotes in Java Script

{ DataError: { user_id: [ [Object] ] } } I want to transform this string into JSON structure like below: { "DataError": { "user_id": [ [Object] ] } } Is there a potential method to achieve this outcome from incorrectly formatted JSON string? ...

The issue with dynamic sizing in React and Tailwind is that it does not consistently work with arbitrary sizes. Some sizes do not appear properly, causing items to

In this code snippet, I am attempting to create a circle component of dynamically sized using html div and Tailwind CSS w-[diameter] & h-[diameter] attributes in a create-next-app@latest project. However, the circle fails to render properly with certa ...

The scroll function within the inner div is malfunctioning on the Firefox browser

Scrolling within inner div is not functioning properly in the Mozilla Firefox browser. However, it works seamlessly in Chrome. Is there a workaround for enabling scrolling in Firefox? Here is the fiddle link: http://jsfiddle.net/t6jd25x9/2/ body { f ...

"Threads snap as soon as they begin to be put to use

Encountering an issue with the command yarn run serve, the error log states: $ vue-cli-service serve INFO Starting development server... 10% building 2/2 modules 0 activeevents.js:173 throw er; // Unhandled 'err ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

Guide to using JavaScript to populate the dropdown list in ASP

On my aspx page, I have an ASP list box that I need to manually populate using external JavaScript. How can I access the list box in JavaScript without using jQuery? I am adding the JavaScript to the aspx page dynamically and not using any include or impor ...

"Trouble with jQuery not being triggered when there is a string in

New to the world of MVC and diving into jQuery for the first time, I am faced with a challenge. My goal is to populate text boxes in a partial view using jQuery that is placed within the parent view. Here are the relevant sections of the parent view: @ ...

Can you explain the significance of the file:workspaces in the package dependencies?

Attempting to utilize npm 7 workspaces feature "workspaces": { "packages": [ "packages/apps/*", "packages/components", ], Upon installation, my package.json includes: "dependencies": ...

Designing an interactive header interface using React and Material UI

My header.jsx file contains the following code: // Default Import Statements var Login = require(login.jsx) const HeaderComponent = React.createClass({ getInitialState () { return { loggedIn: false, }; }, render() { return ( ...

Mobile Image Gallery by Adobe Edge

My current project involves using Adobe Edge Animate for the majority of my website, but I am looking to create a mobile version as well. In order to achieve this, I need to transition from onClick events to onTouch events. However, I am struggling to find ...

Rendering a Pop-up for a Single Array Item Retrieved from an API in ReactJS

Apologies if my wording is unclear, this is my first question, and I'm relatively new to JS/React... I have successfully mapped through an array from an API call and displayed the necessary information. How can I display a popup for a single element ...

Exploring Vue and Nuxt JS: What Causes the Issue of Unable to Create the Property 'display' on the String 'bottom:30px;right:30px;'

this piece of code is designed for a component that allows users to jump back to the top of the page. However, after refreshing the page, it stops working and throws an error. The project uses the Nuxt and Vue framework. Can anyone identify the reason behi ...

The login button has dual functionality, redirecting users to different pages based on their login status. First-time logins will be directed to an agreement page, while returning users will be

During my testing of login functionality, I follow these steps: Enter username Enter password Click on the login button Verify if the agreement page is displayed This is how my Page Object Model (POM) for the login page looks like: class loginPage { ...

What is the best way to verify the existence of a remote image in AngularJS?

Here is an example of the code snippet : <div ng-repeat="u in users"> <!--An active URL will always be received --> <div ng-if="u.imageUrl"> <!--Check if the provided URL is active--> <!--Content only visible if image url is li ...

Creating a Dynamic Bar in Your Shiny Application: A Step-by-Step Guide

Currently, I am developing a unique crowd funding shiny app to monitor donation amounts. Is there a method available that allows for the creation of a reactive bar in Shiny? Alternatively, is it feasible to achieve this using html, css, and javascript? He ...

Setting the outcome of an Ajax call as a global variable in JavaScript

I have a method that uses AJAX to request data and returns a JSON string containing Tokens records. I am trying to store this result in a global variable named 'tokens' so I can access it in other functions. After assigning the result to the &ap ...

Using the @ symbol in jQuery within an MVC framework can be achieved by first ensuring that

I'm attempting to incorporate the @ symbol into a JavaScript if condition, but I keep receiving an error. if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) { alert('yes'); ...

Send the content written in summernote to an AJAX request

I'm having trouble with ajax and javascript, so I need to ask for assistance. Within a form, I have an editor (using summernote editor). <div id="summernote">summernote text</div> After that, I use this ajax function to send the form dat ...

"Removing an item from an array stored in localstorage: A step-by-step guide

I need to remove an object from an array and also delete it from local storage. I have attempted to use the splice method but am struggling with how to implement it correctly. Below is the code that I have tried: var details = []; function addEntry() ...

Using a Firebase token repeatedly: simple steps to follow

I have integrated Firebase Web Notification using Firebase SDK. The implementation process involves two files: a) generate-token.js and b) firebase-messaging.sw.js To get access token, permission is requested by calling requestPermission function. Upon ...