javascriptgoogle-chrome-extensioncontent-script

Obtaining "this" tab ID from content script in Chrome extension?


From a content script, is it possible to access that tab's id?

I want to send a message to the background page from the content script that tells my extension to "do something with this tab" using the chrome.tabs.* API.

A tabID is needed, and there is no point in doing a bunch of logic in the background page to hunt for a tabID when my content script can simply tell it the tabID in the message contents.


Solution

  • Tab id is automatically passed inside MessageSender object:

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        console.log("sent from tab.id=", sender.tab.id);
    });
    

    Note: According to docs, this property is not always available:

    This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app.