首页 > 解决方案 > 如何获取打开 chrome 扩展程序的选项卡 ID

问题描述

我正在新窗口中打开扩展程序。 背景.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)?

标签: google-chromegoogle-chrome-extension

解决方案


其实很简单

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

推荐阅读