Save HTML locally with Javascript

后端 未结 10 1513
夕颜
夕颜 2020-12-03 01:19

I do know that Javascript cannot write data in the filesystem, for security reasons. I have often read that the only way to save data locally with Javascript is cookies or <

10条回答
  •  眼角桃花
    2020-12-03 02:09

    The canonical answer, from the W3C File API Standard:

    User agents should provide an API exposed to script that exposes the features above. The user is notified by UI anytime interaction with the file system takes place, giving the user full ability to cancel or abort the transaction. The user is notified of any file selections, and can cancel these. No invocations to these APIs occur silently without user intervention.

    Basically, because of security settings, any time you download a file, the browser will make sure the user actually wants to save the file. Browsers don't really differentiate JavaScript on your computer and JavaScript from a web server. The only difference is how the browser accesses the file, so storing the page locally will not make a difference.

    Workarounds: However, you could just store the innerHTML of the

    in a cookie. When the user gets back, you can load it back from the cookie. Although it isn't exactly saving the file to the user's computer, it should have the same effect as overwriting the file. When the user gets back, they will see what they entered the last time. The disadvantage is that, if the user clears their website data, their information will be lost. Since ignoring a user's request to clear local storage is also a security problem, there really is no way around it.

    However, you could also do the following:

    • Use a Java applet
    • Use some other kind of applet
    • Create a desktop (non-Web based) application
    • Just remember to save the file when you clear your website data. You can create an alert that pops up and reminds you, or even opens the save window for you, when you exit the page.

    Using cookies: You can use JavaScript cookies on a local page. Just put this in a file and open it in your browser:

    
    
    
    
    
    
    
      

提交回复
热议问题