Chrome如何获取当前标签页的ID?

7
chrome.tabs.getCurrent(function(tab){
  alert(tab.id);
});

tab是一个对象吗?为什么它没有id属性?

如何获取当前标签页的id


你看过这些吗?https://developer.chrome.com/extensions/tabs#method-getCurrent 和 https://developer.chrome.com/extensions/tabs#type-Tab - Patrick Roberts
@PatrickRoberts 你能给我一个例子吗? - woody
您是否在Chrome扩展程序的上下文中运行此代码?除非它在具有以下内容的Chrome扩展程序中运行,否则该代码将无法工作:"permissions": [ "tabs"] - Patrick Roberts
@PatrickRoberts 我该如何获取当前选项卡的ID? - woody
@PatrickRoberts 我是新来的,也是新手,感谢您的耐心! - woody
1
@PatrickRoberts,“tabs”权限仅在需要读取私人信息、URL、标题等时才是必要的。 - Daniel Herr
1个回答

7

chrome.tabs.getCurrent(function(tab){ console.log(JSON.stringify(tab,null, 2)); }) 给我下面的结果:

{
  "active": true,
  "audible": false,
  "favIconUrl": "chrome-extension://eggkanocgddhmamlbiijnphhppkpkmkl/img/favicon.png",
  "height": 853,
  "highlighted": true,
  "id": 5280,
  "incognito": false,
  "index": 0,
  "mutedInfo": {
    "muted": false
  },
  "pinned": false,
  "selected": true,
  "status": "complete",
  "title": "Tabs Outliner",
  "url": "chrome-extension://eggkanocgddhmamlbiijnphhppkpkmkl/activesessionview.html?type=main&focusNodeId=5220&altFocusNodeId=5046&scrollToViewWinId=5046",
  "width": 400,
  "windowId": 5279
}

以下是您可以在https://developer.chrome.com/extensions/tabs#type-Tab找到的所有属性列表,其中ID被标记为可选项。
标签的ID是唯一的,在浏览器会话中是唯一的。在某些情况下,可能不会为标签分配ID,例如在使用会话API查询外部标签时,在这种情况下可能存在会话ID。对于应用程序和开发工具窗口,也可以将标签ID设置为chrome.tabs.TAB_ID_NONE。
如果您尝试从控制台运行代码,则这一点非常重要。
标签ID也可以设置为chrome.tabs.TAB_ID_NONE,用于应用程序和开发工具窗口。

考虑用JSON.stringify(tab, null, 2);或其他方式替换您的屏幕截图。 - Patrick Roberts
是的,这似乎是唯一可行的方法。我像这样使用它:chrome.tabs.query({currentWindow: true, active: true}, function(tabs){ chrome.tabs.update(tabs[0].id, { url: "link"}); } ); - user25

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接