Manifest V3 Chrome扩展获取当前标签ID报错:Cannot read properties of undefined
问题分析与解决
核心错误原因
你遇到的Cannot read properties of undefined (reading 'id')错误,根源在于chrome.tabs.query是异步API,它返回的是Promise对象而非直接的tabs数组。你的getTabId函数直接将返回值当作数组去读取tabs[0].tabId,自然会触发错误——Promise对象没有索引0,tabs[0]为undefined,读取tabId就会抛出类型错误。
关键逻辑误区
你的目标是在扩展popup页面显示Google Charts饼图,完全不需要向其他标签页注入脚本。popup本身是独立的HTML页面,可直接在其中加载Chart库并执行渲染逻辑,无需使用chrome.scripting.executeScript或chrome.tabs相关API。
完整修正方案
1. 调整manifest.json
移除不必要的background配置和冗余权限:
{ "manifest_version": 3, "name": "Google Calendar Time Tracker", "description": "Base Level Extension", "version": "1.0", "action": { "default_popup": "index.html", "default_icon": "hello_extensions.png" }, "permissions": [] }
2. 修正index.html
修复script标签的属性错误,调整图表尺寸适配popup默认大小,并引入本地渲染脚本:
<html> <head> <link rel="stylesheet" href="styles.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@700&display=swap"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" /> <script src="https://www.gstatic.com/charts/loader.js"></script> <script src="chart.js"></script> </head> <body> <div id="donutchart" style="width: 350px; height: 250px;"></div> <h4>GOOGLE CALENDAR</h4> <h5>Time Tracker</h5> <hr> </body> </html>
3. 移除冗余文件
直接删除js/main.js,因为不需要后台脚本和标签页注入逻辑。
4. 保留chart.js(无需修改)
你的chart.js渲染逻辑是正确的,只要popup加载了Chart库就能正常运行:
google.charts.load("current", { packages: ["corechart"] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Task', 'Hours per Day'], ['Work', 11], ['Eat', 2], ['Commute', 2], ['Watch TV', 2], ['Sleep', 7] ]); var options = { title: 'My Daily Activities', pieHole: 0.4, }; var chart = new google.visualization.PieChart(document.getElementById('donutchart')); chart.draw(data, options); }
额外注意事项
- 确保文件路径匹配:chart.js需放在与index.html同级的目录,或根据实际路径调整script标签的
src属性。 - 加载扩展时,开启Chrome扩展管理页面的"开发者模式",通过"加载已解压的扩展程序"选择项目文件夹。
内容的提问来源于stack exchange,提问作者May
相关产品推荐
相关产品推荐

