WordPress Security in WordPress - Escaping escape data in js code


Example

esc_js() is intended to be used for inline JS, inside a tag attribute.

For data inside a <script> tag use wp_json_encode().

<input type="text" onfocus="if( this.value == '<?php echo esc_js( $fields['input_text'] ); ?>' ) { this.value = ''; }" name="name">

wp_json_encode() encodes a variable into JSON, with some sanity checks.

Note that wp_json_encode() includes the string-delimiting quotes automatically.

<?php
$book = array(
    "title" => "JavaScript: The Definitive Guide",
    "author" => "Stack Overflow",
);
?>
<script type="text/javascript">
var book = <?php echo wp_json_encode($book) ?>;
/* var book = {
    "title": "Security in WordPress",
    "author" => "Stack Overflow",
}; */
</script>

or

<script type="text/javascript">
    var title = <?php echo wp_json_encode( $title ); ?>;
    var content = <?php echo wp_json_encode( $content ); ?>;
    var comment_count = <?php echo wp_json_encode( $comment_count ); ?>;
</script>