如何使用Chrome扩展程序关闭当前选项卡?

4

我快完成一个简单的Chrome扩展程序了,我想要添加的最后一件事情是关闭当前标签页。

这个扩展程序的作用是当检测到Zoom加入会议页面时,点击按钮使Zoom应用程序打开。之后,我想要关闭Zoom会议页面。

有很多问题都显示了如何实现它,但我找不到一个完整的示例来说明如何做。在有关发送消息的文档中,有三个代码块,我无法理解哪里放置代码以及如何使用它来关闭当前标签页。

这个问题说你需要标签页的ID来关闭它,所以我想要能够获取ID,然后关闭页面(似乎我需要将一条消息传递给后台页面)。

如果要使用chrome.tabs,则需要从content_script向background script发送消息并操作chrome.tabs

这是我的当前扩展程序:

manifest.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标签页?

2个回答

2
你可以使用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
}

})


0
感谢@Noob dev的帮助,但对于清单v3,我需要从message更改为msg
以下内容适用于我:
在您的内容脚本页面上:
function closeLastTab() {
    chrome.runtime.sendMessage(
        { 
            msg: "tab_close_msg"
        }, 
        function (response) {
            console.log("response from the bg", response)
        }
    );
}

在你的 background.js 文件中:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    if (request.msg === "tab_close_msg") {
        chrome.tabs.query({
            currentWindow: true,
            active: true
        }, function (tabs) {
            chrome.tabs.remove(tabs[0].id);
        });
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接