Using IndexedDB for Save-Game Data

I initially used localStorage for storing they player’s save-games. That works, but has a size limit of about 5MB (although it’s hard to find consistent documentation on this). Ladon’s save data can grow well beyond that, so I started looking at other options.

My first thought was to have a “download file” button. That’s fairly easy to do by using a hidden <a href="data..."> tag. Loading the saved data is a little tricky because it requires a hidden file upload form. You’ll probably want to reload the page when you upload the data, which means having to pass all that data (megabytes of it) through a POST method or some other server-side magic. That approach starts to get pretty complicated and not great for performance. Another thing I really dislike about this approach is that browsers don’t allow the user to choose a filename. They just give you the “What do you want to do with this file – open it or save it?” dialog box. You have to explain to the user “Make sure you click ‘save file’ in the dialog… blah blah…”

You can’t choose to overwrite the older saves, either. So after playing for a while, you end up with a folder of downloaded saves like this:

LadonSaveGame(8).txt
LadonSaveGame(7).txt
LadonSaveGame(6).txt
LadonSaveGame(5).txt
LadonSaveGame(4).txt
LadonSaveGame(3).txt
LadonSaveGame(2).txt
LadonSaveGame(1).txt
LadonSaveGame.txt

I am a fanatical Cookie Clicker player, and it has exactly this same problem. My “Downloads” folder fills up every few days and I have to delete old files.

So, instead, I did some research into IndexedDB, which is a simple database built into the browser. It’s hard to nail down what the size limit actually is, but it seems to be in the gigabyte range. It’s a little more complex than localStorage but easy enough if all you want to do is load/save a big JSON object. You can just do “get” and “put” operations.

The one huge danger here is that the browser can just choose to clear your database at any time. Supposedly, that won’t happen unless your hard drive is running out of space. But it could be really upsetting to the user if their save-game just vanishes without warning. The safest option is probably to use IndexedDB but also provide the option to do a manual backup by downloading your save. The thing is, most people won’t bother to make the backup, even if you warn them that they might unexpectedly lose their data.

I think the all-around-best solution is the upcoming File System API. That will allow us to just write save-game files to the disk.

Check out version 0.5.0.1 on the releases page. You won’t notice the difference, but the game is now saved in IndexedDB. You can see the data in the browser console if you’re curious.

Leave a Reply

Your email address will not be published.