Sub topic 2
Enabling LWS in Your Org
This chapter assumes you know basic Lightning web component structure, modern JavaScript, DOM concepts, namespaces, and static resources. Lightning Web Security (LWS) isolates component code while still allowing approved browser operations.
Enable LWS safely
Enable LWS in a sandbox first. In Setup, open Session Settings, select Use Lightning Web Security for Lightning web components and Aura components, and save. Test your components, Aura components, and third-party libraries before enabling the setting in production.
Plan the change as a migration. Record components that use global objects, direct DOM access, or external libraries. LWS can expose code that depended on undocumented browser behavior or on sharing objects between namespaces.
DOM access: what your component can reach
LWS gives a component access to the DOM that belongs to its own template. Use this.template.querySelector() or this.template.querySelectorAll() for elements rendered by that component.
import { LightningElement } from 'lwc';
export default class FocusInput extends LightningElement {
handleClick() {
const input = this.template.querySelector('lightning-input');
if (input) {
input.focus();
}
}
}A component should not search the document for another component's internal elements. Do not depend on another component's shadow DOM, private fields, or global variables. Communicate through public properties and events instead.
Standard JavaScript and web APIs under LWS
LWS supports normal JavaScript language features and many standard web APIs, but it mediates access to sensitive objects. Use APIs through the component or platform-supported interfaces. For example, use this.template for component DOM access and Salesforce resource loaders for static resources.
Avoid assuming that window, document, storage, timers, or network APIs behave like unrestricted page-level APIs. Content Security Policy can also block connections or scripts even when LWS allows the JavaScript operation.
If an API fails, determine whether LWS denied access, CSP blocked the resource, or the library depends on unsupported internals. Change the code or replace the library rather than bypassing the security boundary.
Exercise
Where should an LWC query an input rendered by its own template?
Show answer
It should call this.template.querySelector() and avoid querying another component's DOM.