Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Chrome Extensions“;铬.存储.本地“;数据更新故障_Javascript_Google Chrome_Web_Google Chrome Extension - Fatal编程技术网

Javascript Chrome Extensions“;铬.存储.本地“;数据更新故障

Javascript Chrome Extensions“;铬.存储.本地“;数据更新故障,javascript,google-chrome,web,google-chrome-extension,Javascript,Google Chrome,Web,Google Chrome Extension,我正在开发一个chrome扩展,我需要使用本地存储将数据从选项页面发送到后台scritps 选项页脚本: function addToStorage(key, val){ let obj = {}; obj[key] = val; chrome.storage.local.set( obj, function() { if(chrome.runtime.lastError) { console.error( "E

我正在开发一个chrome扩展,我需要使用本地存储将数据从选项页面发送到后台scritps

选项页脚本:

function addToStorage(key, val){
    let obj = {};
    obj[key] = val;

    chrome.storage.local.set( obj, function() {
      if(chrome.runtime.lastError) {
        console.error(
          "Error setting " + key + " to " + JSON.stringify(val) +
          ": " + chrome.runtime.lastError.message
        );
      }
    });
}
背景:

chrome.storage.local.get('code', function(code) {
    ... with code.code ...
});
例如: 现在
chrome.storage.local
code
值为
abcd

我正在从选项页脚本执行添加到存储('code','1234') 之后,后台脚本值
code
只有在我手动点击chrome扩展页面上的“更新”时才会改变


如何在后台脚本中自动获取实际数据?

后台脚本按原样启动时只检查一次

更新本地存储后,可以将选项脚本中的mesage传递给后台脚本,并将其用作检查存储的触发器

试试这个:

选项页

function addToStorage(key, val){
    let obj = {};
    obj[key] = val;

    chrome.storage.local.set( obj, function() {
      if(chrome.runtime.lastError) {
        console.error(
          "Error setting " + key + " to " + JSON.stringify(val) +
          ": " + chrome.runtime.lastError.message
        );
      }
      chrome.runtime.sendMessage({status: "Storage Updated"}, function (responce) {
          console.log(responce);
      })
    });
}
背景页:

chrome.runtime.onMessage.addListener(
    function (request, sender, responce) {
        if (request.status === "Storage Updated") {
            chrome.storage.local.get('code', function(code) {
                // ... with code.code ...
            });

            sendResponce({status: "Update Recieved"});
        }
    }
);

希望这有帮助,这里的消息传递文档:

您当前的背景脚本错误,或者没有做任何有意义/有用的事情。背景脚本在单独的隐藏背景页中运行。当A)浏览器配置文件启动、b)重新启用扩展或c)安装时,将运行永久性后台脚本。因此,在选项脚本设置存储之前,您的代码会立即查询存储。您需要使用API事件或删除后台脚本。有关更多信息,请参阅。