Change record status: 
Project: 
Introduced in branch: 
8.8.x
Introduced in version: 
8.8.0
Description: 

A new MessageCommand allows adding messages from an Ajax response. The new command will create a new Drupal.Message() object and call its addMessage() method.

To use the command simply add it to a \Drupal\Core\Ajax\AjaxResponse object like any other command that implements \Drupal\Core\Ajax\CommandInterface.

For example:

$response = new AjaxResponse();

// A status message added in the default location.
$response->addCommand(new MessageCommand('Your changes have been saved.'));

// A warning message added in the default location.
$response->addCommand(new MessageCommand('There was a problem. Please save your work and go outside.', NULL, ['type' => 'warning']));

// A status message added an alternate location.
$response->addCommand(new MessageCommand('Hey look over here!', '#alternate-message-container'));

// An error added in an alternate location.
$response->addCommand(new MessageCommand('Open the pod bay doors, HAL.',  '#alternate-message-container', ['type' => 'error']));

By default, previous messages in a location are cleared before the message is added. If you would like to leave the previous messages in a location, you may do so by setting the fourth parameter to FALSE:

$response->addCommand(new MessageCommand('Hey look over here.', NULL, ['type' => 'error'], FALSE));

Integration with Drupal.Announce() for screen readers

Developers should take care when using MessageCommand and AnnounceCommand together in the same AJAX response. Unless the "announce" option is set to an empty string (''), this command will result in the message being announced to screen readers. When combined with AnnounceCommand, this may result in unexpected behavior. Manual testing with a screen reader is strongly recommended.

If you wish to display a message without the text being announced to screen readers, add options.announce = '' (i.e. an empty string).
$response->addCommand(new MessageCommand('You made a goal! Your score is now 8675309!', '#alternate-message-container', [ 'announce' => '']));

If you wish to set the announcement priority to assertive, you can do that this way:

$response->addCommand(new MessageCommand('You added 3 cat pics.', '.js-media-library-messages', ['priority' => 'assertive']));
Impacts: 
Site builders, administrators, editors
Module developers
Site templates, recipes and distribution developers