How to query the URL of the currently active tab in a background script

51 Views Asked by At

I have recently started writing a privacy extension that requires me to create a list of active domains to run a background task for each. I'm new to writing browser extensions, but my idea was to query the active tab using browser.tabs.query inside a chrome.tabs.onActivated event listener.

let activeTabDomain
const getActiveTabDomain = tabs => {
  activeTabDomain = tabs[0].url
}

const onError = _ => {
  activeTabDomain = "none"
}

chrome.tabs.onActivated.addListener(activeInfo => {
  browser.tabs.query({active: true, currentWindow: true}).then(getActiveTabDomain, onError)
  if (activeTabDomain) {
    const match = activeTabDomain.match(/^(?:https?:\/\/)?(?:www\.)?([^/#]+)/)
    if (match) activeTabDomain = match[1]
    console.log(`domain: ${activeTabDomain}`)
  }                                                                                 
})  

However, when I run this code in a background script, the outcome I get is always the previous active domain being printed. Am I doing something wrong with the event listener?

0

There are 0 best solutions below