Skip to content

Linter Rule: Disallow unsafe ERB output in JavaScript attributes ​

Rule: erb-no-unsafe-js-attribute

Description ​

ERB interpolation in JavaScript event handler attributes (onclick, onmouseover, etc.) must be wrapped in a safe helper such as .to_json, j(), or escape_javascript(). Without proper encoding, user-controlled values can break out of string literals and execute arbitrary JavaScript.

Rationale ​

HTML attributes that start with on (like onclick, onmouseover, onfocus) are evaluated as JavaScript by the browser. When ERB output is interpolated into these attributes without proper encoding, it creates a JavaScript injection vector. The .to_json method properly serializes Ruby values into safe JavaScript literals, while j() and escape_javascript() escape values for safe embedding in JavaScript string contexts.

Examples ​

✅ Good ​

erb
<a onclick="method(<%= unsafe.to_json %>)"></a>
Add an `href` attribute to `<a>` to ensure it is focusable and accessible. Links should navigate somewhere. If you need a clickable element without navigation, use a `<button>` instead. (html-anchor-require-href)
erb
<a onclick="method('<%= j(unsafe) %>')"></a>
Add an `href` attribute to `<a>` to ensure it is focusable and accessible. Links should navigate somewhere. If you need a clickable element without navigation, use a `<button>` instead. (html-anchor-require-href)
erb
<a onclick="method(<%= escape_javascript(unsafe) %>)"></a>
Add an `href` attribute to `<a>` to ensure it is focusable and accessible. Links should navigate somewhere. If you need a clickable element without navigation, use a `<button>` instead. (html-anchor-require-href)

🚫 Bad ​

erb
<a onclick="method(<%= unsafe %>)"></a>
Add an `href` attribute to `<a>` to ensure it is focusable and accessible. Links should navigate somewhere. If you need a clickable element without navigation, use a `<button>` instead. (html-anchor-require-href)
Unsafe ERB output in `onclick` attribute. Use `.to_json`, `j()`, or `escape_javascript()` to safely encode values. (erb-no-unsafe-js-attribute)
erb
<div onmouseover="highlight('<%= element_id %>')"></div>
Unsafe ERB output in `onmouseover` attribute. Use `.to_json`, `j()`, or `escape_javascript()` to safely encode values. (erb-no-unsafe-js-attribute)

References ​

Released under the MIT License.