如何获取打开Chrome扩展程序的标签页ID

时间:2019-01-09 07:18:39

标签: google-chrome google-chrome-extension

我要在新窗口中打开扩展名。 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中获取所有的窗口标签,但是在这里我不知道打开扩展名(google.com)的标签ID?

1 个答案:

答案 0 :(得分:1)

它实际上很简单

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
  })
})