aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • Programming

The Future of Javascript: Entering Into ShadowRealms

  • Ackley Wyndam
  • March 26, 2022
  • 5 minute read

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.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

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.
Read More  C Vs. Go: Comparing Programming Languages

 

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();

 

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');
}

 

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

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

Read More  Tools To Help Developers Provide A Positive User Experience

 

let myRealm = new ShadowRealm();

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

let fileAnalysis = runFunction();

 

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();

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')`);

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();
    console.log(window.myVariable); // Returns undefined
})

 

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:

Read More  PyTorch/XLA: Performance Debugging On TPU-VM Part 1

 

globalThis.name = "fjolt";

export function returnGlobals(property) {
  return globalThis[property];
}

 

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
})

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 codebase, 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 codebase. As such, expect to see them popping up in the future.

This feature was republished from hackernoon.com


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

Ackley Wyndam

Related Topics
  • Code
  • Coding
  • javascript
  • Programmers
  • Programming
  • Shadowrealm
You May Also Like
View Post
  • Architecture
  • Data
  • Engineering
  • People
  • Programming
  • Software Engineering
  • Technology
  • Work & Jobs

Predictions: Top 25 Careers Likely In High Demand In The Future

  • June 6, 2023
View Post
  • Programming
  • Software Engineering
  • Technology

Build a Python App to Alert You When Asteroids Are Close to Earth

  • May 22, 2023
View Post
  • Programming

Illuminating Interactions: Visual State In Jetpack Compose

  • May 20, 2023
View Post
  • Computing
  • Data
  • Programming
  • Software
  • Software Engineering

The Top 10 Data Interchange Or Data Exchange Format Used Today

  • May 11, 2023
View Post
  • Architecture
  • Programming
  • Public Cloud

From Receipts To Riches: Save Money W/ Google Cloud & Supermarket Bills – Part 1

  • May 8, 2023
View Post
  • Programming
  • Public Cloud

3 New Ways To Authorize Users To Your Private Workloads On Cloud Run

  • May 4, 2023
View Post
  • Programming
  • Public Cloud

Buffer HTTP Requests With Cloud Tasks

  • May 4, 2023
View Post
  • Programming
  • Public Cloud
  • Software
  • Software Engineering

Learn About Google Cloud’s Updated Renderer For The Maps SDK For Android

  • May 4, 2023

Stay Connected!
LATEST
  • 1
    Just make it scale: An Aurora DSQL story
    • May 29, 2025
  • 2
    Reliance on US tech providers is making IT leaders skittish
    • May 28, 2025
  • Examine the 4 types of edge computing, with examples
    • May 28, 2025
  • AI and private cloud: 2 lessons from Dell Tech World 2025
    • May 28, 2025
  • 5
    TD Synnex named as UK distributor for Cohesity
    • May 28, 2025
  • Weigh these 6 enterprise advantages of storage as a service
    • May 28, 2025
  • 7
    Broadcom’s ‘harsh’ VMware contracts are costing customers up to 1,500% more
    • May 28, 2025
  • 8
    Pulsant targets partner diversity with new IaaS solution
    • May 23, 2025
  • 9
    Growing AI workloads are causing hybrid cloud headaches
    • May 23, 2025
  • Gemma 3n 10
    Announcing Gemma 3n preview: powerful, efficient, mobile-first AI
    • May 22, 2025
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • Understand how Windows Server 2025 PAYG licensing works
    • May 20, 2025
  • By the numbers: How upskilling fills the IT skills gap
    • May 21, 2025
  • 3
    Cloud adoption isn’t all it’s cut out to be as enterprises report growing dissatisfaction
    • May 15, 2025
  • 4
    Hybrid cloud is complicated – Red Hat’s new AI assistant wants to solve that
    • May 20, 2025
  • 5
    Google is getting serious on cloud sovereignty
    • May 22, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.