Shopify Script Tag

- 1 answer

I am adding script tag in my store via api. The script tag loading fine. In script tag I added this code:

Shopify.onItemAdded = function(line_item) {
  console.log(line_item.title + ' was added to your shopping cart.');

So whenever a product is added to cart I got the callback. so I want to do some work here. But this function never called.

Can you guys tell what i might be doing wrong.



The theme your script is loaded into may not be using the ajax-cart. As far as I know there is no universal way to monitor the cart for items being added since there are several ways that can happen.

One way things get added to the cart is through a traditional POST so there won't be any event so if you are checking the cart you'd have to do so on page load. In that case you could cache the cart client side in window.sessionStorage and check it on page load for changes.

If your script is installed in a site that does use some sort of ajax add to cart or cart update then you could store the cart in sessionStorage on page load and then poll cart.js on some reasonable basis and compare it against the saved cart. This is potentially very unfriendly to mobile users but I see worse things in people's accounts.

If the ajax-cart is being used then your script will break other integrations with it. Because it isn't really an evented library what you'd have to do is something like:

    var defaultAction = Shopify.onItemAdded;
    Shopify.onItemAdded = function(line_item){
                defaultAction.apply(Shopify, arguments);
                //your override
                console.log(line_item.title + ' was added to your shopping cart.');

The other way you could handle cart updates would be a bit of effort.

Your app needs an application proxy, a websockets client, and a card update webhook. The application proxy provides a same host channel for the websocket client.

When the page loads you check for a cart. If you have a cart you open a websocket connection and register the cart token.

If the app receives a cart update that matches your token it sends the cart to your websocket listener.

This doesn't work if your cart is updated via ajax but not via the ajax-cart api so you're back to polling for that initial cart load.