如何获取 Chrome 扩展程序所在选项卡的 ID

5

我正在新窗口中打开扩展程序。 Background.js

chrome.browserAction.onClicked.addListener(function(msg, sender, response){
 chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {tabId: tabs[0].id}, function(response) {});
    // creating new window.
    chrome.windows.create({ url: 'popup.html', width: 320, height: 480})
 })
})

在打开新窗口之前,选项卡ID将是当前活动选项卡ID,意味着在哪里打开Chrome扩展程序(例如:google.com)。我正在尝试在popup.js中访问该选项卡ID,因为我想访问打开Chrome扩展程序的页面(google.com)的DOM。我该如何做?或者有没有其他方法可以在popup.js中获取选项卡ID?在popup.js中尝试了其他方法。
chrome.windows.getAll({populate:true}, function(tabs){
  console.log(tabs)
});

在popup.js中,我获取了所有窗口选项卡,但我不知道扩展程序打开的选项卡ID(例如google.com)是什么?


chrome.windows.create({ url: 'popup.html', width: 320, height: 480}) 会创建一个新的窗口。如果我使用 chrome.tabs.getCurrent,它会返回当前弹出窗口对象而不是 google.com 对象。 - Sam
弹出窗口是一个全新的窗口,它不会作为我打开的Chrome扩展程序的一部分。 - Sam
2
啊,你可以通过 URL 参数传递 id,如 url: 'popup.html#' + tab.id 然后在你的 popup.js 中提取它。或者你也可以发送一条消息,但那更加复杂。 - wOxxOm
谢谢,这个方法也可以。但我用另一种方式解决了。谢谢。 - Sam
1个回答

9

实际上,这非常简单。

chrome.tabs.query({active: true}, function(tabs){})

它可以提供所有活动窗口选项卡并访问其他窗口的DOM(google.com)。

chrome.tabs.query({active: true}, function(tabs){
  chrome.tabs.executeScript(tabs[0].id,{   //tabs[0].id will give the tab id where extension is opened.
    code: 'document'  // any javascript statement
  })
})

1
更新:这个解决方案似乎在清单v3中不起作用,因为executeScript中没有“code”参数。有一个“func”参数可能可以工作,但将参数添加到查询字符串可能是更健壮的解决方案。 - Yogi

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