首页 > 解决方案 > 为什么 chrome.storage.local.get 返回 undefined 的值?

问题描述

我正在开发谷歌扩展并使用谷歌存储。

下面是我保存和访问已保存数据的代码。我检查了控制台,数据保存正确。但是,当我使用 chrome.storage.local.get 访问此数据时,控制台返回未定义的值而不是保存的值。

保存代码:popup.html 的 save.js

function save() {
    # the id is for a textarea in another html page
    var text = document.getElementById("text").value;

    chrome.storage.sync.set({"txt": text}, function(){
      
       # console states the correct value
       console.log('Value is set to ' + text);
     });

   # this is the page I want to retrieve the saved data in 
   window.location.replace("anotherHTMLpage.html");

}

访问代码:retrieve.js for anotherHTMLpage.html

function retrieve() {
    chrome.storage.sync.get(["txt"], function(data) {
     
      # console says "value currently is undefined"
      console.log('Value currently is ' + data.key);

   });
  }

我在这里先向您的帮助表示感谢!

标签: google-chrome-extensionundefinedgoogle-chrome-storage

解决方案


Chrome 将数据保存在您设置的密钥下。在您的示例中,您将其保存为txt,因此它将位于data.txtnot之下data.key

查看文档以获取更多详细信息https://developer.chrome.com/docs/extensions/reference/storage/#usage


推荐阅读