Can JavaScript save values without PHP? - javascript

I am begginer in programming. I have made these stopwatch for speedsolves using HTML and JavaScript.
Is there any way of saving my average solve time using Javascript only?
For instance i have some variable with loop:
var time=0;
if (true){
time++;
}
and after I close the HTML site, close the browser and turn off the computer, after opening the site again I want to get var time=value before closing the site
I'm familiar with PHP and databases, but I dont really want to use it, since I have to start a server.

If you just want to save data for your program to read later, you can use localStorage or sessionStorage. That is, localStorage.setItem('name', 'value') and localStorage.getItem('name') to read it. (They're the same, except sessionStorage gets cleared once the browser is closed, while localStorage doesn't.)
To actually save a file, you can do that only by triggering it to be downloaded. First you create a Blob with the content you want for the file, then you get an object URL for that Blob. Assign the URL to the href of a link with a "download" attribute and click it.
function saveFile(contents, name) {
const blob = new Blob([contents], {type: 'text/plain'});
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.download = name;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

Little more information will help, but, as you are talking of storage, you can use localstorage or sessionstorage within javascript to store the values.

For saving files on the local device, you can use FileSaver. But in your situation, an easier solution would be to take advantage of localstorage.
Note: From what I've found, LocalStorage won't work without a server. So if you want to store data and aren't using a server, FileSaver may work better. Then again, I don't know if it's possible to load the data in a file saved in FileSaver into javascript in a browser, especially if you don't have a server

Related

Is there any way of listening to download complete event after download starts using anchor tag?

The anchor tag click automates the download. Are there events attached to anchor tags that I can listen on ?
downloadMyFile(){
const link = document.createElement('a');
link.setAttribute('href', 'abc.net/files/test.ino');
link.setAttribute('download', `products.csv`);
document.body.appendChild(link);
link.click();
link.remove();
}
You will not be able to be notified by the client when the download completes this way.
You have 2 possible solutions, which mostly depends on the size of the file.
Option 1: Use an ajax call instead, you can stream the whole file in memory and then make the browser download it to a file (which will be instant). This means you have full view on the different download events.
// Get the content somehow
// and then make the browser download
window.location.href = window.URL.createObjectURL(content);
Option 2: Monitor it with the server. I'd suggest you add a UID to the request like:
link.setAttribute('href', 'abc.net/files/test.ino?uid='+myUID);
Have the server keep track of that request and store details with the UID, you can then have another route report the status of the request when provided the UID. The problem with this is that you'd have to poll every now and then to know if the download is finished.
Since we do not know exactly the use for your request it is hard to tell if there are other possibilities. But IMHO there is no real use for you to know if the file has completed downloading. I cannot figure out why you'd want that in the beggining. I see it is a CSV file, they usually are not that big and the download should be real quick... Unless it is because it takes a lot of time to start since it has to be generated before? In this case I suggest you see a popular question/answer I made a while back. How to display a loading animation while file is generated for download?
Edit: Since the file may be big and not fit in memory, you could write the file on disk using the FileSystem API. This way you will be able to pipe the stream coming from your request directly to the filesystem. Since a stream has a close event, you'll be able to know when it is all done.

Save/log HTML-Object into the file

Would it be possible to implement google-analystics like feature, which on page load would append the existing file located on the server with the current href? Is this achievable with js?
It is achievable with JS. but if you're thinking of doing it only with client side JS (presumption), that won't work, you need to have a server.
Only server side code would have the right access to add contents to a file on server.
It depends on what you need to obtain.
If you just want the user to save some data available on the shown page you can obtain a similar risult with a trick without server side code.
Here's a small example using jQuery:
var fileContent = "test";
var encodedUri = encodeURI(fileContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF
link.click(); // This will download the data file named "my_data.csv".
If, on the other hand, what you need is specifically file manipulation on the server then my suggestion is to use node.js or any other server technology to achieve such a result.

Write to a local JSON file from the browser [duplicate]

This question already has answers here:
Download JSON object as a file from browser
(14 answers)
Closed 7 months ago.
I'm trying to write to my local JSON file with javascript, I'm getting it from my HTML, changing it and want to write it back. I found how to read it from here but didn't find how to write to it back to the json file.
Note: I want to this without Node.js , 'fs' won't help..
My code to get the JSON file:
<script type="text/javascript" src="data.json></script>
<script type="text/javascript" src="javascrip.js"></script>
var mydata = JSON.parse(data);
Then I changed the value of the 'name', for example.
mydata["name"] = "NewName";
And then I want to send it back to the json file, update it.
I didn't really find any code to do so.
While you can't directly write to the file system due because of security constraints, you can trigger a save dialog to request the user to save the file. I use this function which works on all recent releases of the major browsers.
function download(data, filename) {
// data is the string type, that contains the contents of the file.
// filename is the default file name, some browsers allow the user to change this during the save dialog.
// Note that we use octet/stream as the mimetype
// this is to prevent some browsers from displaying the
// contents in another browser tab instead of downloading the file
var blob = new Blob([data], {type:'octet/stream'});
//IE 10+
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else {
//Everything else
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.href = url;
a.download = filename;
setTimeout(() => {
//setTimeout hack is required for older versions of Safari
a.click();
//Cleanup
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 1);
}
}
It is also worth mentioning that HTML5 spec has a download attribute, but it isn't currently supported on IE.
As ArtemSky said, You can't write to the local file system. The way to accomplish what you want to do would be to use a server that can write to it's local file system or a database or whatever.
So you would want to have the data stored somewhere, either a local file on the server, in the cloud, etc. or a database of some sort. Then you would set up an API on the server that you could call remotely to get the data via an XMLHttpRequest(XHR)
Then you would create another API method you can use to send the data back and then call that with the updated/new data.
Writing to the local file system is a security concern because if anyone who can write code could overwrite your system files otherwise. Preventing the ability to write to the local file system is the only way to make the web safe.
You can't write to file system due to security constraints of the browser.
You can do that only this way - https://stackoverflow.com/a/30800715/6149665

How to generate and prompt to save a file from content in the client browser? [duplicate]

This question already has answers here:
Create and save a file with JavaScript [duplicate]
(11 answers)
Closed 7 years ago.
I have a situation where I need to give my users the option to save some data stored locally in their client memory to disk. The current workaround I have is having a handler like this
(define-handler (download-deck) ((deck :json))
(setf (header-out :content-type) "application/json"
(header-out :content-disposition) "attachment")
deck)
which does exactly what it looks like. The client sends their data up, and saves the returned file locally.
This seems stupid.
Please, please tell me there's a better, simpler, cross-browser way to let a client save some local data to their disk with a file-save dialog box.
Every answer I read on the subject either says "no, you can't save files with javascript" or "yes, there's this one semi-documented piece of the Chrome API that might let you do it in three pages".
This "FileSaver" library may help. If you want it to be reasonably cross-browser, you'll also need this to implement the W3C Blob API in places it's not already implemented. Both respect namespaces, and are completely framework agnostic, so don't worry about naming issues.
Once you've got those included, and as long as you're only saving text files, you should be able to
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
Note that the first argument to new Blob has to be a list of strings, and that you're expected to specify the filename. As in, the user will see this file being downloaded locally, but won't be able to name it themselves. Hopefully they're using a browser that handles local filename collisions...
This is my code:
<a id='tfa_src_data'>Export</a>
document.getElementById('tfa_src_data').onclick = function() {
var csv = JSON.stringify(localStorage['savedCoords']);
var csvData = 'data:application/csv;charset=utf-8,'
+ encodeURIComponent(csv);
this.href = csvData;
this.target = '_blank';
this.download = 'filename.txt';
};
You can use various data types.
Depending on what you are trying to do exactly, the HTML5 local storage concept might help you.
So what is HTML5 Storage? Simply put, it’s a way for web pages to store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the web site, close your browser tab, exit your browser, or what have you. Unlike cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually). http://diveintohtml5.info/storage.html
There's also the Filesystem API (so far only implemented in Chrome AFAIK)
http://www.html5rocks.com/en/tutorials/file/filesystem/

How to save the window.URL.createObjectURL() result for future use?

I'm making an application in HTML5 where you choose a video file, and then the application plays it with the HTML5 video tag and the window.URL.createObjectURL(). The problem is that I want to save the data about this video in localStorage and play it again when the user uses my application, but as Mozilla MDN states about the results of this method:
Browsers will release these automatically when the document is unloaded
So is it possible to do what I'm trying to do? Or do the same thing without the window.URL.createObjectURL() but with something else?
I haven't used createObjectURL(), but if I understand correctly, it's essentially a temporary reference to a file or an in-memory object. If you want to save the actual video, it won't be useful, because the video itself will no longer be referenced by this pointer the next time the user visits the application.
I think you might be able to do this with a data: URL instead, as that URL actually includes the full data from the file. This example demonstrates using a FileReader to generate a data URL. I think you should be able to do this:
var reader = new FileReader();
reader.onload = function(e) {
var myDataUrl = e.target.result;
// do something with the URL in the DOM,
// then save it to local storage
};
reader.readAsDataURL(file);
Update: If you want to go up to 1GB, as you note in your comment, you'd probably be better served by the FileSystem API. This would require you to get the local file, save a copy of the file to persistent filesystem storage, and then use createObjectURL() to get a URL for the file copy. You still have a problem with disk space - you just added 1GB of duplicative file content to the user's filesystem - but I don't think it's possible to keep a persistent reference to a file outside of the browser sandbox otherwise.

Categories