I'm building a toolbar button extension for Firefox. In my background script, I need to access the document
for the current tab when the toolbar button is clicked.
window
in this context is the window for the extension, not for the current tab. Other functions like browser.tabs.getCurrent()
don't work in background scripts.
I know it is possible since other extensions have access to the current document (e.g. 1Password will identify and fill input
elements.)
Note: All of the previous questions on SO about the same functionality from 2010, 2012, etc. are no longer value.
To get the active tab in the current window you can use tabs.query()
e.g.:
browser.tabs.query({currentWindow: true, active: true})
That is how to get the active tab.
Tab is separate from the content page (web page). In order to interact with the context page, you would need to inject your code into the page.
For example using tabs.executeScript()
As you are injecting into the active tab, there is no need to get the active tab separately any more, since tabs.executeScript()
would inject into the active tab if tabId
is omitted.
e.g.:
browser.tabs.executeScript({
code: `console.log('location:', window.location.href);`
});