Somehow subscribe/react to addMessage

I’m trying to find an event that I can subscribe to for the method addMessage.

I need to trigger some code everytime a status message is added. On reacting to this event, I need to send a variable from php to JS. I could not find an event to subscribe to so instead I used a preprocess, below.

<?php
function mymodule_preprocess_status_messages(&$variables) {
  $variables['#attached']['drupalSettings']['send_me_to_js']['_variable'] = 'Going to js...';
}

This preprocess runs everytime addMessage is used and a status message is displayed, but, the variable that i need sent to JS, is not always sent.

For example, this works for messages created from core, and I get the variable in JS. But when Drupal Commerce uses addMessage (eg. when adding a product to cart in ajax setup), the preprocess runs, the status message displays, but the variable is not available in JS.

Here’s the javascript:

(function ($, Drupal, drupalSettings) {

  Drupal.behaviors.alwave_alerts = {
    attach: function (context, settings) {
      
      $('.my-class', context).once('unique-string').each(function () { 
        
        // Run after each ajax call
        $(document).ajaxComplete(function () {
          
          // This is sometimes undefined even though the preprocess above runs
          // and there is a status message on screen
          // (eg. when  commerce creates a status message)
          console.log(settings.send_me_to_js);

        });
          
      });
  
    }
  };
  
}(jQuery, Drupal, drupalSettings));

There must be an easy way?


Go to Source of this post
Author Of this post: hga77
Title Of post: Somehow subscribe/react to addMessage
Author Link: {authorlink}