How to use Javascript to display page messages

by Holly   Last Updated August 10, 2018 12:09 PM

Is it possible to use JavaScript to display a page message? I would like to display one when I receive an ajax response on a custom module I'm working on.

You can see an example of one of these messages after you save your user account info on the frontend.

enter image description here

I know I can build this markup with jQuery and add it to the page, but am wondering if Magento provides a better way of doing this.

I looked at Magento_Theme/js/view/messages and thought maybe I could include it as a dependency of my JavaScript module. Setting the message in the jQuery cookieStorage API which Magento uses to retrieve the message info in Magento_Theme/js/view/messages.

define ([
], function ($, messages) {
    'use strict';

    return function () {
        $.cookieStorage.set('mage-messages', [{type: "success", text: "custom message text"}]);

All though this approach did not work, even though I could see that the message info was retrieved in Magento_Theme/js/view/messages with

this.cookieMessages = _.unique($.cookieStorage.get('mage-messages'), 'text');

It was not displayed on the frontend.

Answers 1

You can use something like following:

], function (url, globalMessageList) {
    'use strict';
    return {
         * @param {Object} response
         * @param {Object} messageContainer
        process: function (response, messageContainer) {
            var error;

            messageContainer = messageContainer || globalMessageList;

            if (response.status == 401) { //eslint-disable-line eqeqeq
            } else {
                var message = response && response.message;

                if (message) {
                    if (message.type === 'error') {
                            message: message.text
                    } else {
                            message: message.text
Prakash Thapa
Prakash Thapa
August 10, 2018 11:33 AM

Related Questions

Close cart product “Added“ Messages - Magento 2

Updated September 11, 2017 10:09 AM

Change success message on applying coupon code

Updated May 09, 2018 08:09 AM