0

很明显,这会打开无限数量的带有 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();

清单.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" ]


}
4

1 回答 1

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;
  });
}
于 2012-12-19T19:43:49.873 回答