Chrome扩展popup中chrome.storage.local存储UserID返回undefined问题
问题核心原因
你的代码存在两处关键问题,导致存储和取值异常:
- 取值时键名引用错误
你调用chrome.storage.local.set存储的键名是UserID,但在get回调中错误访问了不存在的result.key,自然返回undefined。 - 未捕获存储操作异常
没有对存储过程的报错进行捕获,无法排查权限或运行层面的问题。
修正后的代码
chrome.storage.local.set({UserID: userCredential.user.uid}, function(){ // 先检查存储操作是否有报错 if (chrome.runtime.lastError) { console.error("存储失败:", chrome.runtime.lastError); return; } console.log("Stored in storage") chrome.storage.local.get(["UserID"], function(result) { // 访问正确的键名UserID console.log('Value currently is ' + result.UserID); }); })
后续校验逻辑示例
你可以在扩展图标点击触发的逻辑中直接使用如下代码判断登录状态:
chrome.storage.local.get(["UserID"], function(result) { if (result.UserID) { // 存在已存储的用户ID,渲染用户信息页 renderUserInfo(result.UserID) } else { // 无用户ID,渲染登录注册按钮 renderAuthButtons() } })
验证方法
你可以在扩展对应的DevTools控制台直接执行chrome.storage.local.get(console.log),即可打印所有本地存储的内容,确认UserID是否写入成功。你已经在manifest.json中配置了storage权限,无需额外修改权限配置。
内容的提问来源于stack exchange,提问作者Suji
相关产品推荐
相关产品推荐

