Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you save/load a file via Javascript?

I want to create a very simple Javascript game using HTML5 (Canvas). But is it possible to save a simple .txt file and load a simple .txt file. I just need to store like the some simple integers. But I just want to know if javascript is allowed to save and load an external file?

Canvas

like image 440
Canvas Avatar asked Dec 25 '22 23:12

Canvas


2 Answers

Since html5 you can use the LocalStorage API. Nowadays almost all browsers support it:

// Check if it is supported in your browser
function supports_html5_storage()
{
      try
      {
        return 'localStorage' in window && window['localStorage'] !== null;
      }
      catch (e)
      {
        return false;
      }
}

//make use of it:
if( supports_html5_storage() == true )
{
   localStorage.setItem("myItem", "myData");
   var myDataString = localStorage.getItem("myItem");
   alert(myDataString);
}
like image 151
Alex Avatar answered Dec 28 '22 11:12

Alex


On Chrome, you can rely on the FileSystem API (for an intro take a look here). Probably other browsers will soon add support to it.

But, if your need is just "to store like the some simple integers" I would consider local storage.

like image 21
MatteoSp Avatar answered Dec 28 '22 13:12

MatteoSp