Data local storage and download in the three--chrome extensions of the Chrome extension development

Source: Internet
Author: User

Directory:
    • 0--Overview of the 0.Chrome extended development (Gmail Accessory Management Assistant) series

    • One of the 1.Chrome extension development file structures for--chrome extensions

    • 2.Chrome Extended Development--chrome The script's operation mechanism and communication mode in the extension

    • 3.Chrome extension Development data local storage and download in the three--chrome extensions

    • A brief introduction to the four--gmail APIs for 4.Chrome extended development

    • 5.Chrome expansion development of the five--oauth2 understanding

    • The implementation of the six--gmailassist core features of the 6.Chrome extended development (including tips and considerations for the use of Gmail APIs)

    • The implementation of the seven--gmailassist complementary functions of 7.Chrome extended development (UI refinement, batch processing, multilanguage/internationalization/i18n)

    • 8.Chrome extended Development Eight--the bugs I've met, the detours I've been through

If you are interested in gmailassist, you can search for "Gmail assistant" in the Chrome store, or click here to visit the store directly to install the trial;
If you are interested in the source code of Gmailassist, you can view its source code on my github.

one, the data local storage commonly used two ways1. HTML5 's Localstorage

In the second article, the script in the Chrome extension can call all of H5 's APIs, and natural Localstorage is no exception. and Localstorage two forms: Sessionstorage and Localstorage can be considered as temporary and permanent storage: the latter is permanently on the hard disk, unless you remove in the program, or manually to delete, and the former, in Chrome, The live time of the locally stored data is equal to the lifetime of the corresponding label. (This is basically the only difference between the two)

Localstorage has the 5 methods of SetItem, getItem, RemoveItem, key, clear . Localstorage stores data in the form of Key/value, and the stored data types are strings . and is clear text, no encryption (so the user password what can not be saved AH).

Gmailassist development at the beginning, OAUTH2 certification began to make me confused, finally probably understand the principle, and feel very difficult to take JS to achieve a certified module. Chrome to the extension of the API, although there are OAuth2 related interfaces, but it does not feel very useful (now look back, just understand that there is a problem, but also lazy did not go to find good studious Google to give the example program). So from the Internet to find a ready-made wheel (this is this), the source code and instructions are very detailed, directly to use. Now there is a further understanding of the JS syntax, look back to see that the source has been clearly understood. Where the preservation of authorization tokens and other information are directly used localstorage, check the discovery is still very simple and useful. A cookie that can be easily understood as large. (The cookie allows 4k,localstorage to allow 5M).

You can access the data through the Localstorage API, or you can access it directly like a JS variable. Here is an example from the online excerpt:

//You can use Web Storage:localStorage.fresh like object literals= "vfresh.org";//set a key value      varA = Localstorage.fresh;//Get key value      Deletelocalstorage[' fresh '];//Delete a key value//or use its API:localStorage.setItem ("Fresh", "vfresh.org");//set a key valueLocalstorage.getitem ("fresh");//get a key valueLocalstorage.key (0);//Gets the name of the key that specifies the subscript (as if an array)Localstorage.removeitem ("fresh");//Delete a key valueLocalstorage.clear ();//Empty Storage

Pay attention to a little! Although the script can access the Localstorage interface, the access is still based on the current domain. This means that the content script and background script cannot access the same piece of local data through Localstorage! (The former domain is the current Browse page site, the latter is the extension of its own domain "Chrome://extension-id/", as the local folder Localstorage, from the name can be seen that the corresponding domain of these files are different)

Finally, Localstorage, since it is permanently stored locally, where is it on the hard disk? What if I want to look directly at the value stored in it?

Hard disk Location: C:\Users\your_username\appdata\local\google\chrome\user data\default\local Storage. Inside a file can be opened with SQLite view. One way to make it easier is to view and modify it directly in Chrome:

Open chrome–> Access chrome://extensions/(or from the browser's settings, find "extensions"), click on the "background page" in the information about the extension you want to see in resource Localstorage Can be viewed, double-click to modify. such as

2. Chrome.storage

Gmailassist is not involved in, it is not an example of detail, the details can be read official documents. Just talk about its similarities and differences with Localstorage:

With:

    • It can be thought that chrome.storage itself is an encapsulation of localstorage. So obviously, the latter features it all have.
    • It is also in plaintext.

