简体   繁体   中英

Cannot access browser local storage from add-on in firefox

I have stored one array in memory using following code using id.js file:

var ids = ["a", "b"];
var obj= {};
var loc = '0';
obj[loc] = ids.toString();
    browser.storage.local.set(obj);
    browser.storage.local.get(loc,function(result){
      console.log(result);
      //console output = {v1:'s1'}
    })

on addon i have this one html file as:

<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="popup.css"/>  


  </head>

<body>

<button class="download">Download</button>
<script type="text/javascript" src="popup.js"></script>
</body>

</html>

and popup.js as:

Components.utils.import("resource://gre/modules/Console.jsm");

var downloadBtn = document.querySelector('.download');
downloadBtn.addEventListener('click', downloadUser);

function downloadUser() {
    browser.storage.local.get("ids",function(result){
        var filename = "ids.txt";
        var text = result;
        alert(text);
        var pom = document.createElement('a');
        pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        pom.setAttribute('download', filename);

        if (document.createEvent) {
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            pom.dispatchEvent(event);
        }
        else {
            pom.click();
        }

    })
}

from popup.js is for getting the data from memory and then downloading it. But nothing is working in it.

here is the manifest file:

{
  "manifest_version": 2,
  "name": "AAA",
  "version": "1.0",
  "icons": {
    "48": "icons/border-48.png"
  },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["id.js", "popup.js"]
    }
  ],

   "permissions": [
    "storage"
  ],


    "browser_action": {
    "default_icon": {
     "48": "icons/border-48.png"
    },
    "default_title": "Id",
    "default_popup": "popup.html"
  }  

}

You set local storage using:

var loc = '0';
obj[loc] = ids.toString();
browser.storage.local.set(obj);

That means key to ids is 0 . You should use 0 as key to get it:

browser.storage.local.get({0:""},function(result){
    alert(JSON.stringify(result));
}

If you want to use ids as key, you should set it by:

obj["ids"] = ids.toString();
browser.storage.local.set(obj);

And get it by:

browser.storage.local.get({ids:""},function(result){
    alert(JSON.stringify(result));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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