javascript - 错误处理响应:TypeError:无法读取未定义的属性“id”
问题描述
我正在尝试进行 chrome 扩展,但由于某些原因,此错误不断发生。我想要做的是我想去最后打开的选项卡并在其中执行一个脚本。有人可以帮我吗?
这是我的背景.js:
function executeScript(){
chrome.tabs.query({}, function(tabs){
var i=0;
while (tabs[i]) {
i++;
};
chrome.tabs.update(tabs[i].id, {highlated: true});
document.getElementById('info').innerHTML = i;
chrome.scripting.executeScript(
{
target:{tabId: tabs[i].id},
function: codeToExecute,
});
})
}
setTimeout(executeScript, 500);
这是我的 manifest.json:
{
"name": "Name of extension",
"description": "Coded by furtuna with JS and ♥",
"version": "1.0",
"manifest_version": 3,
"background": {
"script": "files/background.js"
},
"permissions": [
"tabs",
"storage",
"scripting"
],
"host_permissions": [
"http://*/*",
"https://*/*"
],
"action": {
"default_popup": "files/main.html"
}
}
解决方案
请注意,当索引 i 中没有选项卡时,您的 while 循环将停止。等于 tabs 数组的长度。不要忘记数组索引是从 0 开始的,所以最后一个元素是数组的长度减去 1。
因此,当您尝试获取 tabs[i] 时,您将无法定义。并且“undefined.id”会引发异常。
如果您的目标是访问最后一个元素的 id,我建议您这样做:
tabs[tabs.length - 1].id
推荐阅读
- python - 如何知道哪种算法技术或深度学习模型最适合某些特定数据集
- python - csv Pandas datetime 将时间转换为秒
- php - 如何在“编辑配置文件”部分添加可更新的输入字段以显示“user_pass”加密数据?
- javascript - 单击按钮以显示类别时,如何对对象数组进行排序?
- reactjs - 如何创建动态反应组件
- python - Django:sendgrid 电子邮件是否应该始终从 Celery 发送?
- python - 如何使用日期和数据列在 python 中访问或调用或提取单变量时间序列数据的元素
- php - 无法在 PHP 中启用 mb_string
- java - Java EE 中的无状态单例
- grammar - 使用 Perl 6 语法在原始正则表达式中传递变量