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.u
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.
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.
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] || '';
}