Chrome扩展报错:Uncaught TypeError: 无法读取undefined的'sync'属性
问题原因
你将popup.html配置为沙箱页面,而沙箱页面处于完全隔离的环境中,无法直接访问Chrome扩展的特权API(包括chrome.storage),这就是触发Uncaught TypeError的根本原因。
解决方案
直接移除manifest.json中对popup.html的沙箱配置即可,因为popup本身属于扩展的特权页面,默认就能访问chrome.storage等扩展API,不需要沙箱隔离。
步骤1:修正manifest.json
删除或修改sandbox字段,确保popup.html不在沙箱页面列表中:
"permissions": [ "storage" ], "background": { "service_worker": "background.js" }, "action": { "default_icon": "images/icon-48.png", "default_popup": "popup.html" }, "content_scripts": [ { "matches": ["###"], "js": ["inject.js"] } ] // 移除原有的"sandbox"配置块,或者如果有其他沙箱页面,仅删除"popup.html"条目
步骤2:保留popup.html的原有脚本
现在popup作为特权页面,可直接调用chrome.storage,无需修改原有代码:
<body> <script> chrome.storage.sync.set({ "enabled": true }, function() { alert('set'); }); </script> </body>
补充说明
如果你的场景确实需要使用沙箱页面(比如加载不可信第三方内容),但又要访问存储API,那必须通过chrome.runtime.sendMessage与后台脚本通信间接操作存储,但你明确表示不想使用后台脚本,因此取消popup的沙箱配置是最直接的解决方式。
内容的提问来源于stack exchange,提问作者user20472970
相关产品推荐
相关产品推荐

