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

Chrome扩展报错Uncaught TypeError:无法读取undefined的'id'属性

解决Chrome扩展中"Cannot read property 'id' of undefined"错误

你遇到的这个错误,核心原因是color.js里的tabs数组是空的——你试图访问tabs[0].id,但tabs[0]根本不存在(是undefined),所以才抛出了类型错误。

我们来一步步修复问题:

错误根源

你的color.js里只声明了空数组tabs = new Array();,但从来没有填充过任何标签页数据,自然拿不到有效的标签页ID。正确的做法应该是获取当前活跃的标签页,而不是用一个空数组。

修复后的color.js代码

把原来的点击事件逻辑替换成用chrome.tabs.query获取当前活跃标签页的写法:

let changeColor = document.getElementById('changeColor');

chrome.storage.sync.get('color', function(data) {
  changeColor.style.backgroundColor = data.color;
  changeColor.setAttribute('value', data.color);
});

window.onload = function() {
  changeColor.onclick = function(element) {
    let color = element.target.value;
    // 获取当前窗口的活跃标签页
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      // 向目标标签页注入脚本修改背景色
      chrome.tabs.executeScript(
        tabs[0].id,
        { code: 'document.body.style.backgroundColor = "' + color + '";' }
      );
    });
  };
};

额外注意事项

  • 移除了没用的空数组声明tabs = new Array();,因为我们通过chrome.tabs.query会直接拿到包含当前标签页的有效数组
  • chrome.tabs.query({active: true, currentWindow: true})会返回当前窗口中处于活跃状态的标签页数组,此时tabs[0]就是我们需要的标签页对象,能正确读取id属性
  • 确保你的manifest.json里已经声明了必要权限,示例配置:
"permissions": [
  "activeTab",
  "storage",
  "declarativeContent"
]

这样修改后,点击按钮就能正常给当前活跃标签页修改背景色,不会再出现那个类型错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:56:38