微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 Chrome 扩展程序关闭当前的 Chrome 标签页?

如何解决如何使用 Chrome 扩展程序关闭当前的 Chrome 标签页?

我几乎完成了一个简单的 Chrome 扩展程序的构建,我想添加的最后一件事是关闭当前选项卡。

此扩展程序的作用是,当它检测到 Zoom 加入会议页面时,它会单击按钮以打开 Zoom 应用程序。我希望它在那之后关闭 Zoom join 页面

有很多问题可以说明如何去做,但我找不到关于如何去做的完整示例。在 the documentation on how to send messages 中,它有三个代码块,我无法理解我在哪里以及如何使用它来关闭当前选项卡。

This question 说你需要标签的 ID 来关闭它,所以我希望能够获取 ID 然后关闭页面(似乎我需要将消息传递给后台页面)。

如果您想使用 chrome.tabs,请将消息从 content_script 传递到后台脚本并使用 chrome.tabs

这是我当前的扩展:

ma​​nifest.json

{
    "name": "Auto Zoom Join","version": "1.0.0","manifest_version": 2,"author": "","description": "Automatically joins zoom meetings.","permissions": ["tabs"],"content_scripts":
    [{
        "matches": ["https://*.zoom.us/j/*"],"js": ["join.js"]
    }]
}

join.js

if(location.href.length-(location.href.indexOf("j/")+11)-location.hash.length>0){
  document.getElementsByClassName("_1FvRrPS6")[0].click();
}
// you can ignore above line; just detects if valid zoom join meeting page,clicks button

chrome.tabs.query({
  currentwindow:true,active:true
},function(tabs){
  chrome.tabs.remove(tabs[0].id);
});

/*
  The above line doesn't work.  It only works in background page,so I need to
  somehow send a message to the background page.
*/

那么基本上如何向关闭 Chrome 选项卡的后台页面发送消息?

解决方法

您可以使用 chrome.runtime.sendMessage API 从内容脚本向后台脚本发送消息。

chrome.runtime.sendMessage({ msg: "tab_close_msg",time: time },function (response) {
    console.log("response from the bg",response)
});

并且您可以使用 chrome.runtime.onMessage.addListener API 从后台页面接收消息

chrome.runtime.onMessage.addListener(function (request,sender,sendResponse) {
if (request.message === "tab_close_msg") {
    // add your code to close tab
}

})

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。