Chrome extensions : cannot get back my stored data

2019-09-06 03:10发布

问题:

I try to save datas from my chrome extension :

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      chrome.storage.sync.set(request, function() {
        chrome.storage.sync.get(null, function(datas) {
            console.log(datas);
            console.log("background");
            sendResponse(datas);
        })
      });
    }
 );

Each time I'm receiving a message, I store this message, and I send all saved item as a response.

In this code, in the console, background is displayed but datas is empty (Nothing in the console)

When I console.log(request) my json objet is ok.

In this code, why datas is empty ?

Thanks

回答1:

You should provide/request a key when you store/retreive your data:

chrome.storage.sync.set({
   MyRequest: request
}, function(){
   chrome.storage.sync.get{
       MyRequest: null
   }, function(data){
      console.log(data.MyRequest);
   }
});

Also make sure you have permission "storage" declared in your manifest file:

"permissions": ["storage"]