I have redirected customer to cart from checkout in a specific scenario using observer with a custom error message. Here is the observer code.

namespace Vendor\Module\Observer;
use Magento\Framework\Event\ObserverInterface;

   public function __construct(
        \Magento\Framework\Url $url,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\Response\Http $http,
        // other dependencies
        $this->url = $url;
        $this->messageManager = $messageManager;
        $this->http = $http;
    public function execute(\Magento\Framework\Event\Observer $observer)

                $cartUrl = $this->url->getUrl('checkout/cart');
                $mySpecificCondition = true;
                if ($mySpecificCondition) {
                    $this->messageManager->addErrorMessage('Custom error message here.');

This error message is shown forever if I do not refresh this page. How I can program it so that this custom error message is hidden after 5 seconds?

  • You can try to use javascript or jquery to hide the error after a certain time in your custom module
    – Korbin
    Commented Sep 26, 2018 at 6:42
  • 1
    I can use jQuery('.messages').delay(5000).fadeOut('slow'); in cart page, but is there a better approach available?
    – amitshree
    Commented Sep 26, 2018 at 7:13
  • I get your point, but I am not sure if there is an easier/better approach. On the other hand you should inject that js file using requirejs-config file. I guess that is the way magento wants
    – Korbin
    Commented Sep 26, 2018 at 7:17

1 Answer 1


Eu resolvi dessa maneira

criar um arquivo requires js dentro de frontend


var config = {
    config: {
        mixins: {
            'Magento_Theme/js/view/messages': {
                '{Vendor_Module}/js/view/messages-mixin': true

Agora criando o Mixin js para adicinar as funções e tempo


], function (customerData) {
    'use strict';

    return function (target) {
        return target.extend({
             * Extends Component object by storage observable messages.
            initialize: function () {

                function hideMessage(){
                    require(['jquery', 'jquery/jquery-storageapi'], function($) {
                        $.cookieStorage.set('mage-messages', '');


Isso vai remover as mensagens apos 5 segundos.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.