You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8" /><metahttp-equiv="X-UA-Compatible" content="IE=edge" /><metaname="viewport" content="width=device-width, initial-scale=1.0" /><title>file save</title><style>#addText {
width:400px;
height:200px;
}
</style></head><body><h1>保存为本地文件并持续实时保存最新编辑的内容</h1><h4>text to save:</h4><div><textareaid="addText" name="addText">hello</textarea></div><buttononclick="saveFile()">1. start save</button><buttononclick="updateFile()">2. update</button><h4>file contents:</h4><pid="fileContent"></p><script>// https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStreamlet$textToAdd;let$fileContent;letnewHandle;constpickerOpts={types: [{description: "Text file",accept: {"text/plain": [".txt"],},},],suggestedName: "testFile",excludeAcceptAllOption: true,multiple: false,};asyncfunctionsaveFile(){// create a new handleconsole.log("showSaveFilePicker");newHandle=awaitwindow.showSaveFilePicker(pickerOpts);console.log("createWritable");// create a FileSystemWritableFileStream to write toconstwritableStream=awaitnewHandle.createWritable();updateFile();}asyncfunctiongetFileContents(){constfileData=awaitnewHandle.getFile();constres=awaitfileData.text();console.log("fileText: ",res);$fileContent.innerText=res;}asyncfunctionupdateFileContent(text){// create a FileSystemWritableFileStream to write toconstwritableStream=awaitnewHandle.createWritable();constdata=newBlob([text],{type: "text"});// write our fileawaitwritableStream.write(data);// close the file and write the contents to disk.awaitwritableStream.close();}asyncfunctionupdateFile(){consttext=$textToAdd.value;awaitupdateFileContent(text);awaitgetFileContents();}document.addEventListener("DOMContentLoaded",()=>{$textToAdd=document.getElementById("addText");$fileContent=document.getElementById("fileContent");});</script></body></html>
The text was updated successfully, but these errors were encountered:
背景:
最近发现drawio的一些功能很黑魔法。
比如首次创建一个文件,浏览器系统弹窗保存到本地,(到这为止都是常规保存文件的套路,很好实现)。
接下来,你在浏览器中继续绘制编辑你创建的图表,ctrol+S 保存之后,神奇的事情发生了,没有任何系统弹窗,最新的内容已经被静默地写入了首次创建的文件中。
这个行为是有点反直觉的,相当于在无感知的情况下,直接读写系统文件。浏览器一般不会给这么大的权限。
如何实现
如果有,也只能是浏览器提供的能力,于是,找到了这个
API: FileSystemWritableFileStream
https://developer.mozilla.org/en-US/docs/Web/API/FileSystemWritableFileStream
兼容性很不好:
思路:
代码:
The text was updated successfully, but these errors were encountered: