首页 > 解决方案 > 错误处理响应: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"
    }
}

有错误的图像

标签: javascriptgoogle-chrome-extension

解决方案


请注意,当索引 i 中没有选项卡时,您的 while 循环将停止。等于 tabs 数组的长度。不要忘记数组索引是从 0 开始的,所以最后一个元素是数组的长度减去 1。

因此,当您尝试获取 tabs[i] 时,您将无法定义。并且“undefined.id”会引发异常。

如果您的目标是访问最后一个元素的 id,我建议您这样做:

tabs[tabs.length - 1].id

推荐阅读