Behseini
Behseini

Reputation: 6320

Getting current tabs and selected tab URL on Chrome API

I am trying to get the URL of all opened Tabs and Selected Tab using these two snippets:

// For Getting URL of All Opened Tabs
chrome.tabs.getCurrent(function(tabs) {
for (var i = 0; i < tabs.length; i++) {
    console.log(tab.url);
     }
});

// For Getting URL of Selected Tab
chrome.tabs.getSelected(function(tab) {
     console.log(tab.url);
});

but neither of them working. For getting all tabs I am getting this error:

Error in response to tabs.getCurrent: TypeError: Cannot read property 'length' of undefined

and for getting the selected tab:

undefined

Why is this happening and how can I fix it?

enter image description here

Upvotes: -2

Views: 3381

Answers (1)

Keith
Keith

Reputation: 155682

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
    }
}

Upvotes: 2

Related Questions