Intoli

Intoli Remote Browser Tour

Evaluating Code in Individual Tabs

The background script context is great for interacting with the Web Extensions API, but you'll often also want to interact with the Document Object Model (DOM) of individual tabs in order to do things like fill out forms, click on elements, or extract content from a page. Remote Browser allows you to access individual tabs from what is known as the content script context. This is essentially the standard page context for a specific tab with a limited subset of the Web Extensions API also available.

The syntax for evaluating code inside of individual tabs is very similar to that of evaluating code in the background script. We specify the code using the same basic method signature, but we additionally need to specify which tab we're interested in. To do so, we use the Web Extension API's browser.tabs.Tab.id identifer which we specify by using square brackets on the Browser client object before calling it. You can see how this compares to evaluating code in the background script here.

// Evaluate code in the background script context.
await browser(myFunction, ...myArgs);

// Evaluate code in the content script context for a tab.
await browser[tabId](myFunction, ...myArgs);

In the example to the right, we use this syntax to retrieve the value of window.location.href from the tab's content script context. This allows us to verify that the tab actually navigated to the correct URL. We'll get to some more realistic examples shortly, but this illustrates how you can access the page context of individual tabs.

4/7
import Browser from 'remote-browser';
// Launch a remote browser instance.
const browser = new Browser();
await browser.launch();
// Navigate to the Intoli Blog in the current
    tab.
const tab = await browser.tabs.update({ url:
    'https://intoli.com/blog' });
// Square brackets allow us to access the
    content script context.
const tabUrl = await browser[tab.id](() =>
    window.location.href);
console.log(`URL: ${tabUrl}`)
// Clean up the browser.
await browser.quit();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX