How ShadowRealm Can Safely Isolate Untrusted JavaScript in the Browser
ShadowRealm, a forthcoming ECMAScript standard now at TC39 Stage 3, lets developers create isolated JavaScript global environments without DOM overhead, offering a lightweight alternative to iframes and eval for securely executing third‑party code, with APIs like new ShadowRealm(), evaluate() and importValue().
We often need to handle code from various sources—third‑party ads, analytics scripts, user plugins, or dynamically loaded modules. Integrating such untrusted or semi‑trusted code into applications carries significant risk.
Developers have tried solutions such as iframe, Web Workers, and even the dangerous eval, but each has drawbacks: iframe is heavyweight with complex communication; Web Workers are asynchronous and unsuitable for synchronous scenarios; eval provides no isolation.
What is ShadowRealm?
ShadowRealm is a proposed ECMAScript standard that allows developers to create a brand‑new, isolated JavaScript global environment .
It can be thought of as a lightweight, JavaScript‑only iframe without DOM or rendering overhead, and it enables controlled synchronous communication.
Each ShadowRealm instance has its own independent global object ( globalThis) and a full set of built‑in objects (Object, Array, Promise, etc.). Code executed inside cannot access the main page’s window or document, providing strong security isolation.
Core Concepts and API Usage
The API is deliberately simple and includes the following parts:
Creating a Realm :
Use the constructor new ShadowRealm() to easily create a new realm.
// In the main environment
const realm = new ShadowRealm();Executing Code :
Use the evaluate() method to run a JavaScript code string inside the realm. It returns a Promise whose resolved value is the execution result.
Note : Code evaluated cannot access any variables from the outer scope.
Importing Functions :
While evaluate() is useful, the more powerful importValue() method lets you import a function defined inside the realm for use in the main environment.
// `greet` is a function defined in the evaluate call above
const wrappedGreet = await realm.importValue(
// 'greet' is the global function name inside the Realm
'greet'
);
// Call the wrapped function
const message = await wrappedGreet('World');
console.log(message); // Outputs: "Hello from the Realm, World!"As of now, the ShadowRealm API is at TC39 Stage 3 , meaning its design is stable and awaiting broad browser implementation and final approval.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
