Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
void.pointer Avatar asked Jun 01 '11 14:06

void.pointer


People also ask

What is the tab ID?

ID is an identifier that allows the tab component to be referenced by other components in the page.

What is chrome content script?

Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them, and pass information to their parent extension.


2 Answers

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); }); 
like image 84
serg Avatar answered Sep 18 '22 08:09

serg


If you want the tabId of yourself (in my case in Content Script) without requiring "tabs" permission, a workaround is to have Content Script send a dummy message to the background script, then have background script respond with sender.tab.id back to the Content Script!

e.g. in content.js:

chrome.runtime.sendMessage({ text: "what is my tab_id?" }, tabId => {    console.log('My tabId is', tabId); }); 

and in background.js:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {     if (msg.text == "what is my tab_id?") {         sendResponse({tab: sender.tab.id});      } }); 

it's a stupid workaround that worked for me. :)

PS. Oh, if you have tabs permission then you can run this async query very easily:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){     var myTabId = tabs[0].id;     chrome.tabs.sendMessage(myTabId, {text: "hi"}, function(response) {         alert(response);     }); }); 
like image 21
Aidin Avatar answered Sep 18 '22 08:09

Aidin