【问题标题】:How to close the current Chrome tab with a Chrome Extension?如何使用 Chrome 扩展程序关闭当前的 Chrome 选项卡?
【发布时间】:2021-01-01 23:09:43
【问题描述】:

我几乎完成了一个简单的 Chrome 扩展,我最不想添加的就是关闭当前选项卡。

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

有很多问题可以说明如何做到这一点,但我找不到关于如何做到这一点的完整示例。在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 标签的后台页面发送消息?

【问题讨论】:

    标签: javascript google-chrome-extension tabs content-script


    【解决方案1】:

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

    })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多