When variables are inserted directly into JavaScript blocks without escaping, attackers can inject scripts (XSS). This allows them to steal session cookies, run malicious code in the user’s browser, or change how the page works.
Escaping values in JavaScript context ensures that user-controlled data is
treated as plain text instead of executable code. Magento provides safe functions
like escapeJs() or using json_encode() to output
structured data. This prevents script injection and protects customers and admins.
# Search PHTML templates for variables inside <script> tags
grep -R "<script" app/design app/code
# Check if variables are escaped with:
$block->escapeJs($var)
json_encode($var)
<script> blocks.$block->escapeJs() for simple values like strings.json_encode() so they are valid JSON.<script>
var name = "<?= $_GET['name'] ?>";
</script>
# Unsafe, attacker can inject "alert(1)" or worse
<script>
var name = "<?= $block->escapeJs($_GET['name']) ?>";
</script>
<script>
var config = <?= json_encode($data) ?>;
</script>
# Safe, variables are escaped or JSON-encoded