local storage variable scope per tab in google chr

2019-06-13 07:12发布

问题:

I wanted to store variables per tab scope. This same question was raised already and the suggestion was to use localStorage. But how to use localstorage to save associative arrays.

For example. A user is logging in a site. i want to create a variable to refer that user. like this the use will open many tabs and he will log in many sites. so i need to maintain the domain name and the user reference in localstorage. so if i use the username as a unique field then i can maintain an association with reference to the username and finally i will need to store these information in the database.

So how to maintain a data structure in google chrome extension. The above is just an example but it could be any case where we need the same variable name in various tabs with different values.

The documentation states to use json format. But still i want the users suggestion on this.

so any kind of response will he helpful like answers, suggestions, references and comments.

回答1:

It is not very clear from your question what do you mean by "tab scope".

If you really need the tab scope, that is store values for this specific tab even when user navigates to a new site, then you can take tabid as a key (only tab id is not persistent between browser restarts).

If you actually mean "domain scope" - then it comes "for free" with content scripts. If you use localStorage inside a content script it would store the value only for this domain. You only need to make sure your keys don't collide with potential site's keys as the site might use the same localStorage.

If you are just asking how to create a data structure that would have domain names as keys, then it could be something like this:

var data = {};
data["google.com"] = {
    username: "user1",
    password: "pass1"
};
data["yahoo.com"] = {
    username: "user2",
    password: "pass2"
};

//store it
localStorage["data"] = JSON.stringify(data);

//load
data = JSON.parse(localStorage["data"]);

//read google username
console.log(data["google.com"].username);