Tab refresh in background

If you have a "Cart" tab in your app, you might want to refresh it in the background when the user adds or removes a product to the cart, so the next time the user goes to that tab it will be up-to-date with the latest products.

To do this, you will need to trigger a nativeFunction when a product gets added or removed from the cart.

The nativeFunction that we will use looks like this:


// Updates all tabs in the app, except the current one
nativeFunctions.updateTabs()
  
// Updates the tab(s) in the declared position(s)
// In this example we are updating the 2nd and the 3rd tab in the bottom navigation
nativeFunctions.updateTab([2, 3])

The first step is to determine the best way to identify that action on your website.

If your website has a cart icon that displays the number of products in it, that would be a smart way to do it.

You can use Javascript code to monitor that icon and identify changes in the number of items.

Imagine that your cart icon HTML code looks like this:\

1<div class="cart-icon">
2    <span class="product-count">1</span>
3</div>
<div class="cart-icon">
    <span class="product-count">1</span>
</div>

We could use the following Javascript snippet to update the cart tab when the number of products in the cart changes:



// Check if the user agent contains 'canvas' (case insensitive)
if (navigator.userAgent.toLowerCase().indexOf('canvas') !== -1) {
    // Select the element that displays the number of products in the cart.
    var cartCountElement = document.querySelector('.product-count');

    // Define the function that triggers when there is a change in the cart.
    function handleCartChange() {
        nativeFunctions.updateTab([2]);
    }

    // Check if the cart count element exists to avoid errors
    if (cartCountElement) {
        // Create a new MutationObserver instance and provide a callback function that will be executed when mutations are observed.
        var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'childList' || mutation.type === 'characterData') {
                    handleCartChange();
                }
            });
        });

        // Start observing the target element for configured mutations. Observe for changes in children (e.g., text changes) and character data.
        observer.observe(cartCountElement, { childList: true, characterData: true, subtree: true });
    }
} 

See also
No items found.
Thank you! We'll be in touch within 48 hours :)
Oops! Something went wrong while submitting the form.