Chrome扩展程序:关闭打开的标签页,无论它是否为当前标签

时间:2015-03-09 18:11:16

标签: javascript google-chrome google-chrome-extension

这是我的chrome扩展程序的background.js。我是编程chrome扩展的新手。 如何关闭此示例中打开的选项卡,无论该选项卡是否为当前选项卡?

chrome.tabs.onCreated.addListener(function() {
    chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, 
        function (tabs) {
            url = tabs[0].url;
            if (url=="http://www.example.com"){
                setTimeout(function(){
                    //would be nice to have this executed after EVERYTHING on the page is loaded
                    chrome.tabs.executeScript(null, {file:"jquery-1.11.1.min.js"});
                    chrome.tabs.executeScript(null, {file:"contentscript.js"});
                },17000);
                setTimeout(function(){
                    tabs[0].remove();
                    alert('tab removed');
                },25000);
            }
        }
    );
});

4 个答案:

答案 0 :(得分:0)

来自commentgui47是正确的 - 只需使用chrome.tabs.remove(...您要移除的标签ID ...)

答案 1 :(得分:0)

很多代码可以使用改进,假设我理解你的意图

想象一下,您可以在选项卡中单击一个链接。它在后台创建一个标签,并为其调用onCreated监听器。

然而,您查询活动选项卡,并获取初始选项卡,而不是新选项卡。

  1. 您应该使用标签信息is passed into onCreated

    这一事实
    chrome.tabs.onCreated.addListener(function(tab) { // Can have a parameter!
      /* use tab.url and tab.id */
    });
    
  2. 当您致电executeScript时,它仍然遵守the run_at parameter,默认情况下为document_idle。这意味着它至少在静态DOM就绪之前不会执行。

    所以不需要超时。为了更加安全,您可以将内容脚本代码包装在$(document).ready()

    如果您想等到加载图像等资源,可以使用身体的load事件。

    如果您需要等到特定事件发生/某些脚本在页面中执行,您可以使用超时和/或MutationObserver之类的内容。但是,将此等待添加到contentscript.js而不是注入代码会更有意义。

    chrome.tabs.onCreated.addListener(function(tab) { // Can have a parameter!
      // Assuming you want to check the address contains that and not exactly it
      if(~tab.url.indexOf("http://www.example.com")) {
        chrome.tabs.executeScript(tab.id, {file:"jquery-1.11.1.min.js"});
        chrome.tabs.executeScript(tab.id, {file:"contentscript.js"});
      }
    });
    
  3. 最后,如果您要关闭该页面,可以拨打chrome.tabs.remove(tab.id)

    但是,从内容脚本中简单地关闭它可能会更好 - 它可能知道何时更好。

    如果您的扩展程序打开了标签页,您可以在内容脚本中使用window.close()

答案 2 :(得分:0)

您应该使用chrome.tabs.remove(tab.id);关闭标签页。 见chrome.tabs.remove( )

答案 3 :(得分:0)

使用chrome.tabs.remove(tabId);

其中tabId是标签的ID。如果您不知道从何处获取tabId,则可以在background.js中使用以下代码。

chrome.tabs.query(
    {
        active:true,
        windowType:"normal",
         currentWindow: true
    },
    function(d)
    {
        tabId = d[0].id;
    });
相关问题