Chrome扩展存储对象时报Cannot read property 'push' of undefined如何解决
报错原因
报错核心是myObjArray调用push方法时为undefined,同时代码还存在隐藏的存储键名错误:
- 首次调用
updateLocalChromeStorage时,chrome.storage.local中还没有对应的存储键,result[key]返回undefined,直接赋值会覆盖你初始化的空数组,导致调用push时报错。你写的if(result)判断没有意义,chrome.storage.local.get的回调参数result永远是对象,哪怕没有匹配的键也不会为空。 - 存储时写的
{ key: myObjArray }属于对象字面量写法,实际存到storage里的键名是固定的"key",不是你传入的动态参数key的值,也会导致后续取值永远拿不到正确的数组。
修复方案
修改updateLocalChromeStorage函数即可:
function updateLocalChromeStorage(key, obj) { chrome.storage.local.get(key, function (result) { // 兜底判断:如果已有值不是数组就用空数组 const myObjArray = Array.isArray(result[key]) ? result[key] : []; myObjArray.push(obj); // 用计算属性设置动态键名 chrome.storage.local.set({ [key]: myObjArray }); }); }
内容的提问来源于stack exchange,提问作者Ahsan
相关产品推荐
相关产品推荐

