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?
chrome.tabs.getSelectedis 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
getSelectedhas been deprecated and replaced withchrome.tabs.querysince Chrome 16.Maintain a hash with the current URLs using
chrome.tabs.onUpdated(add tabID + URL),chrome.tabs.onRemoved(to remove obsolete entries) andchrome.tabs.onActivated(to set the current active tab).Code for 2: