-1

I have some javascript that I use to write a text file when the user leaves the page. Here is the function:

function handleBrowserCloseButton() { 

get_text();   

var textToWrite = array;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = "windows.txt"

var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
downloadLink.click();
}

This works well. The only problem is the name of the file is constant - "windows.txt". What this means is that every time the user leaves the page the file written is "windows(n).txt" where n increases in value by one each time.

Is there a way to have javascript replace the file "windows.txt" instead of creating a new file each time?

Rob
  • 189
  • 2
  • 11

2 Answers2

0

No, if you are using browser's JavaScript, for security reasons, you can not change the existed files on your local machine.

But you may try to use localStorage if the file is not too big.

 // Store
 localStorage.setItem("key", "value");

 // Retrieve
 localStorage.getItem("key");

About the size of localStorage: What is the max size of localStorage values?

The key-value pairs in localStorage will be stored in browsers and according to the implementations of each browsers.

Community
  • 1
  • 1
Andre Lee
  • 1,180
  • 1
  • 11
  • 13
0

Based on the helpful comment of Patrick Evans, I switched from trying to write out a local text file to storing the data in localStorage.

Rob
  • 189
  • 2
  • 11