Siki-Siki
Siki-Siki

Reputation: 113

Get more value from chrome.storage.sync.get

I would like to send an ajaxrequest, but first i have to get 3 value from chrome.storage.sync. This is an async function so i cant push it a variable and send the request.

i would like to do something like this (i know this is async, so i can't get the variable)

var a;
var b;
var c;

chrome.storage.sync.get("a", function(callback){
    a = callback.a;
});
chrome.storage.sync.get("b", function(callback){
    b = callback.b;
});
chrome.storage.sync.get("c", function(callback){
    c = callback.c;
});

function sendwithajax (url) {
        var info = {
            aa: a,
            bb: b,
            cc: c
        }

        return $.ajax({
            method: "GET",
            url: url,
            data: {data:info}
        })
}

Upvotes: 2

Views: 1735

Answers (2)

Troy Wray
Troy Wray

Reputation: 1018

Firstly, as @Deliaz pointed out, you can get all 3 parameters in one shot. You should also combine this with the ability to set defaults should those items not yet exist.

Also, somewhere in your code you would need provision to wait until the stored values have been returned because calls to storage.get are asynchronous. As it is, the code above would finish and continue with the next line before a, b or c have been retrieved. If you were expecting the next line to be

sendwithajax("some url");

it wouldn't work because a, b and c would not be available yet.

This is in general how you should structure your code:

function sendDataWithAjax(url) {
    chrome.storage.sync.get({"a": "", "b": "", "c": ""}, function (result) {
        var info = {
            aa: result.a,
            bb: result.b,
            cc: result.c
        };
        sendwithajax(url, info, process);
    });
}

function sendwithajax(url, info, callback) {

    $.ajax({
        method: "GET",
        url: url,
        data: {data: info},
        success: callback
    });
}

function process(serverResult) {

}

Note you can't get the result of the ajax call by your method either:

return $.ajax()

would return something about the ajax object, not the result. The result will also come back asynchronously, so in my code, function process will only be called after the data has been retrieved from storage and the ajax call has completed.

Upvotes: 2

Denis L
Denis L

Reputation: 3292

If you look closer at the StorageArea docs you will find that the first parameter might be:

string or array of string or object

A single key to get, list of keys to get, or a dictionary specifying default values (see description of the object). An empty list or object will return an empty result object. Pass in null to get the entire contents of storage.

So that means you can pass an array of string keys you need:

chrome.storage.sync.get(["a", "b", "c"], function(items){
    a = items.a;
    b = items.b;
    c = items.c;
});

In order to get all stored values, just pass null.

Upvotes: 1

Related Questions