Open file from local system and save changes to file that opened
in this example we are try with txt file:
<button onclick="openfile()" title="Open txt file">Openfile</button>
<button onclick="savefile()" title="Open txt file">Save file</button>
<textarea id="editor" style="width: 100%; height: 200px;" placeholder="open file..."></textarea>
<script>
let editor = document.getElementById("editor");
const openfile = async () => {
[fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
const contents = await file.text();
editor.value = contents;
}
const savefile = async () => {
const writable = await fileHandle.createWritable();
await writable.write(editor.value);
await writable.close();
}
</script>
Ctrl + s
add this code as follows:
window.addEventListener("keydown" , e => { if (e.key === 's' && e.metaKey) { e.preventDefault(); savefile(); } });
return to first exemple:
let editor = document.getElementById("editor"); const openfile = async () => { [fileHandle] = await window.showOpenFilePicker(); const file = await fileHandle.getFile(); const contents = await file.text(); editor.value = contents; } const savefile = async () => { const writable = await fileHandle.createWritable(); await writable.write(editor.value); await writable.close(); } window.addEventListener("keydown" , e => { if (e.key === 's' && e.metaKey) { e.preventDefault(); savefile(); } });

© 2025 Manajmnt code
Comments
Post a Comment
message