How to get the tab id where the chrome extension is opened

Viewed 7698

I am opening the extension in the new window. 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})
 })
})

Before opening new window, the tab ID will be the active tab ID means where i opened the chrome extension(eg: google.com). I am trying to access that tab ID in popup.js. Because i want to access the DOM of the page(google.com) where chrome extension is opened. How can i do that? or is there any other way to get the tab ID in the popup.js?

Tried other way in popup.js

chrome.windows.getAll({populate:true}, function(tabs){
  console.log(tabs)
});

Here i am getting all the window tabs in popup.js, but here i do not know that tab ID where extension is opened(google.com)?

1 Answers

Its actually very simple

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

Its is giving what are all the active window tabs and accessing other window 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
  })
})
Related