Using local storage in Chrome as a DB?

2019-04-14 23:36发布

I'm having success setting/getting data via local storage. Essentially I'm building a reminder extension/geo-location that allows a user to save the url, their geo-location, and title of the url. 3 pieces of data needs to be saved each time. I'm using JSON.stringfy and JSON.parse to do this. Here is where I'm stuck:

  1. How do I save each entry from the user without writing over the last entry in local storage? Each time I save the url it doesn't save it in local storage as a new entry. It just keeps saving over the last entry.
  2. Over time, the user will probably have dozens of entries, but I want to be able to update specific entries in the dataset. (e.g. if [one of the stored urls in the dataset] == [the url that is presently in the browser url $(location).attr('href');] then do something.

I started with something very simple. Saving and getting data is working.

//save my data
var mydata = { urlTitle: myTitle, myurl: currentUrl, urlLoc: geoUrl }​​​​​​​;
localStorage.setItem("mydata", JSON.stringify(mydata));

//get my data
var returnData = localStorage.getItem("mydata");
mydata = JSON.parse(returnData);

Just need a bit of guidance.

1条回答
男人必须洒脱
2楼-- · 2019-04-15 00:36

localStorageDB does exactly this.

// Setup database
var lib = new localStorageDB("library", localStorage);
lib.createTable("books", ["code", "title", "author", "year", "copies"]);

// Insert rows
lib.insert("books", {code: "B001", title: "Phantoms in the brain", author: "Ramachandran", year: 1999, copies: 10});
lib.commit();

// Query rows
lib.query("books", {author: "ramachandran"});

Disclosure: I authored the library

查看更多
登录 后发表回答