Different: (I directly excerpt the Chinese document)

This API is particularly optimized for the storage needs of the Extender, which provides the same capabilities as the Localstorage API, but with several important differences:

    • User data can be automatically synced (using) via Chrome's sync feature storage.sync .
    • Your extender's content scripts can directly access user data without the need for background pages.
    • Even with discrete stealth behavior, the user's extender settings are preserved.
    • It is asynchronous and can do a lot of read and write operations, so it is faster than blocking and serializing the localStorage API.
    • User data can be stored as objects ( localStorage the API stores data as strings).
    • You can read the enterprise policy (usage and schema) that the administrator configures for the Extender storage.managed .
3. When to use which

respectively, the advantages and disadvantages of these two ways, the choice is very obvious.

Localstorage:

Advantages: can be used as normal JS variable, simple and convenient.

Disadvantage:

    1. Content script can not and background common access to a domain data, only through the second article mentioned in the SendMessage to Exchange data;
    2. Unlike Chrome.storage, which accesses data asynchronously, localstorage is slower than chrome.storage when it accesses data slightly;
    3. Unable to access the data in Incognito mode;
    4. If some of the setup parameters of the Extender are saved locally with localstorage, the user cannot get a synchronous backup of this setting on the other computer, and chrome.storage can achieve this synchronization by setting the sync.
    5. Stored data is a string, if you need an object, you also need to manually turn around (although it is not troublesome ...) )。

Chrome.storage:

Advantage: (as opposed to the above disadvantage)

    1. Content script can use the. Storage interface to access data for the Extender's domain;
    2. asynchronous access, fast;
    3. The data can still be accessed in Incognito mode;
    4. Sync domain data is automatically synced when you connect to Chrome;
    5. Data of the object type can be stored directly.

Disadvantage: Asynchronous access results in the need for a callback function to process the obtained data, which cannot be accessed as directly as a JS variable as localstorage.

4. There is also a way to Web SQL

I didn't use it, I didn't mention it much. Having looked at something related to it, my feeling is that it is not appropriate for the development of Gmailassist, which does not have much local storage, and there is no extension that needs to perform complex queries locally.

Second, download

To initiate a file download, the Chrome extension must be done through the chrome.downloads API. There's nothing to understand, just take a good look at the documentation and get it all figured out. I try to write and I feel like I can't write anything but a copy. So just give me a link to this ebook chapter that I think has been clearly written.

Combined with gmailassist say, my download feature is implemented.

The requirement is that you want the user to be able to select the items you want to download in the list of attachments for bulk download.

The implementation is: through a table, each row gives a check box, and then each check box corresponding to the attachment (this address is generated by the Gmail API to get the message information in the PartID to generate, more specific I will say in the Gmail API) as a parameter, to invoke Chrome.downloads.download method. But PartID is captured in content script and is naturally spelled out in content script, but unfortunately not included in the Chrome.* API that the content script can invoke. Downloads. What's the whole? Who can tune this API to write the logic of the download, and then pass the URL to it through SendMessage.

So I have the following code in my background.js:

Chrome.runtime.onMessage.addListener (function  (message, sender, Sendresponse) {    if (message.url) {        chrome.downloads.download ({            url:message.url,            ' uniquify ',             false         });     Else if  (...) {        ... // other logic that must be processed in the background     }});

Of course, if you have to declare the permissions in Manifest.json to use the download interface:

{        ...        " Permissions ": [          " Downloads "        ],        ...}

Then in the Content.js:

Btndownload.onclick =function () {       varID2 = 0;//Id2 is used to traverse the list of attachments to find out who is selected by the user and need to download         for(id2 = 0; id2 < visiblerows.length; id2++) {            varChebox = document.getElementById ("Checkbox_" +id2); if(chebox.checked = =true) {                varurl = ' https://mail.google.com/mail/u/0/?ui=2&ik=undefined&view=att&th= ' + visiblerows[id2].split (' |-| ') [6] + ' &attid=0 ' + Vis iblerows[id2].split (' |-| ') [7] + ' &AMP;DISP=SAFE&AMP;ZW ';//that's the spelling of the word.Chrome.runtime.sendMessage ({Url:url},function(response) {...//There are some things you can do about the returned response, but I don't need it here .                }); }        } };

This completes the download.

Data local storage and download in the three--chrome extensions of the Chrome extension development

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.