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

Manifest V3中popup.js点击按钮注入脚本如何获取tabId实现V2同等功能

修正后的可运行代码(Manifest V3版本)

document.addEventListener('DOMContentLoaded', function () {
    // 获取按钮元素
    const button = document.getElementById('btnScan');

    button.onclick = async function () {
        // 查询当前窗口处于激活状态的标签页
        const [currentTab] = await chrome.tabs.query({
            active: true,
            currentWindow: true
        });
        
        // 执行脚本注入
        await chrome.scripting.executeScript({
            target: { tabId: currentTab.id },
            files: ['Scripts/script.js']
        });
        
        window.close();
    };
});

注:Manifest V2中chrome.tabs.executeScript传null作为第一个参数时,默认注入当前窗口的激活标签页,上述写法完全对齐该行为。

配套manifest.json权限要求

除已添加的scripting权限外,还需要补充activeTab权限:

{
  "manifest_version": 3,
  "permissions": ["activeTab", "scripting"],
  // 其余原有配置保持不变即可
}

回调形式兼容写法(不使用async/await)

如果需要适配不支持顶层async的场景,可改用回调写法:

document.addEventListener('DOMContentLoaded', function () {
    const button = document.getElementById('btnScan');

    button.onclick = function () {
        chrome.tabs.query({active: true, currentWindow: true}, function([currentTab]) {
            chrome.scripting.executeScript({
                target: { tabId: currentTab.id },
                files: ['Scripts/script.js']
            }, function() {
                window.close();
            });
        });
    };
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 17:24:01