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
相关产品推荐
相关产品推荐

