Salesforce Certified Application Architect

Friday 6 October 2017

LockerService: DOM Access Containment

LockerService enhances security by isolating Lightning components in their own namespace. Due to this, a component can only traverse the DOM and access elements created by a component in the same namespace. Let’s look at a sample component that demonstrates DOM containment.

<!--c:domLocker-->
<aura:component>
    <div id="myDiv" aura:id="div1">
        <p>See how LockerService restricts DOM access</p>
    </div>
    <lightning:button name="myButton" label="Peek in DOM" aura:id="button1" onclick="{!c.peekInDom}"/>
</aura:component>
 
 
 
 
({ /* domLockerController.js */
    peekInDom : function(cmp, event, helper) {
        console.log("cmp.getElements(): ", cmp.getElements());
        // access the DOM in c:domLocker
        console.log("div1: ", cmp.find("div1").getElement());
        console.log("button1: ", cmp.find("button1"));
        console.log("button name: ", event.getSource().get("v.name"));

        // returns an error
        //console.log("button1 element: ", cmp.find("button1").getElement());
    }
}) 


You can't use cmp.find("button1").getElement() to access the DOM element created by <lightning:button>

LockerService doesn't allow c:domLocker to access the DOM for <lightning:button> because the button is in the lightning namespace and c:domLocker is in the c namespace.

So, use cmp.find("myInput").get("v.name") instead of cmp.find("myInput").getElement().name. The latter doesn’t work if you don’t have access to the component, such as a component in another namespace

No comments:

Post a Comment

Salesforce Certified Application Architect & Certified Data Architecture and Management Designer Exam

How to pass Salesforce Certified Data Architecture and Management Designer Exam This exam was 1st architect exam for me. Its not that muc...