Sub topic 7
Standard JavaScript and web APIs under LWS
This chapter covers which standard JavaScript and browser APIs your component can use under Lightning Web Security (LWS), what changes when you call them, and how to handle the cases where they behave differently. It assumes you know the following:
- You can write a basic Lightning web component with a template, a JavaScript class, and a metadata file.
- You are comfortable with modern JavaScript, including modules and
async/await. - You know what the same-origin policy is.
- You know what a namespace is, and the earlier chapters' explanation of how LWS gives each namespace its own sandbox.
The working model: the same language, a different global object
LWS does not replace JavaScript. Your component still runs in the browser's JavaScript engine, and the language itself (classes, promises, Map, Set, JSON, Math, Intl, typed arrays) works as you expect. What LWS changes is the set of objects your code receives when it reaches for browser globals such as window, document, and the prototypes of DOM classes.
Your namespace's code runs in a sandbox. Inside it, window is not the real browser window. It is a stand-in object that forwards most operations to the real one. For a small set of APIs, LWS applies a distortion, which is a replacement or wrapper for the standard behavior. The distortion exists to stop code in one namespace from reading or changing data that belongs to another namespace or to the platform.
For most code the result is invisible. A call like Math.max(1, 2) or new Date() behaves identically. Distortions show up in three situations:
- Your code reaches outside its own component, for example with
document.querySelector. - Your code stores data on a shared global, such as
window.myCache = {}, and expects another namespace to read it. - A library inspects or patches built-in prototypes, which is common in older libraries.
Language features and built-in objects
Everything defined by the ECMAScript standard works under LWS. That includes the following:
- Syntax: classes, destructuring, optional chaining, generators, and async iteration.
- Collections and data:
Array,Map,Set,WeakMap,JSON,BigInt, andSymbol. - Internationalization:
Intl.NumberFormat,Intl.DateTimeFormat, and related objects. - Asynchronous tools:
Promise,setTimeout,setInterval, andqueueMicrotask.
Two points matter for intermediate developers.
First, LWS leaves your own objects alone. If you create a class or a plain object, no proxy wraps it. This is different from Lightning Locker, where objects crossing certain boundaries were wrapped in secure proxies and could fail instanceof checks or identity comparisons. Under LWS you can generally compare, serialize, and spread your own data without surprises.
Second, built-in prototypes are shared inside a namespace sandbox but not across namespaces. If your code adds a method to Array.prototype, other code in your namespace may see it, but a component in another namespace will not. Treat patching built-ins as unsupported anyway, because it breaks as soon as a library depends on a clean prototype.
Web APIs you can normally use
Browser APIs are available when they apply to your own component's content or to neutral features of the page. The table below summarizes common categories. Use it as a starting point and check the current Salesforce documentation, because distortions are updated between releases.
| API category | Examples | Typical behavior under LWS |
|---|---|---|
| Timers and scheduling | `setTimeout`, `requestAnimationFrame` | Work normally |
| Network | `fetch`, `XMLHttpRequest` | Work, but are limited by Content Security Policy and the org's trusted sites |
| URL and encoding | `URL`, `URLSearchParams`, `TextEncoder`, `atob` | Work normally |
| Formatting | `Intl.*`, `Date`, `toLocaleString` | Work normally |
| Own-template DOM | `this.template.querySelector`, `classList`, `addEventListener` | Work normally |
| Document-wide DOM | `document.querySelector`, `document.body` | Restricted: results are limited to what your namespace may see |
| Global state | `window.foo = value` | Visible only inside your namespace's sandbox |
| Storage | `localStorage`, `sessionStorage` | Available, but test your use case, since the sandbox may scope or restrict data |
| Dynamic code | `eval`, `new Function` | Governed by CSP and often blocked |
The document-wide DOM row is the most common source of confusion. The next chapters on DOM access cover it in detail, so here the rule is simply to query through this.template whenever you can.
Example: using several standard APIs together
The following component uses URLSearchParams, Intl.NumberFormat, fetch with error handling, and this.template for DOM access. It has no other dependencies and works under LWS.
<template>
<lightning-card title="Price Lookup">
<div class="slds-var-p-around_medium">
<lightning-input label="Product code" data-id="code"></lightning-input>
<lightning-button label="Look up" onclick={handleLookup}></lightning-button>
<p data-id="result">{message}</p>
</div>
</lightning-card>
</template>import { LightningElement } from 'lwc';
export default class PriceLookup extends LightningElement {
message = 'Enter a code and press the button.';
async handleLookup() {
// Query only inside this component's own template.
const input = this.template.querySelector('lightning-input[data-id="code"]');
const code = input ? input.value : '';
if (!code) {
this.message = 'A product code is required.';
return;
}
// URLSearchParams builds a safe query string.
const params = new URLSearchParams({ code });
const url = `/services/apexrest/prices?${params.toString()}`;
try {
const response = await fetch(url, {
headers: { Accept: 'application/json' }
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: data.currency || 'USD'
});
this.message = `Price: ${formatter.format(data.amount)}`;
} catch (error) {
// Network, CSP, and parsing failures all end up here.
this.message = 'Lookup failed. Check the console for details.';
console.error('Price lookup failed', error);
}
}
}Note that the endpoint path is an example. In a real org you would usually call an Apex method with @AuraEnabled instead of fetch against a REST resource. Apex calls from LWC are not affected by CSP restrictions on outbound network access, and they follow the platform's own security checks. Use fetch for external services and for cases where the platform does not offer a wire adapter or Apex alternative.
Global state and window properties
Developers often use window as a place to share a value. Under LWS, the window your code sees belongs to your namespace's sandbox.
- Two components in the same namespace share one sandbox. If component A sets
window.appConfig = {...}, component B in the same namespace can read it. - A component in a different namespace gets a different sandbox. It will see
window.appConfigasundefined.
This is intended. It prevents a managed package from reading your custom globals, and it prevents yours from reading theirs. If you rely on a window property to coordinate with another namespace, the code breaks silently: no error is thrown, you just read undefined.
The replacement is explicit communication. Use public @api properties for data flowing down, custom events for data flowing up, and Lightning Message Service for components that are not in the same DOM tree. A later chapter covers these patterns.
Distortions you may notice
A distortion changes a specific API so that it respects the namespace boundary. The exact list changes over time, and some entries are narrow. The patterns you should recognize are these:
- Scoped queries. Document-level query methods return only nodes your namespace is allowed to see. A query that finds an element in the browser console may return
nullin your component. - Restricted property access. Reading properties of objects owned by another namespace, such as an element created by another namespace's component, can return a limited view or throw.
- Blocked or filtered features. Some capabilities that would let code escape the sandbox, such as certain ways to reach the real global object, are removed or replaced.
When you hit a distortion, resist the urge to work around it with tricks like Function('return this')() or walking constructor chains. Those techniques target the sandbox itself, and they either fail or break across releases. Change the design so that the component only uses its own template and the public interfaces of others.
Feature detection
Because distortions vary by API and release, do not assume that an API behaves the same in every context. Two habits keep components resilient:
- Detect before use. Check that the function exists and, where it matters, test it with a harmless call.
- Fail visibly. Wrap calls that may be distorted in
try/catchand log the error with enough context to diagnose it.
import { LightningElement } from 'lwc';
export default class StorageProbe extends LightningElement {
status = 'Not checked';
connectedCallback() {
this.status = this.canUseSessionStorage()
? 'Session storage works'
: 'Session storage unavailable; using in-memory fallback';
}
canUseSessionStorage() {
try {
const key = '__lws_probe__';
window.sessionStorage.setItem(key, '1');
window.sessionStorage.removeItem(key);
return true;
} catch (error) {
console.warn('sessionStorage probe failed', error);
return false;
}
}
}This pattern also helps outside LWS, since browsers can disable storage for reasons unrelated to Salesforce, such as privacy settings.
Network access and CSP
fetch and XMLHttpRequest are allowed by LWS, but LWS does not override Content Security Policy. If your org's CSP does not list the target host as a trusted site, the browser blocks the request and you see a CSP violation in the console. A failed request that never shows up in the Network tab usually means CSP, not LWS. A later chapter covers CSP configuration.
Common errors
- A query returns
nullthat works in dev tools. You useddocument.querySelectorfor an element your namespace does not own. Switch tothis.template.querySelectorand give elementsdata-idattributes. - A shared global is
undefinedin another package. The namespaces have separate sandboxes. Pass the value through@apior an event. - A library works in one org and fails in another. The orgs may differ in whether LWS is enabled. Test with the setting that production uses.
- An
instanceofcheck fails on an object from a library. Make sure the library and your component are loaded in the same namespace, so they share one sandbox.
Exercise
A component in namespace acme sets window.settings = { theme: 'dark' }. A component in namespace globex on the same page reads window.settings.theme and gets a TypeError. What explains this, and what should the developers change?
Show answer
Under LWS each namespace runs in its own sandbox with its own window object, so the globex component sees window.settings as undefined and reading .theme throws. They should stop sharing data through globals. The acme component should expose the value through a public @api property or send it in a custom event, or the two components can use Lightning Message Service if they are not in the same DOM tree.
Exercise
Why is this.template.querySelector preferred over document.querySelector in an LWS component, and what does the first return when no matching element exists in the component's own template?
Show answer
this.template.querySelector searches only the component's own rendered template, which LWS always allows. document.querySelector searches the whole document, and under LWS its results are restricted to nodes the namespace may see, so it can return null for elements that exist on the page. When no element matches in the component's own template, this.template.querySelector returns null, so the code should check the result before using it.