WordPress.org

Make WordPress Core

Opened 19 months ago

Closed 19 months ago

Last modified 19 months ago

#46131 closed defect (bug) (fixed)

Scripts: Default package inline scripts missing semi-colons

Reported by: aduth Owned by: ocean90
Milestone: 5.1 Priority: normal
Severity: normal Version:
Component: Script Loader Keywords: has-patch
Focuses: javascript Cc:

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)

46131-semicolon.diff (450 bytes) - added by aduth 19 months ago.

Download all attachments as: .zip

Change History (6)

#1 follow-up: @swissspidy
19 months ago

I wonder if we can perhaps automatically detect this and add a semicolon if necessary when concatenating.

#2 follow-up: @ocean90
19 months ago

  • Owner set to ocean90
  • Resolution set to fixed
  • Status changed from new to closed

In 44709:

Script Loader: Add missing semicolon.

Fixes #46131.

#3 @ocean90
19 months ago

  • Milestone changed from Awaiting Review to 5.1

#4 in reply to: ↑ 2 @ocean90
19 months ago

Replying to ocean90:

In 44709:

Script Loader: Add missing semicolon.

Fixes #46131.

Props aduth!

#5 in reply to: ↑ 1 @aduth
19 months 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.

Note: See TracTickets for help on using tickets.