Get together and do the chrome extension "Local storage Localstorage"

Source: Internet
Author: User
Tags to domain

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 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": "Working together for 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

varMain = {        /** * Create interface*/createhtml:function(){        var_html = ' <div id= ' ls_box ' > ' + ' ; $(' Body '). Append (_html); }}

The interface is roughly as follows

Fourth step: Send a message to background

The method is simple.

/** *function(straction, Dicdata, callback) {    Chrome.extension.sendMessage ({' action ': straction, ' data ': Dicdata}, callback);},
Fifth step: Output the stored content to the page
/** * Write the existing data on the page*/showlist:function(diclist) {if(!diclist | | diclist.length = = 0){        $("#ls_list"). HTML (' <p> no data found </p> '); return; }    //traversing objects, building output HTML    var_html = [' <ul> '];  for(varIinchdiclist) {_html.push (' <li><span class= ' Ls_del "data-item=" ' +diclist[i]+ ' ">X</span> ' +diclist[i]+ ' </li> '); } _html.push (' </ul> '); $("#ls_list"). HTML (_html.join (' ')); //Listener Delete_this.listendel ();},
Sixth step: Listening and saving

A 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 Events*/Listensave:function() {_this= This; $("#ls_save"). Click (function(){        //Get Message        varstrmessage = $.trim ($ (' #ls_message ')). Val ()); if(!strmessage) {            return false; }        //notify background, save data_this.sendmessageback (' save ', {' message ': strmessage},function(response) {if(Response.Status = = 200){                //output content to a page_this.showlist (Response.data); $(' #ls_message '). Val (');    }        }); });},
Seventh step: Listening and deleting

Delete 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    varDicreturn; //Read saved data    if(request.action = = ' List '){        //reading data from the Localstorage        varstrlist = localstorage[' list ']; if(strlist) {//to convert a JSON string to an object            varDiclist =json.parse (strlist) Dicreturn= {' Status ': $, ' data ': Diclist}}Else{Dicreturn= {' Status ': 404}        }        //return information to Content_scriptSendresponse (Dicreturn); }    //Save    if(Request.action = = ' Save '){        //Content_script came to a message        varstrmessage =Request.data.message; //reading data from the Localstorage        varstrlist = localstorage[' list ']; varDiclist = []; if(strlist) {//to convert a JSON string to an objectDiclist =json.parse (Strlist)} diclist.push (strmessage); localstorage[' list '] =json.stringify (diclist); Dicreturn= {' Status ': $, ' data ': Diclist}; //return information to Content_scriptSendresponse (Dicreturn); }    //Delete    if(request.action = = ' del '){        //Message from Content_script        varstrmessage =Request.data.message; //reading data from the Localstorage        varstrlist = localstorage[' list ']; if(strlist) {//to convert a JSON string to an objectDiclist =Json.parse (strlist); //traverse the data to find the corresponding value             for(varIinchdiclist) {                if(Diclist[i] = =strmessage) {                    //Delete this valueDiclist.splice (i, 1); }            }            //Re-storagelocalstorage[' list '] =json.stringify (diclist); //return information to Content_scriptSendresponse ({' 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.

Source

This sample code: Https://github.com/onlyfu/localstorage

Get together and do the chrome extension "Local storage Localstorage"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.