Sub topic 7
Standard JavaScript and web APIs under LWS
This chapter assumes you can write a basic Lightning web component and use async/await. It also assumes you know what a namespace is and that LWS isolates code by namespace, as covered earlier in this tutorial. Here you will see which standard APIs work as usual and which behave differently, and how to spot the difference in your own code.
The working model
Under Lightning Web Security (LWS), your component runs inside a JavaScript sandbox. A sandbox is a separate copy of the global environment (window, document, and the built-in objects). One sandbox exists for each namespace.
LWS does not replace the browser's APIs with its own wrappers. It gives your code the real APIs and applies distortions where needed. A distortion is a small change to one API, such as hiding a property or limiting what a function can return, so that code in one namespace cannot reach another namespace's data.
For you this means two things:
- Language features work as they do in any modern browser.
Promise,Map,Set,JSON,Intl,Arraymethods, classes, and modules all behave normally. - Web APIs that touch the page, other components, or shared state may be distorted.
What works without changes
Most everyday code needs no adjustment. This component uses only standard features:
import { LightningElement } from 'lwc';
export default class DateSummary extends LightningElement {
summary = '';
connectedCallback() {
const formatter = new Intl.DateTimeFormat('en-US', {
dateStyle: 'medium'
});
const counts = new Map();
['a', 'b', 'a'].forEach((key) => {
counts.set(key, (counts.get(key) || 0) + 1);
});
const data = structuredClone({ counts: [...counts] });
this.summary = `${formatter.format(new Date())}: ${JSON.stringify(data)}`;
}
}Nothing here depends on LWS. You can use fetch, URL, URLSearchParams, setTimeout, Promise.all, and AbortController the same way. A call to an external origin through fetch is still limited by the browser's rules, so that origin must be allowed by CORS and by your org's Content Security Policy (covered in a later chapter).
Where behavior differs
The differences show up in three places.
| Area | What to expect |
|---|---|
| `window` and globals | Your code sees the sandbox's global object. A value you set on `window` is visible to other code in the same namespace, not to other namespaces. |
| `document` queries | Reading the page outside your component is limited. Use `this.template.querySelector` for your own elements. |
| Shared state and cross-frame access | APIs that would expose another namespace's objects are distorted or blocked. |
The global behavior is the one that surprises developers most. Suppose one namespace's script sets window.appConfig = {...}. Code in a component from a different namespace will not find window.appConfig, even though both run on the same page.
// Namespace "acme": works, because both lines run in the acme sandbox
window.appConfig = { region: 'EU' };
console.log(window.appConfig.region);
// Component from another namespace: window.appConfig is undefined here.
// Pass the value with an @api property or a custom event instead.Writing code that stays inside the rules
Follow these habits and you will rarely hit a distortion:
- Treat
windowas private to your namespace. Do not use it to pass data between components. - Query the DOM through
this.template, and use@apiproperties and events to communicate. - Wrap calls to unusual or older browser APIs in
try/catchwhile you are testing, so a blocked call gives a clear message. - Prefer language built-ins over global helpers that a library attaches to
window.
Finding a blocked API
When a call is blocked, the browser console shows an error that names the API or property. A short loop works well:
- Reproduce the failure and read the console message.
- Find the line that touches
window,document, or a global. - Replace it with a template query, a public property, or an event.
- If no replacement exists, test the same call in a small component and check the documentation.
Exercise
A component in namespace "acme" sets window.selectedId = '001'. A component in namespace "partner" on the same page reads window.selectedId and gets undefined. Why does this happen, and what should you use instead?
Show answer
Each namespace runs in its own sandbox with its own global window, so a value set in the acme sandbox is not visible in the partner sandbox. Pass the value with a public @api property on the partner component, or have the acme component dispatch a custom event that carries the id.