Chrome扩展content.js调用chrome.storage.sync.get返回空对象问题
问题根源与解决方案
嘿,我一眼就看出问题所在了——你搞混了Chrome扩展的专属存储和网页自身的localStorage!
为什么你得到的是空对象?
chrome.storage.sync是Chrome扩展独有的存储区域,和你访问的www.app.com页面里的localStorage完全是两个互不干扰的存储空间。你从来没往扩展的sync存储里存过auth值,所以调用chrome.storage.sync.get(['auth'])自然返回空对象{}。
而你的auth密钥明明存在**网页的localStorage**里,content script是可以直接访问这个存储空间的!
修正后的代码
把你的content.js改成下面这样,直接读取网页的localStorage:
// 从页面的localStorage中获取auth字符串 const authStr = localStorage.getItem('auth'); // 因为localStorage只能存储字符串,所以要解析成JSON对象 const authObj = JSON.parse(authStr); // 展示auth内容 alert(JSON.stringify(authObj)); // (可选)如果需要把这个auth值同步到扩展的chrome.storage.sync里,添加以下代码: chrome.storage.sync.set({ auth: authObj }, () => { console.log('Auth值已同步到扩展存储'); });
额外说明
- 权限与注入验证:你的
manifest.json配置没问题——storage权限已经添加,content script的匹配规则*://*.app.com/*和all_frames: true也能确保脚本正确注入到目标页面。 - 隔离环境特性:content script运行在隔离的环境中,但Chrome允许它直接访问页面的
window.localStorage,不需要额外配置。 - 扩展跨组件数据共享:如果之后你想从扩展的其他部分(比如background、popup)获取这个
auth值,就可以用chrome.storage.sync.get(['auth'])了,因为我们已经把网页的auth同步到扩展存储里了。
内容的提问来源于stack exchange,提问作者Umbro
相关产品推荐
相关产品推荐

