0

I am trying to handle the chrome.tabs.query to return tab id.

function getTabID () {
  var tabID = ''
  chrome.tabs.query({
    active: true,
  }, function(tabs) {
    tabsID = tabs[0].id
  } 
  return tabID
}

And i am trying to get the tabID. It seems chrome.tabs.query({ is a async method.

var responseTabID = getTabID()     //calling the getTabID method.
// Code using responseTabID

So here i need to wait for the getTabID method to return the tabID. so that i am going to use that tabID further.

I can even call a method inside function(tabs) { // calling a method here }. But i need the tabID in multiple places, so i just wanted to implement a new method to return the tabID.

How to wait for the getTabID method? is it possible to using async/await?

Sam
  • 2,275
  • 9
  • 30
  • 53
  • You can use Promise or callbacks, see [How do I use promises in a Chrome extension?](https://stackoverflow.com/a/50845092). – wOxxOm Jun 06 '20 at 17:08

1 Answers1

4

You can try wrapping your callback in promise and then use await inside an async function to retrieve the tab id:-

function getTabID() {
    return new Promise((resolve, reject) => {
        try {
            chrome.tabs.query({
                active: true,
            }, function (tabs) {
                resolve(tabs[0].id);
            })
        } catch (e) {
            reject(e);
        }
    })
}

//function where you need it
async function something() {
    let responseTabID = await getTabID();
}
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39