[wp-trac] [WordPress Trac] #60320: JSON is corrupted when output via wp_get_inline_script_tag() and HTML5 theme support absent

WordPress Trac noreply at wordpress.org
Mon Jan 22 18:54:13 UTC 2024


#60320: JSON is corrupted when output via wp_get_inline_script_tag() and HTML5
theme support absent
---------------------------+-------------------------
 Reporter:  westonruter    |      Owner:  westonruter
     Type:  defect (bug)   |     Status:  assigned
 Priority:  normal         |  Milestone:  6.5
Component:  Script Loader  |    Version:  6.4
 Severity:  normal         |   Keywords:  needs-patch
  Focuses:  javascript     |
---------------------------+-------------------------
 The [https://github.com/WordPress/performance/issues/908 Speculation
 Rules] plugin as part of Performance Lab outputs JSON in a `script` tag
 via:

 {{{#!php
 <?php
 wp_print_inline_script_tag(
         wp_json_encode( $rules ),
         array( 'type' => 'speculationrules' )
 );
 }}}

 We found that when `html5` theme support is absent (specifically
 `scripts`), this results in the following being printed:

 {{{
 <script type="speculationrules">
 /* <![CDATA[ */
 []
 /* ]]> */
 </script>
 }}}

 Note the CDATA wrappers which are added for XML/XHTML compatibility. These
 break the JSON parsing. (Note in #59883 that these CDATA comments are also
 proposed to be eliminated entirely with the removal of legacy XHTML
 compat.) Ironically,
 `wp_get_inline_script_tag()`/`wp_print_inline_script_tag()` didn't
 actually used to print the CDATA wrapper comments. They were missing until
 6.4 in which they were "fixed" (ahem, by me) in [56687] as part of #58664.

 This will also be an issue for the new script modules in 6.4 (#56313).
 When HTML5 theme support is absent, an import map script is currently
 printed as:

 {{{
 <script type="importmap" id="wp-importmap">
 /* <![CDATA[ */
 {"imports":{"bar":"http:\/\/localhost:10023\/bar.js?ver=6.5-alpha-57321"}}
 /* ]]> */
 </script>
 }}}

 Example plugin code to reproduce:

 {{{#!php
 <?php
 add_action(
         'after_setup_theme',
         static function () {
                 remove_theme_support( 'html5' );
         },
         PHP_INT_MAX
 );

 add_action(
         'wp_enqueue_scripts',
         static function () {
                 wp_register_module( 'bar', home_url( '/bar.js' ) );
                 wp_enqueue_module( 'foo', home_url( '/foo.js' ), array(
 'bar' ) );
         }
 );
 }}}


 In short, the CDATA wrapper comments need to only ever be printed when the
 type of the `script` will be JavaScript. They should be omitted for every
 other type (e.g. `importmap`, `speculationrules`, `application/json`).

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/60320>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list