Inline JavaScript Event Handler

ID

html.inline_javascript_event_handler

Severity

low

Resource

Injection

Language

Html

Tags

CWE:79, NIST.SP.800-53, OWASP:2021:A4, PCI-DSS:6.5.4, PCI-DSS:6.5.6

Description

This rule identifies the use of inline JavaScript event handlers (such as onclick, onerror, or onload) within HTML elements. These handlers execute code defined directly in the HTML attribute rather than in an external or encapsulated script.

Rationale

Inline event handlers pose significant security and maintainability risks:

Content Security Policy (CSP) Bypass: A robust CSP often forbids unsafe-inline scripts to prevent Cross-Site Scripting (XSS). Inline handlers are blocked by such policies unless dangerous exceptions are made.

Attack Surface: They provide a primary injection point for XSS attacks. If an attacker can inject an attribute into an HTML tag, they can execute arbitrary code.

Code Maintenance: Mixing logic (JavaScript) with presentation (HTML) makes the codebase harder to audit, test, and debug.

Consider the following code:

<button onclick="alert('Button clicked!')">Click Me</button>

<img src="profile.jpg" onerror="logError('UserID: ' + 123)">

Remediation

To address this issue, remove the inline attributes and use unobtrusive JavaScript. Assign event listeners using addEventListener within an external script file or a dedicated <script> block.

Corrected Example:

<button id="submit-btn">Click Me</button>

JavaScript (external file):

document.addEventListener('DOMContentLoaded', () => { const btn = document.getElementById('submit-btn'); if (btn) { btn.addEventListener('click', () => { alert('Button clicked!'); }); } });

This approach allows you to implement a strict CSP (e.g., script-src 'self') which significantly hardens the application against injection.

Configuration

The detector monitors the following attributes by default but are configurable within the detector .yml:

  • onclick

  • onerror

  • onload

References

  • MDN : Inline event handlers — don’t use these

  • CWE-79 : Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')