March 13, 2024

Chrome extension: Get storage data

I share here a recent learning about Chrome extension programming and getting storage data.

Problem description

Common examples of using Chrome Storage Data, use the data directly in the function but does not return the storage data for further proceeding in another function.

Solution


This is the way to get the value of a key stored in the extension storage data:

const getObjectFromLocalStorage = async function(key) {
return new Promise((resolve, reject) => {
    try {
    chrome.storage.sync.get(key, function(value) {
        resolve(value[key]);
    });
    } catch (ex) {
    reject(ex);
    }
});
};

This isn't obvious at all to me with this resolve function.

Example

I made use of it in my Confluence Chrome Extension.

I build the searchUrl from the user input and the extension data like this:

async function getSearchUrl() {
    var searchQuery = document.getElementById('confluenceSearchQuery').value;
    var subdomain = await getObjectFromLocalStorage('subdomain');
    var spacekey = await getObjectFromLocalStorage('spacekey');
    var type = await getObjectFromLocalStorage('type');
    var rootUrl = `https://${subdomain}.atlassian.net/wiki`;
    var cql = Query2Cql(searchQuery,spacekey,type);
    return rootUrl + '/rest/api/content/search?cql=' + cql ;
}


No comments:

Post a Comment