getSelected :
Deprecated since Chrome 33.
This feature is deprecated and not recommended for use.
You can use the query function. Sort of:
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) { alert(tabs[0].id); });
We get the active tab in the current window. You can operate on the result in the callback function, which is passed as a parameter to the query function.
When executing, an external alert is first executed, setting an empty value, then an internal one, showing the required identifier.
Read about Asynchronous vs. synchronous methods on developer.chrome.com
Code
chrome.windows.getCurrent(function(w){ chrome.tabs.getSelected(w.id,function(t){ tabId = t.id + ''; alert(tabId); }) });
asynchronous. That is, at the time of calling the external alert'a it is in the process of being executed and therefore you first receive an external alert with an empty value, and after it has been processed, you receive an internal alert with the desired value.
UPD to comment
With all due respect, I did not understand. I don’t want to operate with the tabId within the callback function. I don’t understand how to output it using the “other function” that accepts tabId.
function someFunction(tabId) { // Делаем что-то с tabId. // Например alert(tabId); } chrome.tabs.query({active: true, currentWindow: true}, function (tabs) { someFunction(tabs[0].id); });
Or you can use promise :
function getTabId() { return new Promise(function (resolve, reject) { chrome.tabs.query({active: true, currentWindow: true}, function (tabs) { resolve(tabs[0].id); // Может еще что-то. reject или.. }); }); }
Next, call the getTabId function getTabId
getTabId().then(function (tabId) { // Делаем что-то с tabId // Например alert(tabId); });
In short
Promise need to work with asynchronous code.
In the first part, we wrote a wrapper function that returns a promise object. It accepts a callback function with two parameters, resolve and reject . resolve used when the operation is successfully completed, that is, we return the result with tabId . In case of any errors we use reject .
Next, when calling the getTabId function, getTabId use the then method which accepts the callback function with the tabId parameter (we passed its value to resolve).
There is a good article about their use (translation). Original
And some more material on MDN - Promise
I think this is enough for understanding.