Intoli

Intoli Remote Browser Tour

Background Script Evaluation

Web Extensions have a concept of background scripts which are code that runs in a persistent browser page context with access to the Web Extensions API. You can do privileged things like open new tabs, intercept and modify HTTP requests, and adjust browser proxy settings from the background script context. We'll get to some more interesting examples later, but, for now, let's just look at how Remote Browser provides access to this context.

We already saw how we can make calls like browser.tabs.update() directly on an instance of a Browser object in the previous step of the tour. What's going on behind the scenes when we do this is that the Remote Browser Web Extension is informed that it needs to evaluate this call in the background script, and then the method's response is sent back to the client. It's also possible to have your own functions evaluated remotely in the privileged background script context.

The syntax for doing this is to simply call a Browser instance like a function and pass the function to evaluate as an argument. The remote function can also be called with arguments from the local environment by passing them as additional arguments after the function itself. This is what Remote Browser does internally when you use the Web Extensions API, and the following two lines are effectively identical.

// Execute a function remotely using `browser(remoteFunction, ...remoteArgs)`.
await browser(url => browser.tabs.update({ url }), 'https://intoli.com');

// A shorthand for the above that doesn't require explicitly passing arguments.
await browser.tabs.update({ url: 'https://intoli.com' });

The code example on the right prints out the URL that the browser autogenerates for the background page context where the background script is executing. We determine the URL by defining a function that returns the value of window.location.href and then evaluating this in the background script context. Our remote function could just as easily make network requests, interact with local storage, or do anything else that would be possible in the background script context of an extension.

3/7
import Browser from 'remote-browser';
// Launch a remote browser instance.
const browser = new Browser();
await browser.launch();
// Find the window location of the background
    page.
const backgroundUrl = await browser(() =>
    window.location.href);
console.log('URL of the background page:');
console.log(backgroundUrl)
// Clean up the browser.
await browser.quit();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX