11

Both methods are producing the same error Uncaught TypeError: Cannot read property 'query' of undefined for my content script... I've already looked at How to fetch URL of current Tab in my chrome extension using javascript and How do you use chrome.tabs.getCurrent to get the page object in a Chrome extension? though I'm still not sure what I'm doing incorrectly.

manifest.json

{
  "name": "Extension Tester",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Tester",
  "permissions": [
    "tabs"
  ],
  "content_scripts": [
    {
      "matches": ["https://www.google.com/"],
      "js": [
        "inject.js"
      ]
    }
  ]
}

inject.js

chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  console.log(tabs[0].id);
});

or

chrome.tabs.getCurrent(function (tab) {
  console.log(tab.id);
});
Community
  • 1
  • 1
Jacob Edward
  • 181
  • 1
  • 2
  • 10
  • 2
    possible duplicate of [chrome.tabs returns undefined in content script](http://stackoverflow.com/questions/15034859/chrome-tabs-returns-undefined-in-content-script) – Xan Oct 17 '14 at 07:02
  • 2
    Definitely a duplicate [chrome.tabs returns undefined in content script](http://stackoverflow.com/questions/15034859/chrome-tabs-returns-undefined-in-content-script) – Marco Bonelli Oct 17 '14 at 10:55

1 Answers1

19

Cannot use chrome.tabs in content script,you need to use chrome.runtime To know the tab id of the content script, first use chrome.runtime.sendMessage to send a message, and the background page receive it.

Using chrome.runtime.onMessage.addListener, the callback function is

function(any message, MessageSender sender, function sendResponse) {...};

so, you will know the tab id by sender.id

KenD
  • 5,280
  • 7
  • 48
  • 85
youmu_i19
  • 206
  • 3
  • 3
  • nice answer, but I have a doubt. The message sent from the content script througth chrome.runtime.sendMessage will be received by any extension that have called chrome.runtime.onMessage.addListener, right? – rmpt Apr 14 '16 at 14:58
  • @rmpt I believe no. addListener and sendMessage work only for the current extension. There is another API to interact between extensions. – Scruffy Aug 05 '19 at 16:00
  • 1
    This is almost right, though for the tab ID you actually need to do `sender.tab.id` like they suggest [here](https://stackoverflow.com/questions/6202953/obtaining-this-tab-id-from-content-script-in-chrome-extension) – Dave Jul 14 '20 at 23:47