How do I access and read a local file from html+javascript page running locally

后端 未结 4 1435
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 12:26

I would like to write a small html file that would run locally and manipulate a small text file on my computer. My requirements are:

  • Text file sits in a direc
4条回答
  •  不知归路
    2020-12-09 12:54

    As is being discussed in Itay Moav's answer, writing to a local file with a local HTML file is perhaps going to be an issue without running in an elevated privilege mode and having additional Javascript capabilities (that allow you to save local files).

    However, accessing a local file from an HTML file is entirely possible. Below is some example code.

    mytext.txt

    My local text file
    

    local.html

    
    
    
    
    
    
    

    Hello World!

    This will make an alert 1 second after the html page loads (to allow the iframe to load first), and will contain the content within the mytext.txt file.

    Note, if it's plaintext, Firefox will wrap it with a PRE element, which is why I did firstChild. Also, note the use of the BASE element, which points to your local directory with your files.

提交回复
热议问题