Make WordPress Core


Ignore:
Timestamp:
08/27/2025 10:32:57 AM (8 months ago)
Author:
jonsurrell
Message:

Scripts: Use appropriate JSON encoding flags for script tags.

wp_json_encode() with default arguments is insufficient to safely escape JSON for script tags. Use JSON_HEX_TAG | JSON_UNESCAPED_SLASHES flags.

Developed in https://github.com/WordPress/wordpress-develop/pull/9557.

Props devasheeshkaul, jonsurrell, siliconforks.
Fixes #63851.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/dependencies/wpLocalizeScript.php

    r58068 r60681  
    44 * @group scripts
    55 */
    6 class Tests_Dependencies_LocalizeScript extends WP_UnitTestCase {
     6class Tests_Dependencies_wpLocalizeScript extends WP_UnitTestCase {
    77    /**
    88     * @var WP_Scripts
     
    3939        );
    4040    }
     41
     42    /**
     43     * Verifies that wp_localize_script() outputs safe JSON whe harmful data is provided.
     44     *
     45     * @ticket 63851
     46     * @covers ::wp_localize_script
     47     */
     48    public function test_wp_localize_script_outputs_safe_json() {
     49        add_theme_support( 'html5', array( 'script' ) );
     50
     51        $path     = '/test.js';
     52        $base_url = site_url( $path );
     53
     54        wp_enqueue_script( 'test-script', $path, array(), null );
     55        wp_localize_script( 'test-script', 'testData', array( '<!--' => '<script>' ) );
     56
     57        $output = get_echo( 'wp_print_scripts' );
     58
     59        $expected  = "<script id=\"test-script-js-extra\">\nvar testData = {\"\\u003C!--\":\"\\u003Cscript\\u003E\"};\n</script>\n";
     60        $expected .= "<script src=\"{$base_url}\" id=\"test-script-js\"></script>\n";
     61
     62        $this->assertEqualHTML( $expected, $output );
     63    }
    4164}
Note: See TracChangeset for help on using the changeset viewer.