class

ShadowRealm

class ShadowRealm

A ShadowRealm is a distinct global environment with its own global object containing its own intrinsics and built-ins (standard objects that are not bound to global variables, like the initial value of Object.prototype).

const red = new ShadowRealm();

// Realms can import modules that execute within their own environment.
// When the module resolves, it captures the binding value, or creates a new
// wrapped function that is connected to the callable binding.
const redAdd = await red.importValue('./inside-code.js', 'add');

// redAdd is a wrapped function exotic object that chains its call to the
// respective imported binding.
let result = redAdd(2, 3);

console.assert(result === 5); // yields true

// The evaluate method runs code inside the ShadowRealm without loading a
// module, though it still requires CSP relaxing.
globalThis.someValue = 1;
red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
console.assert(globalThis.someValue === 1);

// The wrapped functions can also wrap other functions the other way around.
const setUniqueValue =
await red.importValue('./inside-code.js', 'setUniqueValue');

// setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);

result = setUniqueValue((x) => x ** 3);

console.assert(result === 16); // yields true
  • sourceText: string
    ): any;
  • specifier: string,
    bindingName: string
    ): Promise<any>;

    Imports bindingName from the module at specifier, executed inside the realm, and resolves with its value. Functions come back as wrapped functions that chain their calls to the binding inside the realm.

    const red = new ShadowRealm();
    const redAdd = await red.importValue('./inside-code.js', 'add');
    console.assert(redAdd(2, 3) === 5);