How It Works

Find out how our solution helps you turn browsers into buyers.

Integrations

From Shopify to Klaviyo, explore over 80 integrations.

Support

Access guides, troubleshooting, and expert assistance.

About Us

Hear our origin story and meet our team.

Partnership

Become an official Retention.com Partner.

Affiliate Program

Learn more about our Affiliate Program.

Careers

Explore career opportunities with Retention.com.

Events

See upcoming events we’re hosting or attending.

Referrals

Got a referral? Let us know here.

Product Support

privacy-red-circle
Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
product-support

Set up Add to Cart and Viewed Product for Reclaim in BigCommerce

This feature can identify viewed products and add to cart events for both unknown, non-logged in users (Grow contacts) and known, non-logged in customers (emails in your Grow suppression list). 

To use this feature, you must have the most recent version of our script on your website. You can find your script in your account under Code Script > View Script.
Click here for a link to the tutorial on how to add the script to your site, in case you need a refresher.

What you'll need

Copy the code block below. This code will be added into your BigCommerce theme and captures key product details and creates a payload for Retention Reclaim events. 

How does it work?

The code injects key product details into the template through the use of BigCommerce handlebars. The subsequent JavaScript script parses the BigCommerce object and generates a payload for the viewed product and add to cart events.

Upon the DOM being fully loaded, the script initiates the 'Viewed Product Reclaim' event. If an 'Add to Cart' button is present, an event listener is set up to capture the 'addToCart' event when clicked.


{{inject 'productInfo' product}}

<script defer type="text/javascript">
// grab BigCommerce Data
var jsContext = JSON.parse({{jsContext}});
    
// create Retention payload object
var vpitem = {
    Name: jsContext.productInfo.title,
    Price: jsContext.productInfo.price.without_tax.formatted,
    ProductID: jsContext.productInfo.id,
    Categories: jsContext.productInfo.category[0],
    ImageURL: jsContext.productInfo.main_image.data.replace("{:size}", jsContext.productSize),
    URL: window.location.href,
    Brand: jsContext.productInfo.brand ? (jsContext.productInfo.brand.name ? jsContext.productInfo.brand.name : '') : ''     
};

// Output to console in Retention debugger mode only
if (window.location.href.includes('vge=true')) {
    console.log("BigCommerce Data", jsContext);
    console.log("Payload for Reclaim events", vpitem);
}

// Call Retention Reclaim events once DOM is loaded 
document.addEventListener('DOMContentLoaded', function () {
    // Call Product Viewed Reclaim event
    geq.event('Viewed Product Reclaim', vpitem);

    // *NOTE* ---- please use the appropriate selector for the Add to Cart button 
    // var addToCartButton = document.getElementsByClassName("form-action-addToCart");
    var addToCartButton = document.getElementById("form-action-addToCart");
    if (addToCartButton) {
        addToCartButton.addEventListener('click', function () {
            // Output to console in Retention debugger mode only
            if (window.location.href.includes('vge=true')) {
                console.log("add to cart clicked;");
            }
            // Call addToCart Reclaim event
            geq.addToCart(vpitem);
        });
    }
});
</script>

This section pertains specifically to scenarios in which users have the option to add other items to their shopping cart directly from a product page.

How does it work?

When a user adds another product to their cart directly from a product page, we have two solutions that allow us to capture the Reclaim add to cart event. For the first solution, we implement an event listener to capture this action and subsequently create a temporary cookie in the browser. Upon redirection to the cart, we perform a check to verify the presence of the cookie. If it exists, we utilize the information of the latest item added to the cart to trigger the Reclaim addToCart event. For the second solution, we create a listener for the Big Commerce "cart/add" endpoint and create a payload from that response for the event. 

Code Snippet 1: Use this if the page redirects after add to cart event
{{inject 'productInfo' product}}

<script defer type="text/javascript">
// grab BigCommerce Data
var jsContext = JSON.parse({{jsContext}});
    
// create Retention payload object
var vpitem = {
    Name: jsContext.productInfo.title,
    Price: jsContext.productInfo.price.without_tax.formatted,
    ProductID: jsContext.productInfo.id,
    Categories: jsContext.productInfo.category[0],
    ImageURL: jsContext.productInfo.main_image.data.replace("{:size}", jsContext.productSize),
    URL: window.location.href,
    Brand: jsContext.productInfo.brand ? (jsContext.productInfo.brand.name ? jsContext.productInfo.brand.name : '') : ''     
};

// Output to console in Retention debugger mode only
if (window.location.href.includes('vge=true')) {
    console.log("BigCommerce Data", jsContext);
    console.log("Payload for Reclaim events", vpitem);
}

// Call Retention Reclaim events once DOM is loaded 
document.addEventListener('DOMContentLoaded', function () {
    // Call Product Viewed Reclaim event
    geq.event('Viewed Product Reclaim', vpitem);

    // *NOTE* ---- please use the appropriate selector for the Add to Cart button 
    // var addToCartButton = document.getElementsByClassName("form-action-addToCart");
    var addToCartButton = document.getElementById("form-action-addToCart");
    if (addToCartButton) {
        addToCartButton.addEventListener('click', function () {
            // Output to console in Retention debugger mode only
            if (window.location.href.includes('vge=true')) {
                console.log("add to cart clicked;");
            }
            // Call addToCart Reclaim event
            geq.addToCart(vpitem);
        });
    }
    
    // This code is for instances where supplementary items are added to the shopping cart directly from a product page.
        
    // *NOTE* --- please use the appropriate selector for the Add to Cart button 
    var otherProducts = document.getElementsByClassName("button--small card-figcaption-button");
    // Convert the HTMLCollection to an array
    var otherProductsArray = Array.from(otherProducts);
        
    // Add an click event listener to each product
    otherProductsArray.forEach(function (product) {
      product.addEventListener('click', function (event) {
        // Set a cookie named _geapc that expires in 1 minute
        const expirationDate = new Date();
        expirationDate.setTime(expirationDate.getTime() + 60 * 1000); // 1 minute
        document.cookie = "_geapc=true; expires=" + expirationDate.toUTCString() + "; path=/";
      }); // end of click event listener for other products
    }); // end of otherProducts check
});
</script>

<script defer type="text/javascript">
// Check if the "_geapc" cookie exists
if (document.cookie.includes('_geapc=true')) {   
    // Grab BigCommerce Data
    var jsContext = JSON.parse({{jsContext}});
    
    const options = { method: 'GET', headers: { 'Content-Type': 'application/json' } };
    fetch(jsContext.secureBaseUrl + '/api/storefront/carts', options)
        .then(response => {
            if (!response.ok) {
                throw new Error("Call to cart failed");
            }
            return response.json();
        })
        .then(data => {
            if (data.length > 0) {
                // Get the last item added to the cart
                var lastAdded = data[0].lineItems.physicalItems[data[0].lineItems.physicalItems.length - 1];
    
                // Create new payload for reclaim ATC 
                var lastItem = {
                    Name: lastAdded.name,
                    Price: lastAdded.listPrice,
                    ProductID: lastAdded.id,
                    Categories: '',
                    ImageURL: lastAdded.imageUrl,
                    URL: lastAdded.url,
                    Brand: lastAdded.brand ? (lastAdded.brand ? lastAdded.brand : '') : ''
                };
                console.log(lastItem);
                
                setTimeout(() => {
                    // Call Reclaim ATC function
                    geq.addToCart(lastItem);
                }, 2000); // 2 second delay before calling the Reclaim ATC function
            }
        })
        .catch(err => console.error(err));
} else {
    console.log("Cookie _geapc not found. API call not made.");
}
</script>
Code Snippet 2: Use this if the page doesn't redirect to the cart
{{inject 'productInfo' product}}

<script defer type="text/javascript">
// grab BigCommerce Data
var jsContext = JSON.parse({{jsContext}});
    
// create Retention payload object
var vpitem = {
    Name: jsContext.productInfo.title,
    Price: jsContext.productInfo.price.without_tax.formatted,
    ProductID: jsContext.productInfo.id,
    Categories: jsContext.productInfo.category[0],
    ImageURL: jsContext.productInfo.main_image.data.replace("{:size}", jsContext.productSize),
    URL: window.location.href,
    Brand: jsContext.productInfo.brand ? (jsContext.productInfo.brand.name ? jsContext.productInfo.brand.name : '') : ''     
};

// Output to console in Retention debugger mode only
if (window.location.href.includes('vge=true')) {
    console.log("BigCommerce Data", jsContext);
    console.log("Payload for Reclaim events", vpitem);
}

// Call Retention Reclaim events once DOM is loaded 
document.addEventListener('DOMContentLoaded', function () {
    // Call Product Viewed Reclaim event
    geq.event('Viewed Product Reclaim', vpitem);

    // The following code works for ATC when the page is not redirected
    (function() {
  var originalXHROpen = window.XMLHttpRequest.prototype.open;
  window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
    originalXHROpen.apply(this, arguments);
    if (url.includes('/cart/add')) {
      this.addEventListener('load', function() {
        if (this.readyState === 4 && this.status === 200) {
          try {
            var item_info = JSON.parse(this.response);
            if (item_info && item_info.data && item_info.data.line_items && item_info.data.line_items.length > 0) {
              var line_item = item_info.data.line_items[0];
              var itemAdded = {
                Name: line_item.product_name,
                Price: item_info.data.product_value,
                ProductID: line_item.product_id,
                Categories: line_item.category_names && line_item.category_names.length > 0 ? line_item.category_names[line_item.category_names.length - 1] : '',
                ImageURL: item_info.data.cart_item.thumbnail,
                URL: item_info.data.cart_item.url,
                Brand: line_item.brand_name || ''
              };
              console.log(itemAdded);
              if (typeof geq !== 'undefined' && geq.addToCart) {
                geq.addToCart(itemAdded);
              }
            }
          } catch (error) {
           if (window.location.search.includes('vge=true')) {
              console.error('Error processing XMLHttpRequest response:', error);
            }
          }
        }
      });
    }
  };
})();
    
});
</script>
Where to add the code?

Code Snippet 1: Insert the initial code block into the product-view.html file, following steps 1 to 3 outlined below. Subsequently, place the second code block within Templates -> Pages -> Cart.html.

Code Snippet 2: Insert the code block into the product-view.html file, following steps 1 to 3 outlined below.


Adding script to BigCommerce

1. In your BigCommerce storefront, go to Themes > Click the "Advanced" dropdown on the current theme > Click "Edit Theme Files"

2. Once you have access to your theme files, proceed to Templates > Components > Products

3. In the "products" folder, locate and open the "product-view.html" file. Copy the provided code block from above and paste it into the editor. Save the changes by clicking the button positioned at the bottom right corner of the screen.

4. Verify the functionality of the code by navigating to a product page and activating the Retention debugger. Confirm that the "Viewed Product Reclaim" event is detected and triggered. Additionally, ensure that the "Add to Cart" event is identified, and it should be activated upon adding the product to your cart.

Disclaimer

General:

These scripts attempt to utilize the capabilities offered by BigCommerce and are intended to be lightweight and perform well in the majority of scenarios. We understand that every website is unique and as such, variations may be required by your team.

chevron-down