Error handling response: TypeError: Cannot read property 'id' of undefined
Error handling response: TypeError: Cannot read property 'id' of undefined
我正在尝试进行 chrome 扩展,但由于某些原因,此错误不断发生。我想做的是我想转到最后打开的选项卡并在其中执行脚本。有人可以帮我吗?
这是我的 background.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"
}
}
Image with the error
请注意,当索引 i 中没有制表符时,您的 while 循环将停止。等于 tabs 数组的长度。
不要忘记数组索引是从 0 开始的,所以最后一个元素就是数组的长度减 1。
因此,当您尝试获取 tabs[i] 时,您将得到 undefined。并且“undefined.id”抛出异常。
如果您的目标是访问最后一个元素的 ID,我建议您这样做:
tabs[tabs.length - 1].id
我正在尝试进行 chrome 扩展,但由于某些原因,此错误不断发生。我想做的是我想转到最后打开的选项卡并在其中执行脚本。有人可以帮我吗?
这是我的 background.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"
}
}
Image with the error
请注意,当索引 i 中没有制表符时,您的 while 循环将停止。等于 tabs 数组的长度。 不要忘记数组索引是从 0 开始的,所以最后一个元素就是数组的长度减 1。
因此,当您尝试获取 tabs[i] 时,您将得到 undefined。并且“undefined.id”抛出异常。
如果您的目标是访问最后一个元素的 ID,我建议您这样做:
tabs[tabs.length - 1].id