Chrome 扩展 V3 注入脚本获取标签页 ID 并关闭 - 代码示例
Chrome 扩展 V3 注入脚本获取标签页 ID 并关闭 - 代码示例
本文将介绍如何使用 Chrome 扩展 V3 注入脚本,获取当前标签页 ID,并将其发送给后台脚本进行处理,实现关闭标签页的功能。
实现步骤
- 在
manifest.json文件中增加permissions:
"permissions": [
"tabs"
],
- 在
content_scripts中增加js文件:
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
- 创建
content.js文件,获取标签页 ID 并发送给background:
// 获取当前标签页 ID
const tabId = chrome.tabs.getCurrent((tab) => {
return tab.id;
});
// 发送消息给 `background`
chrome.runtime.sendMessage({
type: 'closeTab',
tabId: tabId
});
- 在
background.js中监听消息并关闭标签页:
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.type === 'closeTab') {
chrome.tabs.remove(message.tabId);
}
});
代码解释
-
content.js使用chrome.tabs.getCurrent获取当前标签页的 ID,并通过chrome.runtime.sendMessage发送消息给background.js。 -
background.js使用chrome.runtime.onMessage.addListener监听来自content.js的消息,并通过chrome.tabs.remove关闭指定 ID 的标签页。
注意:
- 以上代码仅供参考,实际使用中可能需要根据具体需求进行修改。
- 确保你的 Chrome 扩展已启用权限
tabs。 - 可以根据需要修改
content_scripts中的matches属性,指定脚本生效的页面。
通过以上步骤,你就可以使用 Chrome 扩展 V3 注入脚本,实现获取标签页 ID 并关闭标签页的功能。
原文地址: https://www.cveoy.top/t/topic/nhUn 著作权归作者所有。请勿转载和采集!