You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展无法设置local storage,读取值始终为undefined

Chrome扩展Storage读取值为undefined问题

我正在开发一款Chrome扩展,尝试通过以下代码读写local storage:

chrome.storage.local.set({lty_username: username}, function(){
    if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError);
    } 
    else {
        console.log("Username saved: " + username);
    }
});

chrome.storage.local.get(["lty_username"]).then((result) => {
    alert("Value currently is " + result.key);
});

但读取同一键值时,结果始终为undefined,且控制台无报错信息。以下是我的manifest.json文件:

{
    "name": "name",
    "version": "1.0.0",
    "description": "description",
    "manifest_version": 3,
    "author": "author",
    "action":{
        "default_popup": "index.html",
        "default_title": "title"
    },
    "host_permissions": [
    "*://*.facebook.com/",
    "*://*.twitter.com/",
    "*://*.linkedin.com/",
    "*://*.nextdoor.com/",
    "*://*.instagram.com/",
    "*://*.reddit.com/",
    "*://*.quora.com/"
    ],
    "permissions": [
    "cookies",
    "storage"
    ]
}

我无法找出local storage无法设置值的原因,请问有人知道问题所在吗?


问题分析与解决

你的代码存在两个核心问题:

  • 读取时的键名错误
    存储的键是lty_username,但你用result.key获取值,这是错误的。chrome.storage.local.get返回的对象会直接以存储的键作为属性名,应该用result.lty_username来访问。

  • 异步执行顺序问题
    chrome.storage.local.set是异步操作,当前代码中get可能在set完成前就执行了,导致读取不到刚设置的值。需要保证get在set完成后执行。

修正后的代码示例

回调方式:

chrome.storage.local.set({lty_username: username}, function(){
    if (chrome.runtime.lastError) {
        console.error(chrome.runtime.lastError);
    } 
    else {
        console.log("Username saved: " + username);
        // 在set完成后执行读取操作
        chrome.storage.local.get(["lty_username"], function(result) {
            alert("Value currently is " + result.lty_username);
        });
    }
});

Promise链式调用方式(适配Manifest V3风格):

chrome.storage.local.set({lty_username: username})
.then(() => {
    console.log("Username saved: " + username);
    return chrome.storage.local.get(["lty_username"]);
})
.then((result) => {
    alert("Value currently is " + result.lty_username);
})
.catch((error) => {
    console.error(error);
});

额外检查项

  1. 确认username变量有实际值,可在set前添加console.log(username)验证。
  2. 你的manifest已正确配置storage权限,这部分无需调整。

内容的提问来源于stack exchange,提问作者us1LfMz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 23:23:13