Surjith S M
Surjith S M

Reputation: 6740

Easy way to get Local Storage Value to Content Script [Chrome Extension]

I want some data stored in Local storage to content script page. As its not directly available, I did it through chrome.runtime.sendMessage But I have several values and looks like this.

var username, apikey, openexchange, currency, locale;

chrome.runtime.sendMessage({method: "getLocalStorage", key: "username"}, function(response) {
  username = response.data;
});

chrome.runtime.sendMessage({method: "getLocalStorage", key: "apikey"}, function(response) {
  apikey = response.data;
});

chrome.runtime.sendMessage({method: "getLocalStorage", key: "openexchange"}, function(response) {
  openexchange = response.data;
});

chrome.runtime.sendMessage({method: "getLocalStorage", key: "currency"}, function(response) {
  currency = response.data;
});

chrome.runtime.sendMessage({method: "getLocalStorage", key: "locale"}, function(response) {
  locale = response.data;
});

When values increasing, this list will go further, Instead Is there any other method to wrap all value in just one function?

Any help would be appreciated.

Upvotes: 0

Views: 2232

Answers (1)

Xan
Xan

Reputation: 77482

I'll answer your direct question first (for educational purposes), and then provide a better way of doing it (not using localStorage at all).


You're the one writing the message listener that answers to the getLocalStorage method. So you can make it more versatile by sending more than one value per request.

Example:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  switch(message.method) {
    // ...
    case "getLocalStorage":
      if(message.key) { // Single key provided
        sendResponse({data: localStorage[message.key]});
      }
      else if(message.keys) { // An array of keys requested
        var data = {};
        message.keys.forEach(function(key) {data[key] = localStorage[key];})
        sendResponse({data: data});
      }
      break;
    // ...
  }
});

So now you can do:

chrome.runtime.sendMessage(
  {method: "getLocalStorage", keys: ["username", "apikey"]},
  function(response) {
    username = response.data.username;
    apikey = response.data.apikey;
  }
);

That said, you're reinventing the wheel. Chrome already has a storage API (called, surprisingly, chrome.storage) that addresses exactly this scenario: some kind of persistent storage available to both the extension pages and content scripts.

After adding the "storage" permission, you can do this:

chrome.storage.local.get(key, function(data) {
  // Use data[key]
});

chrome.storage.local.get([key1, key2], function(data) {
  // Use data[key1], data[key2]
});

chrome.storage.local.get({key1: default1, key2: default2}, function(data) {
  // Use data[key1], data[key2], and defaults will be used if not yet in storage
});

chrome.storage.local.set({key1: value1, key2: value2});

Upvotes: 2

Related Questions