I'm writing a Chrome extension and, in one part of it, I need to get the current tab's title and URL when a button on the popup page is clicked.
I've worked with Chrome's message passing system before and, after much effort, managed to get it to work, on many occasions. However, I've never had to use them with popup pages and, from what I've read, it's much more difficult to do.
The timeline I've managed to figure out so far is this:
popup.html
/ popup.js
: Button is clickedpopup.html
/ popup.js
: Request / message is sent to the content scriptcontentScript.js
: Request / message is received from the popup pagecontentScript.js
: The title and URL of the current tab are stored in a variablecontentScript.js
: The 2 variables are sent as a stringified responsepopup.html
/ popup.js
: The 2 variables are parsed from the responseUsually I'd be able to figure this out but, I've read a few things that have thrown a spanner in the works, such as:
chrome.tabs.getSelected
can only be used in a background page / script. Does this mean that content scripts don't need to be used at all?I already found Chrome's message passing system difficult enough but, this has totally confused me. Hence, this post.
chrome.tabs.getSelected
is deprecated. You should use chrome.tabs.query
instead.
chrome.tabs.query
requires two parameters: a query object and a callback function that takes the array of resulting tabs as a parameter.
You can get the "current tab" by querying for all tabs which are currently active and are in the current window.
var query = { active: true, currentWindow: true };
Since the query will return a Tab array containing the current tab alone, be sure to take the first element in the callback
function callback(tabs) {
var currentTab = tabs[0]; // there will be only one in this array
console.log(currentTab); // also has properties like currentTab.id
}
Et voilà:
chrome.tabs.query(query, callback);