Inline JavaScript
Why is this an issue?
Inline JavaScript (code in <script> tags or event handler attributes) creates security and maintenance concerns:
XSS risk: Inline JavaScript can increase exposure to cross-site scripting attacks when combined with unsanitized dynamic content
CSP violations: Content Security Policy often blocks inline scripts, especially in Lightning. Allowing them requires the
'unsafe-inline'CSP directive, which weakens your security policyNo independent caching: Inline scripts cannot be cached separately from the page, causing redundant downloads across multiple pages
Maintenance difficulty: JavaScript mixed in with HTML can be hard to maintain
Examples
Visualforce
Example of incorrect code:
<apex:page>
<script>
function openPopup() {
window.open('/apex/MyPopup', 'Popup', 'width=700,height=500');
}
</script>
<apex:commandButton value="Open" onclick="openPopup()"/>
</apex:page>
Example of correct code:
<apex:page>
<apex:includeScript value="{!$Resource.PopupUtils}"/>
<apex:commandButton value="Open" onclick="openPopup()"/>
</apex:page>
With external JavaScript file (PopupUtils static resource):
function openPopup() {
window.open('/apex/MyPopup', 'Popup', 'width=700,height=500');
}
Aura
Example of incorrect code:
<aura:component>
<button onclick="document.getElementById('modal').style.display='none'">Close</button>
</aura:component>
Example of correct code:
<aura:component>
<button onclick="{!c.closeModal}">Close</button>
</aura:component>
With example controller file myComponentController.js:
({
closeModal : function(component, event, helper) {
component.set('v.showModal', false);
}
})
How can I fix violations?
Visualforce: Move inline
<script>blocks to static resources and include them with<apex:includeScript>. UseloadOnReady="true"if the script accesses DOM elements, so that it executes when the DOM has loaded.Aura: Replace inline event handlers with controller bindings (e.g.,
onclick="{!c.handleClick}"), or view attribute bindings for actions passed from a parent component.
When should I disable this rule?
You may want to dismiss Visualforce violations of this rule in cases when scripts must execute immediately during page load (e.g. third-party error monitoring scripts), where time spent waiting for an external script file to load could result in missed events.
Resources
