The local storage in chrome is also used in HTML5 localstorage, the only difference is that the Chrome extension has its own localstorage, which belongs to this extension and not to a domain name. This is a good thing to do. Expand some of your data without being affected by the sites and domain names you visit.
Localstorage Foundation
Localstorage is a HTML5 feature, so some browsers don't necessarily support it, but we're talking about chrome extensions, so don't worry about it at all. If you want to use it on a Web page, check to see if it supports it.
This can be detected as:
if (window.localstorage) { console.log (' Support ');} else{ Console.log (' not supported ');}
Localstorage, like Memcache, is the storage type of key/value, so unless you save a string, it is stored in JSON form. After parsing the array, it is possible to use the value inside.
Additions and deletions to check:
Store/Modify Localstorage.name = ' only '; localstorage[' name '] = ' only ';//delete localstorage[' name '] = null; Delete a localstorage.clear (); Delete all//check var name = Localstorage.name;var name = localstorage[' name '];
Localstorage is not cross-domain, so the localstorage of different domain names are non-interference. For example, a value is stored on the jgb.com, and www.jgb.com cannot access it, and vice versa.
Localstorage in Chrome extensions
The localstorage in the extension is nothing different, just have a note point, content_script in the localstorage is stored in the corresponding domain name, so other domain name is inaccessible. The localstorage in Background_script is stored under the Chrome extension, so you can access it regardless of the domain name. This is important, and without this feature, there will be a lot less application scenarios for extensions.
View Localstorage
View the localstorage of the corresponding domain name
Right-click the review element and select
View the extended Localstorage
Open the Extensions screen to open the background page of your extension
Choose
Simple example
This example is simple, the extension will match www.jgb.cn and www.amazon.com, after opening two sites, a list and a form are displayed in the middle of the page, and the list is the name that was previously filled in, and the form can be filled in with your name in another name. List, you can delete one or all of the names. Simple also say, is an adding and deleting check. In this example, you can see that the contents of these stores can be read and manipulated in both www.jgb.cn and www.amazon.com, and are not subject to domain name restrictions.
First step: Create a Folder
The directory name is called Localstorage, the structure of the directory is basic
In addition to the Mainfest.json is necessary, other things can be in accordance with their own habits
Step two: Build the Mainfest.json file
The previous log has already talked about this file, so here is the direct content
{ "manifest_version": 2, "name": "To do the local storage of chrome extensions", "version": "0.1", "description": " A simple local storage example ", " background ": { " scripts ": [ " Include/jquery-1.11.0.min.js ", " scripts/ Background.js " ] }, " content_scripts ": [{ " matches ": [ " http://*.jgb.cn/* ", "/HTTP/ *.amazon.com/* " ], " CSS ": [" Css/common.css "], " JS ": [ " Include/jquery-1.11.0.min.js ", " Scripts/main.js " ]} ]}
If you are not familiar with this file, you can look together to do the Chrome extension "Basic Introduction"
Copy jquery to the include and then to the scripts directory to build Main.js and Background.js
Step three: Create the interface
Here we create a simple interface, in the right middle of the target site, showing a 500*300 floating layer, normal JS, the wording arbitrary
var main = { /** * Create interface * /Createhtml:function () { var _html = ' <div id= ' ls_box ' > ' + ' < H3> ' + ' locally stored local storage ' + '
The interface is roughly as follows
Fourth step: Send a message to backgroundThe method is simple.
/** * Send message to Background * @params straction string Execution method * @params dicdata dict data dictionary * @params callback function callback */SENDM Essageback:function (Straction, Dicdata, callback) { chrome.extension.sendMessage ({' Action ': straction, ' data '): Dicdata}, callback);},
Fifth step: Output the stored content to the page/** * Writes the existing data to the page */showlist:function (diclist) { if (!diclist | | diclist.length = 0) { $ ("#ls_list"). HTML (' <p > No data found </p> '); return; } Traverse object, build output HTML var _html = [' <ul> ']; for (var i in diclist) { _html.push (' <li><span class= "Ls_del" data-item= "' +diclist[i]+ '" >x</span > ' +diclist[i]+ ' </li> '); } _html.push (' </ul> '); $ ("#ls_list"). HTML (_html.join (")); Listen to delete _this.listendel ();},
Sixth step: Listening and savingA simple click event that sends the text content to background.js and then outputs the returned data to the page using the method above
/** * Monitor Save Event */listensave:function () { _this = this; $ ("#ls_save"). Click (function () { //Get message var strmessage = $.trim ($ (' #ls_message '). Val ()); if (!strmessage) { return false; } Notify background, save data _this.sendmessageback (' save ', {' message ': strmessage}, Function (response) { if ( Response.Status = =) { //Content output to page _this.showlist (response.data); $ (' #ls_message '). Val ('); } }) ;
Seventh step: Listening and deletingDelete and save the same way, just send to background request method different, normal JS operation, here do not post code, finally see Background.js Listening and return message
Eighth step: Background listening messages and returning/** * Listen for messages sent by Content_script */chrome.extension.onmessage.addlistener (function (Request, _, Sendresponse) {//Return data var Dicreturn; Read the stored data if (request.action = = ' list ') {//Read data from localstorage var strlist = localstorage[' list ']; if (strlist) {//Convert JSON string to object var diclist = Json.parse (strlist) Dicreturn = {' Status ': 20 0, ' data ': diclist}}else{dicreturn = {' status ': 404}}//Return information to Content_script Sen Dresponse (Dicreturn); }//Save if (request.action = = ' Save ') {//Content_script message var strmessage = Request.data.message ; Read data from localstorage var strlist = localstorage[' list ']; var diclist = []; if (strlist) {//Convert JSON string to Object diclist = Json.parse (strlist)} diclist.push (strmessage); localstorage[' list ' = Json.stringify (diclist); Dicreturn = {' status ': $, ' Data ': diclist}; To conTent_script return information sendresponse (Dicreturn); }//Delete if (request.action = = ' del ') {//Content_script message var strmessage = Request.data.message ; Read data from localstorage var strlist = localstorage[' list ']; if (strlist) {//Convert JSON string to Object diclist = Json.parse (strlist); Traverse the data to find the corresponding value for (var i in diclist) {if (diclist[i] = = strmessage) {//delete this value Diclist.splice (i, 1); }}//re-store localstorage[' list ' = Json.stringify (diclist); Return information to Content_script sendresponse ({' Status ': 200}); }else{sendresponse ({' Status ': 501, ' msg ': ' Delete failed, no data '}); } }})
Receive Content_script data, use request.data.message,data.message are defined by their own key, so want to pass anything, you can decide
The return value uses the Sendresponse () method, the content is an object, Content_script accepted, can be used directly, so there is the if (Response.Status = = 200) {} this way.
A simple local storage is like this, loaded into chrome or the same kernel browser, open www.jgb.cn or www.amazon.com, you can see the extension interface, save some data, refresh in two sites, you will find that the data are available.
SourceThis sample code: Https://github.com/onlyfu/localstorage
Get together and do the chrome extension "Local storage Localstorage"