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  Streamline Open-Source Security Compliance On Kubernetes With Tanzu Application Catalog

 

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  Kubernetes RBAC 101: Authorization

 

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  Why Hackers Should Learn Python For Pen Testing

 

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
    Pure Accelerate 2025: All the news and updates live from Las Vegas
    • June 18, 2025
  • 2
    ‘This was a very purposeful strategy’: Pure Storage unveils Enterprise Data Cloud in bid to unify data storage, management
    • June 18, 2025
  • What is cloud bursting?
    • June 18, 2025
  • 4
    There’s a ‘cloud reset’ underway, and VMware Cloud Foundation 9.0 is a chance for Broadcom to pounce on it
    • June 17, 2025
  • What is confidential computing?
    • June 17, 2025
  • Oracle adds xAI Grok models to OCI
    • June 17, 2025
  • Fine-tune your storage-as-a-service approach
    • June 16, 2025
  • 8
    Advanced audio dialog and generation with Gemini 2.5
    • June 15, 2025
  • 9
    A Father’s Day Gift for Every Pop and Papa
    • June 13, 2025
  • 10
    Global cloud spending might be booming, but AWS is trailing Microsoft and Google
    • June 13, 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
  • Google Cloud, Cloudflare struck by widespread outages
    • June 12, 2025
  • What is PC as a service (PCaaS)?
    • June 12, 2025
  • 3
    Crayon targets mid-market gains with expanded Google Cloud partnership
    • June 10, 2025
  • By the numbers: Use AI to fill the IT skills gap
    • June 11, 2025
  • 5
    Apple services deliver powerful features and intelligent updates to users this autumn
    • June 11, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.