簡體   English   中英

獲取本地存儲值到內容腳本[Chrome擴展程序]的簡便方法

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

我希望一些數據存儲在本地存儲到內容腳本頁面中。 由於它不直接可用,我通過chrome.runtime.sendMessage但是我有幾個值,看起來像這樣。

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;
});

當值增加時,此列表將更進一步,相反,是否還有其他方法可以將所有值包裝在一個函數中?

任何幫助,將不勝感激。

我將首先回答您的直接問題(出於教育目的),然后提供一種更好的方法(根本不使用localStorage )。


您是編寫getLocalStorage方法的消息偵聽器的人。 因此,您可以通過為每個請求發送多個值來使其具有更多用途。

例:

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;
    // ...
  }
});

現在,您可以執行以下操作:

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

也就是說,您正在重新發明輪子。 Chrome已經有一個存儲API( 令人稱奇的chrome.storage ),可以精確地解決這種情況:擴展頁面和內容腳本均可使用的某種持久性存儲。

添加"storage"權限后,您可以執行以下操作:

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});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM