chrome.tabs.getSelected
has been deprecated. so we should use tabs.query({active: true}...
instead.
chrome.tabs.getCurrent
passes a single tab to the callback function. It doesn't "Getting URL of All Opened Tabs", it:
Gets the tab that this script call is being made from. May be undefined if called from a non-tab context (for example: a background page or popup view).
So:
// Write the URL of the current tab to the console
chrome.tabs.getCurrent(tab => console.log(tab.url));
This requires the "activeTab"
or "tabs"
permission in the manifest. If there is an error it won't throw an exception, instead it will populate chrome.runtime.lastError
.
I find it easier to deal with all the callbacks using an asynchronous or promise wrapper library like chrome-extension-async
. This let's us use async
/await
syntax and a regular try-catch
:
try {
const currentTab = await chrome.tabs.getCurrent();
console.log(currentTab.url);
}
catch(err) {
// Handle errors
}
In your popup.html
you can't access chrome.tabs.getCurrent
- you have to use chrome.tabs.query
instead:
async function writeAllTabUrlToConsole() {
try {
// Get all the tabs
const tabs = await chrome.tabs.query({});
// Write all their URLs to the popup's console
for(let t of tabs)
console.log(t.url, t.active);
}
catch(err) {
// Handle errors
}
}