Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the id of a Chrome tab?

chrome.tabs.get apparently doesn't work in the content script, and other than sending it through chrome.extension.sendRequest I've no idea how to make the background respond to the correct tab.

How can I make the content script send information to the background page, then the background page return information back to the tab where it came from?

like image 705
Anonymous Avatar asked Mar 27 '11 09:03

Anonymous


1 Answers

As a courtesy to anyone viewing this question post-2011, I've provided an answer that uses the newer conventions and APIs. This is a fairly popular question and the accepted answer is somewhat dated at this point (but still an accurate answer, nonetheless), so for any newcomers this should hopefully provide a clearer and more applicable answer to the question.

For starters, you can send a message from the content script using chrome.runtime.sendMessage. This will indiscriminately send the message when a runtime event occurs (i.e. the browser action is clicked). It will look something like this:

content.js

chrome.runtime.sendMessage({ from: 'content', message: 'info to send' });

Since you need to communicate with an event page (in accordance with newer conventions, the event page is the preferred choice over the persistent background page) to grab information about the active tab (assuming you want just the tab id), you can actually grab that information by adding a runtime event listener and checking the sender parameter. It will look something like this:

event.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.from == 'content') {
    // tabId will hold the sender tab's id value
    var tabId = sender.tab.id;
    sendResponse({ from: 'event', message: 'any info to send back', tabId: tabId });
}});

However, since we need to deliver that information back to the content script, we'll need to go back and add a callback handler to chrome.runtime.sendMessage. It will now look something like this:

content.js

chrome.runtime.sendMessage({ from: 'content', message: 'info to send' }, function(callbackResponse) {
  if (callbackResponse.from == 'event') {
    // do what you need to do in here
    console.log(callbackResponse.tabId);
  }
});

This setup will now allow you to pass simple, one-time messages from content.js to event.js, where event.js provides information back to content.js.

Again, this is just an updated version of the accepted answer for those who would like an example of how the new approach works.

like image 63
nburr Avatar answered Oct 23 '22 08:10

nburr