DEV Community

Cover image for Future Javascript: ShadowRealms
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

Future Javascript: ShadowRealms

It sounds dark and mysterious - but it's just another future Javascript feature. The ShadowRealm is a new feature coming to Javascript, which will let us create a separate global context from which to execute Javascript. In this article, we'll look at what the ShadowRealm is, and how it works.

Support for ShadowRealms in Javascript

ShadowRealms are a Javascript proposal, currently at Stage 3. As such, ShadowRealms do not have support in browsers or natively in server side languages like Node.JS, and given it has had many changes over the years, there is no stable babel or npm plugin to polyfill the functionality. However, given it has reached Stage 3, this means there won't be very many changes going forward, and we can expect ShadowRealms to have native support at some point in the future.

How ShadowRealms in Javascript work

A ShadowRealm is ultimately a way to set up a totally new environment with a different global object, separating the code off from other realms. When we talk about a global object in Javascript, we are referring to the concept of window or globalThis. The problem that ShadowRealm ultimately tries to solve, is to reduce conflict between different sets of code, and provide a safe environment for executing and running code that needs to be run in isolation. It means less pollution in the global object from other pieces of code or packages. As such, code within a ShadowRealm cannot interact with objects in different realms.

ShadowRealm Use Cases:

  1. Code editors where the user can edit code, and which we don't want to interact with the main webpage.
  2. Plugins that can be executed independently.
  3. Emulating the DOM in a separated environment, i.e. if we need to know the scroll position in certain scenarios, we could emulate it within a ShadowRealm so that the user scrolling on the main webpage would not affect the window.top variable in our emulation.

ShadowRealms run on the same thread as all other Javascript - so if you want to multi-thread your Javascript, you still have to use Web Workers. As such, a ShadowRealm can exist within a worker, as well as within a regular Javascript file. ShadowRealms can even exist within other ShadowRealms.

Creating a ShadowRealm in Javascript

Let's look at how a ShadowRealm actually looks in code. The first thing we have to do is call a new ShadowRealm instance. We can then import some Javascript into our Realm, which will run within it. For this, we use a function called importValue, which works effectively in the same way as import.

let myRealm = new ShadowRealm();

let myFunction = await myRealm.importValue('./function-script.js', 'analyseFiles');

// Now we can run our function within our ShadowRealm
let fileAnalysis = myFunctions();
Enter fullscreen mode Exit fullscreen mode

In the above example, analyseFiles is the export name we are importing from function-script.js. We then capture and store this export within myFunction. Significantly, the export we import into our realm must be callable, so it must effectively be a function we can run.

Our function-script.js file is just a normal Javascript file with an export. It may look something like this:

export function analyseFiles() {
    console.log('hello');
}
Enter fullscreen mode Exit fullscreen mode

The ShadowRealm is totally separate from other global objects we may have, such as window or globalThis.

Similar to other imports, we can use the curly bracket import notation:

let myRealm = new ShadowRealm();

const { runFunction, testFunction, createFunction } = await myRealm.importValue('./function-script.js');

let fileAnalysis = runFunction();
Enter fullscreen mode Exit fullscreen mode

Or, we can create multiple promises that all translate into an array if we want to use named importValues.

let myRealm = new ShadowRealm();

const [ runFunction, testFunction, createFunction ] = await Promise.all([
    myRealm.importValue('./file-one.js', 'runFunction'),
    myRealm.importValue('./file-two.js', 'testFunction'),
    myRealm.importValue('./file-three.js', 'createFunction'),
]);

let fileAnalysis = runFunction();
Enter fullscreen mode Exit fullscreen mode

Executing Code with evaluate in ShadowRealms

Should we want to execute code directly in a ShadowRealm, which does not come from another file, we can use the evaluate method on our ShadowRealm, to execute a string of Javascript. This works in much the same way as eval():

let myRealm = new ShadowRealm();

myRealm.evaluate(`console.log('hello')`);
Enter fullscreen mode Exit fullscreen mode

ShadowRealm importValue is thennable

Since importValue returns a promise, its value is thennable. That means we can use then() on it, and then do something with the output function that it returns. For example:

window.myVariable = 'hello';
let myRealm = new ShadowRealm();

myRealm.importValue('someFile.js', 'createFunction').then((createFunction) => {
    // Do something with createFunction();
})
Enter fullscreen mode Exit fullscreen mode

We can also use this methodology to access global variables defined in someFile.js. For example, let's say we changed someFile.js to this:

globalThis.name = "fjolt";

export function returnGlobals(property) {
  return globalThis[property];
}
Enter fullscreen mode Exit fullscreen mode

Now, in our then function, we could get the value of globalThis.name:

window.myVariable = 'hello';
let myRealm = new ShadowRealm();

myRealm.importValue('someFile.js', 'returnGlobals').then((returnGlobals) => {
    // Do something with returnGlobals();
    console.log(returnGlobals("name")); // Returns fjolt
    console.log(window.myVariable); // Returns undefined
})
Enter fullscreen mode Exit fullscreen mode

Conclusion

Today, iframes are the way we usually separate out separate environments on the web. iframes are clunky, and can be quite annoying to work with. ShadowRealms on the other hand, are more efficient, allow us to easily integrate with our existing code base, and integrate well with modern Javascript technologies like Web Workers.

Given their unique value proposition of providing a separated area for code execution, which does not interact at all with the rest of the code base, ShadowRealms will likely become a staple in writing Javascript code. They could become an important way for packages and modules to export their contents without worrying about interference from other parts of the code base. As such, expect to see them popping up in the future.

Read about the ShadowRealm specification here.

Top comments (2)

Collapse
 
amatiasq profile image
A. Matías Quezada

Can't wait for this, looks like JavaScript is finally becoming the mature environment we need.

Few notes as feedback:

Where you say "Or, we can create multiple promises that all translate into an array if we want to use named importValues." I'm the example you destructure the result of Promise.all as an object, did you mean to use square brackets?

Also in the last snippet it says "console.log(window.myVariable); // Returns undefined
})". I don't understand why would it return undefined, we set window.myVariable to "hello" in the first line.

Thanks for this series, it's nice to have a glimpse of the future.

Collapse
 
smpnjn profile image
Johnny Simpson

On your last point, I re-read the code and realised you were right. I've fixed it now.