popup.html中的chrome.tabs.create正在打开无限数量的选项卡。如何打开一个标签?

时间:2012-12-19 18:57:35

标签: javascript google-chrome-extension

很明显,这会打开popup.html的无数个标签页。如何更改它以便只打开一个选项卡。

chrome.tabs.create({'url': chrome.extension.getURL('popup.html')}, function(tab) {
        // Tab opened.

    });

编辑:(一个基本的popup.html)

<!DOCTYPE html>
    <html lang="en">


    <!--<script src="script.js"></script>-->
    <script src="jquery.min.js"></script>
    <script src="popup.js"></script>
      <head>
          <meta charset="utf-8">
          <title> Chrome Extension</title>
          <!--<link rel="stylesheet" href="style.css" />-->
      </head>
      <body id="container">
        <div id="left">
          <div class="input-wrapper">

        hello

          </div>


    </div> <!-- end #left -->
      </body>
    </html>

popup.js

function openTab()
{
    filename = "popup.html"

  var myid = chrome.i18n.getMessage("@@extension_id");
  chrome.windows.getCurrent(
  function(win)
  {
    chrome.tabs.query({'windowId': win.id},
    function(tabArray)
    {
      for(var i in tabArray)
      {
        if(tabArray[i].url == "chrome-extension://" + myid + "/" + filename)
        {
          // console.log("already opened");
          chrome.tabs.update(tabArray[i].id, {active: true});
          return;
        }
      }
      chrome.tabs.create({url:chrome.extension.getURL(filename)});
    });
  });
}

openTab();

的manifest.json:

{
  "name": "App",
    "version": "1.1",
  "manifest_version": 2,
  "description": "Test",
  "background_page": "background.html",
  "browser_action": {
    "name": "App",
    "icons": ["icon.png"],
    "default_icon": "icon.png",
   "default_popup":"popup.html"
  },
  "content_scripts": [ {
    "js": [ "jquery.min.js", "background.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }],
   "permissions": [ "<all_urls>", 
                  "storage",
                  "tabs",
               "contextMenus" ]


}

1 个答案:

答案 0 :(得分:1)

以下是特定标签的搜索示例。如果该选项卡不存在,则该功能将打开它,否则现有选项卡将被激活。

function openTab(filename)
{
  var myid = chrome.i18n.getMessage("@@extension_id");
  chrome.windows.getCurrent(
  function(win)
  {
    chrome.tabs.query({'windowId': win.id},
    function(tabArray)
    {
      for(var i in tabArray)
      {
        if(tabArray[i].url == "chrome-extension://" + myid + "/" + filename)
        {
          // console.log("already opened");
          chrome.tabs.update(tabArray[i].id, {active: true});
          return;
        }
      }
      chrome.tabs.create({url:chrome.extension.getURL(filename)});
    });
  });
}

或者,您可以在后台页面(如下面的草稿)中创建新的标签ID,并在标签关闭时清理变量(通过chrome.tabs.onRemoved.addListener)。

if(chrome.extension.getBackgroundPage().savedTabId != undefined)
{
  chrome.tabs.create({url:chrome.extension.getURL(filename)},
  function(tab){
    chrome.extension.getBackgroundPage().savedTabId = tab.id;
  });
}