Get the active tab in a chrome extension (includes fallbacks)

PHOTO EMBED

Mon Jul 11 2022 18:47:53 GMT+0000 (Coordinated Universal Time)

Saved by @Explosion #javascript #chrome #extension

function getActiveTab(){
   return new Promise((r, reject) => {
      chrome.tabs.query({
         active: true,
         lastFocusedWindow: true,
      }, (tabs) => {
         if (tabs.length){
            r(tabs[0]);
         } else {
            chrome.tabs.query({}, tabs => {
               if (tabs.length){
                  if (tabs.length === 1){
                     r(tabs[0]);
                  } else if (tabs.find(i => i.active)){
                     r(tabs.find(i => i.active))
                  } else {
                     reject("No tab found");
                  }
               } else {
                  reject("No tab found");
               }
            })
         }
      })
   });
}
content_copyCOPY

https://gist.github.com/Explosion-Scratch/4e868a4a55da531b6715c9461cea88a2