[wp-trac] [WordPress Trac] #46131: Scripts: Default package inline scripts missing semi-colons

WordPress Trac noreply at wordpress.org
Mon Jan 28 21:46:47 UTC 2019


#46131: Scripts: Default package inline scripts missing semi-colons
---------------------------+-----------------------------
 Reporter:  aduth          |      Owner:  (none)
     Type:  defect (bug)   |     Status:  new
 Priority:  normal         |  Milestone:  Awaiting Review
Component:  Script Loader  |    Version:
 Severity:  normal         |   Keywords:  has-patch
  Focuses:  javascript     |
---------------------------+-----------------------------
 The inline script added by the following sample code should effectively
 cause nothing to happen, aside from log a message to the console.

 {{{#!php
 <?php
 add_action( 'admin_enqueue_scripts', function() {
         wp_add_inline_script( 'wp-data', '( function() { console.log(
 "Run" ); } )();' );
 } );
 }}}

 However, when visiting the block editor, it can be seen in the console
 both that an error has occurred, and the "Run" message is not logged.

 >Uncaught TypeError: (intermediate value)(intermediate value)(intermediate
 value)(...) is not a function at post-new.php:207

 Due to the concatenating behavior of `wp_add_inline_script`, the issue can
 be seen by observing the page markup:

 {{{
 <script type='text/javascript'>
 ( function() {
         var userId = 1;
         var storageKey = "WP_DATA_USER_" + userId;
         wp.data
                 .use( wp.data.plugins.persistence, { storageKey:
 storageKey } )
                 .use( wp.data.plugins.controls );
 } )()
 ( function() { console.log( "Run" ); } )();
 </script>
 }}}

 Because the first [https://developer.mozilla.org/en-US/docs/Glossary/IIFE
 IIFE expression] does not terminate itself with a semi-colon, the
 subsequent IIFE is treated as calling the preceding line.

 >The source [...] is not transformed by automatic semicolon insertion,
 because the parenthesised expression that begins the second line can be
 interpreted as an argument list for a function call: [...] **In the
 circumstance that an assignment statement must begin with a left
 parenthesis, it is a good idea for the programmer to provide an explicit
 semicolon at the end of the preceding statement rather than to rely on
 automatic semicolon insertion.**

 https://www.ecma-international.org/ecma-262/5.1/#sec-7.9.2

 See also:

 - https://stackoverflow.com/questions/1873983/what-does-the-leading-
 semicolon-in-javascript-libraries-do
 - https://make.wordpress.org/core/handbook/best-practices/coding-
 standards/javascript/#semicolons

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


More information about the wp-trac mailing list