简体   繁体   English

如何从Chrome本地存储中保存和检索关联的数组

[英]How can I save and retrieve associated array from chrome local storage

How can I store associated array in chrome local storage, and retrieve that in the same format? 如何将关联的数组存储在chrome本地存储中,并以相同的格式进行检索? I want to save "identityKeyPair", which is in the form 我要保存“ identityKeyPair”,其形式为

identityKeyPair -> { pubKey: ArrayBuffer, privKey: ArrayBuffer } identityKeyPair-> {pubKey:ArrayBuffer,privKey:ArrayBuffer}

I tried the below things. 我尝试了以下方法。 But not working out. 但没有解决。 I am getting [Object Object] on trying to retrieve it. 我正在尝试检索[Object Object]。

Saving to local storage 保存到本地存储

chrome.storage.sync.set({'identityKeyPair': JSON.stringify(identityKeyPair)}, function() {
          alert('identityKeyPair saved');
        });

Trying to retrieve 尝试检索

chrome.storage.sync.get(["identityKeyPair"], function(items){
  if (items.identityKeyPair) {
alert(JSON.parse(items.identityKeyPair).pubKey);
  }

Please follow these steps while you are using chrome.storage.sync 使用chrome.storage.sync时,请按照以下步骤chrome.storage.sync

  1. Declare storage permissions in your manifest. 在清单中声明存储权限。

manifest.json manifest.json

{
  "manifest_version": 2,

  "name": "Storage",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",
  "icons":{
"256":"img/icon.png"
    },
  "permissions": [
    "storage"
  ],
  "app": {
    "launch": {
      "local_path": "options.html"
    }

  },
   "background": {
    "scripts": ["js/app/background.js"]
  }

}
  1. Reload your App in chrome://extensions so that your manifest.json gets updated in your browser. chrome://extensions重新加载您的应用,以使manifest.json在浏览器中得到更新。

  2. Follow the exact syntax of chrome.storage.sync with its callback function. 遵循chrome.storage.sync的确切语法及其回调函数。

Sample.js Sample.js

$(".thing").click(function() {
      chrome.storage.sync.set({"myKey": "testPrefs"},function(){
       alert("object stored");
})
    chrome.storage.sync.get("myKey",function(obj){
        alert(obj.myKey);
    })
});

This will work for you. 这将为您工作。 I tested this code in my chrome app. 我在Chrome应用中测试了此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM