user962284
user962284

Reputation: 678

Get current tab and pass it to variable in a Chrome Extension

I'm trying to create a function that returns the current tab url:

function tabURL() {
var url="";
chrome.tabs.getSelected(null, function(tab) {url = tab.url;});
return url;
}

When I use:

chrome.tabs.getSelected(null, function(tab) {alert(tab.url);});

Chrome shows the url, but if I use my function inside the chrome console, the function returns "".

Is there a way to pass the tab.url to a variable and then return this variable?

Upvotes: 0

Views: 4739

Answers (1)

Rob W
Rob W

Reputation: 348992

chrome.tabs.getSelected is asynchronous. That means that when the callback function is called, return url "has already occurred".

You've got two options to achieve the desired effect.

  1. Properly rewrite your code, to correctly implement the asynchronous aspect (the exact details depends on your extension's implementation).
    Note that getSelected has been deprecated and replaced with chrome.tabs.query since Chrome 16.

  2. Maintain a hash with the current URLs using chrome.tabs.onUpdated (add tabID + URL), chrome.tabs.onRemoved (to remove obsolete entries) and chrome.tabs.onActivated (to set the current active tab).

Code for 2:

// Our hash
var tabIdToURL = {};
var currentTabId = -1;
// Add changes to the hash (tab creation, tab's page load)
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    tabIdToURL[tabId] = tab.url; // also available as tab.id and changeInfo.url
});
// Remove entries from closed tabs
chrome.tabs.onRemoved.addListener(function(tabId) {
    delete tabIdToURL[tabId];
});
// Set the ID of the current active tab
chrome.tabs.onActivated.addListener(function(activeInfo) {
    currentTabId = activeInfo.tabId;
});

// Usage, based on the question's function
function getURL() {
    return tabIdToURL[currentTabId] || '';
}

Upvotes: 6

Related Questions