0

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.

Chris
  • 11,819
  • 19
  • 91
  • 145
  • Content scripts can communicate with background scripts via messages https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Communicating_with_background_scripts – Kris Dec 12 '20 at 18:18
  • See https://vzurczak.wordpress.com/2017/11/23/getting-the-source-code-of-a-tab-from-a-web-extension/ for an example – Kris Dec 12 '20 at 18:52

1 Answers1

1

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);`
});
erosman
  • 7,094
  • 7
  • 27
  • 46
  • 1
    How would I then get the window/document of that tab? I don't see anything in the docs or in their examples – Chris Jan 01 '20 at 18:43