#46131 closed defect (bug) (fixed)
Scripts: Default package inline scripts missing semi-colons
| Reported by: | aduth | Owned by: | ocean90 |
|---|---|---|---|
| Priority: | normal | Milestone: | 5.1 |
| Component: | Script Loader | Version: | |
| Severity: | normal | Keywords: | has-patch |
| Cc: | Focuses: | javascript |
Description
The inline script added by the following sample code should effectively cause nothing to happen, aside from log a message to the console.
<?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 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:
Attachments (1)
Change History (6)
#5
in reply to: ↑ 1
@
8 years ago
Replying to swissspidy:
I wonder if we can perhaps automatically detect this and add a semicolon if necessary when concatenating.
I do think this would be a wise / simple enhancement, yes.
![(please configure the [header_logo] section in trac.ini)](/chrome/site/your_project_logo.png)
I wonder if we can perhaps automatically detect this and add a semicolon if necessary when concatenating.