Magento – Magento 2 Add to cart frontend event listener

addtocartjavascriptknockoutjsmagento2mini-cart

I am trying to find good solution to execute custom javascript when product is successfully added to cart. Also this custom javascript need information about product that was added to cart (sku, qty, price, name, etc.)

Currently I come up with the following way to get information about products added to cart:

  1. Rewrite $.mage.catalogAddToCart.prototype.enableAddToCartButton (for products added to cart from catalog or product view page)
  2. Rewrite $.mage.dataPost.prototype.postData (for products added to cart from widgets)

To get necessary information I have to parse page (f.e. to get qty) and output additional infromation to page (f.e. to get sku having product id)

However my solution:

  • has two entry points
  • does not look nice
  • does not handle situation when validation is failed on backend
  • does not provide me all required information conveniently

Unfortunately I was not able to find any suitable extension point of checkout minicart to resolve my problem.

Any suggestions are much appreciated!

Best Answer

When something is added to the cart, the local storage information is updated and you can subscribe to a knockout observable in the cart section of the customer data to be notified when it's content changes.

Here is an example:

require(['Magento_Customer/js/customer-data'], function (customerData) {

    var cart = customerData.get('cart');
    var count = cart().summary_count;
    cart.subscribe(function () {
        if (cart().summary_count !== count) {
            count = cart().summary_count;
            // do something here
            console.log('Number of items in cart is now: ' + count);
        }
    });
});
Related Topic