如何获取现有网址的Tab标签ID

时间:2018-12-02 02:00:00

标签: api google-chrome-extension

我想获取现有网址的Tab标签ID 例如,我在Chrome中有3个标签 标签1是youtube 标签2是google 标签3是twitter 而且我想获取选项卡的ID已存在url google com

2 个答案:

答案 0 :(得分:0)

这里是一个例子:

// get all the tabs, you can also limit it to the current window if you wish
// chrome.tabs.query({currentWindow: true}, ...)
chrome.tabs.query({}, tabs => {

  // loop through the tabs
  for (const tab of tabs) {
    if (tab.url === 'theOneYouWant) {
      // do whatever needed with tab.id

      // break/stop the loop
      break;
    }
  }
});

您可以将代码更改为检查域(不是整个URL)或任何其他相关条件。

答案 1 :(得分:0)

在扩展页面中使用chrome.tabs API ,例如browserAction弹出窗口或后台脚本。

manifest.json:

"permissions": ["tabs"]

最简单的情况-域名没有变化

chrome.tabs.query({url: 'https://www.youtube.com/*'}, tabs => {
  // use 'tabs' inside the callback
});

简单情况-子域中有变化,但TLD(顶级域)名称没有变化:

chrome.tabs.query({url: 'https://*.twitter.com/*'}, tabs => {
  // use 'tabs' inside the callback
});

艰难的情况-TLD有所不同:

const RE_ALL_GOOGLE = /^https:\/\/(www\.)?google\.([a-z]{2,3}|com?\.[a-z]{2})\//;
// the tabs API doesn't accept wildcards in TLD so we need to enumerate all tabs
// and we restrict the list to https-only as an optimization for the case of many open tabs
chrome.tabs.query({url: 'https://*/*'}, tabs => {
  const googleTabs = tabs.filter(({url}) => RE_ALL_GOOGLE.test(url));
  // use 'googleTabs' here inside the callback
});

您可以使用full list of all Google domains和类似this one的RegExp生成器来编写更严格的正则表达式。


内容脚本不能直接使用chrome.tabs ,因此您需要通过后台脚本来实现。

内容脚本:

chrome.runtime.sendMessage({
  action: 'getTabs',
  url: 'https://*/*',
  // messaging can't transfer regexps so we convert it to a string
  pattern: /^https:\/\/(www\.)?google\.([a-z]{2,3}|com?\.[a-z]{2})\//.source,
}, tabs => {
  // use 'tabs' inside the callback
});

manifest.json:

"permissions": ["tabs"],
"background": {
  "scripts": ["background.js"],
  "persistent": false
}

background.js:

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.action === 'getTabs') {
    chrome.tabs.query({url: msg.url}, tabs => {
      if (msg.pattern) {
        const re = new RegExp(msg.pattern);
        tabs = tabs.filter(({url}) => re.test(url));
      }
      sendResponse(tabs);
    });
    // keep the reponse channel open since the chrome.tabs API is asynchronous
    return true;
  }
});