Share This Post

Quick Wins for BigCommerce Developers

If you spend any time on the BigCommerce support and community forums, you’ll see some recurring questions about making small theme or functional modifications.  Since so many store owners do not have a dedicated developer or agency to rely on for support, many of the answers to these questions go unanswered or are answered with “You should find a BigCommerce partner to help you with that.”  I’ll share some quick wins for BigCommerce developers and store owners looking for some guidance.  We’re going to illustrate most of these quick wins in Javascript that can be added to your store via your store admin panel.  If you find the scripts below are a bit too technical, then you may need to actually hire that BigCommerce partner or developer. :-). 

A Few Caveats

Most of the tips and code samples are based on the Cornerstone theme.  Why Cornerstone?  Well, it is the de facto starting point theme for most stores.  When we create a custom theme here at Blue Fish, we typically start with the Cornerstone theme.  It is also worth noting that Cornerstone is updated regularly to take advantage of the latest BigCommerce features, so it is a great baseline theme.  Your implementation might be slightly different, but often the biggest differences are in the selectors used to uniquely identify something on the page.

For some of the steps identified below, you will need to login to your store as the store owner.

Detect a Logged In Customer

This question comes up a lot on the support forums.  There are several ways to detect whether a shopper is logged in or not, but I’m going to illustrate the secure way to detect a logged-in user, as recommended by BigCommerce.  These are the steps we’re going to take:

  1. Create a secure client application ID for your store.
  2. Write a script to securely detect a logged in user.
  3. Install the user-detection script in your store
  4. Lastly, I’ll show you how to use your new script

1. Create Client Application ID

To create Client Application ID, you’ll need to visit the BigCommerce Developer Portal while logged in as the store owner.    From here, click the “Create an App” button and give your app a name like “Web Token POC.”  Next, click on the Technical tab and find the find the OAuth scopes section.  Here, you will want to activate the slider for the “Customer Login -> Login Token.”  Lastly, select Update & Close to save your app.  Now you can select the View Client Id icon on the page and copy the Client Id value.  Make note of the client Id to be used in the next steps.

Application Oauth Scopes

2. Create and Modify Script to Detect Logged in User

We’ll start with the simple script from BigCommerce.  Don’t forget to add your Client ID in the placeholder at the top of the script!  

				
					<script type="text/javascript">
function customerJWT() {
    var appClientId = "**BC_CLIENT_ID**"; 
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 ) {
           if (xmlhttp.status == 200) {
               console.log('Customer JWT:\n' + xmlhttp.responseText);
           }
           else if (xmlhttp.status == 404) {
              console.log('Not logged in!');
           }
           else {
               console.log('Something went wrong');
           }
        }
    };
    xmlhttp.open("GET", "/customer/current.jwt?app_client_id="+appClientId, true);
    xmlhttp.send();
}
customerJWT();
</script>
				
			

You may notice I changed lines 8, 11, and 14 above so they would log to the console.  In my case, I have a third-party module script whose execution hinges on whether the customer is logged in or not.  For that, I can create a global variable that I can check from my third-party javascript (e.g. window.logged_in). 

				
					 if (xmlhttp.status == 200) {
        window.logged_in = true;
        console.log('Customer JWT:\n' + xmlhttp.responseText);
     }
				
			

3. Install the Script in your Store

Now, we need to install this script in our store and test it!  To install it, login to your BigCommerce store and navigate to Storefront -> Script Manager.   Click on Create a Script.  Give the script a meaningful name and then select footer for location, select All pages , Essential and Script for the remaining options, then paste your new script in the contents area and save.

4. Test and Use the Customer Logged-in Script

Next open your storefront and right click on the browser to inspect and view the console.  Once you have the browser console up, refresh your page and verify that you can see the “Not logged in!” message in the log.

Lastly, log in as a customer and verify that you see the “Customer JST: ###” message in the log.  For good measure, enter “window.logged_in” in the console prompt and verify that the value true is returned. 

You’re all set.  Now you can test window.logged_in from anywhere on your site to check the logged-in status of the current customer or guest!

One final security note, as mentioned in the BigCommerce article, if you are using this token to verify a customer in a custom, server-side application, you must use the application’s secret to validate the signature on the JWT token returned in the script.  

Browser Console Log for Is logged in JWt

Change a Checkout Field

So you want to change something about the steps displayed at checkout?  This one can be a bit scary, but I’ll walk you through some best practices.  First, all of these modifications are assuming that you are using Optimized One-page Checkout (OOPC).  If you aren’t using OOPC, you should be to ensure you always have the latest security updates and features offered by BigCommerce.  Now, navigate through a sample checkout in your store and notice that each step of the checkout process dynamically loads only after you’ve have completed each of the previous, required steps.  Since the page elements load dynamically, we’ll use Mutation Observers to identify when the page element we are interested in is loaded on the the checkout page.

Below is a sample script you can use that incorporates Mutation Observers to indicate when the element we are interested in is rendered.  For each element you are observing, you can add a ready statement as illustrated on highlighted lines 54 – 62.  You can repurpose these lines to suit your needs, by replacing the console.log lines with  your changes.  Make note that line 1 includes a script to add a jQuery library to your checkout pages.  You do not need to do include this script if you are comfortable using native JavaScript DOM selectors! 

				
					<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
(function(win) {
    'use strict';
    
    var listeners = [], 
    doc = win.document, 
    MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
    observer;
    
    function ready(selector, fn) {
// Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn
        });
        if (!observer) {
// Watch for changes in the document
            observer = new MutationObserver(check);
            observer.observe(doc.documentElement, {
                childList: true,
                subtree: true
            });
        }
// Check if the element is currently in the DOM
        check();
    }
        
    function check() {
// Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
// Query for elements matching the specified selector
            elements = doc.querySelectorAll(listener.selector);
            for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                element = elements[j];
// Make sure the callback isn't invoked with the 
// same element more than once
                if (!element.ready) {
                    element.ready = true;
// Invoke the callback with the element
                    listener.fn.call(element, element);
                }
            }
        }
    }

 // Expose `ready`
  win.ready = ready;
 
            
})(this);

//Shipping form has loaded
ready('#checkoutShippingAddress', function (element) {
    console.log("Shipping form has loaded!");
});

//Mobile: Cart Summary modal is loaded
ready('.cart-modal-link', function (element) {
    console.log("Cart Summary modal is loaded!");
});

</script>
				
			

For the purposes of illustration, we’ll add a message to the customer at the top of the shipping form.  Notice, on line 7, we insert the message above the form.

				
					//Shipping form has loaded
ready('#checkoutShippingAddress', function (element) {
    console.log("Shipping form has loaded!");
     var div = document.createElement("div");
    div.innerHTML = "<span><strong>PLEASE NOTE: We cannot ship to P.O. Boxes!</strong></span>";
    div.style = "display: table-row";
    $(div).insertBefore($('.checkout-form form'));
});
				
			
Checkout Shipping Message
Modified Shipping Form

Enhance your Order Confirmation Page

The order confirmation page is another opportunity to create a lasting impression with your buyers.  I’ll show you how to create a simple script to modify your order confirmation page with a nice thank you message and a memorable image.  We already have a head-start on this one, because we are going to re-use the Mutation Observer script from above to accomplish this one, too.   This time, we just need the “Continue Shopping” button to load on the page to signal that the order confirmation page has loaded from BigCommerce.  Skip to the highlighted code below to see how we added a pretty image above the Continue Shopping button.

				
					<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
(function(win) {
    'use strict';
    
    var listeners = [], 
    doc = win.document, 
    MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
    observer;
    
    function ready(selector, fn) {
        // Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn
        });
        if (!observer) {
            // Watch for changes in the document
            observer = new MutationObserver(check);
            observer.observe(doc.documentElement, {
                childList: true,
                subtree: true
            });
        }
        // Check if the element is currently in the DOM
        check();
    }
        
    function check() {
        // Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
            // Query for elements matching the specified selector
            elements = doc.querySelectorAll(listener.selector);
            for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                element = elements[j];
                // Make sure the callback isn't invoked with the 
                // same element more than once
                if (!element.ready) {
                    element.ready = true;
                    // Invoke the callback with the element
                    listener.fn.call(element, element);
                }
            }
        }
    }

    // Expose `ready`
    win.ready = ready;
 
            
})(this);

ready('.continueButtonContainer', function(element) {
  
    var image = document.createElement("img");
     image.setAttribute("height", "768");
     image.setAttribute("width", "1024");
     image.setAttribute("alt", "Thank You for doing business with us!");
     image.src = 'https://store-hdyeju3abc.mybigcommerce.com//content/order-confirmation.jpg';
    $(image).insertBefore(this);
    
   
});   
</script>

				
			

You’ll notice on line 60 above, that the source URL for our image is the content folder of our BigCommerce sample store.   If you don’t already know how to access your store’s server space, BigCommerce has a great article to help you get connected to webDAV.

As we did earlier, to install the script, login to your BigCommerce store and navigate to Storefront -> Script Manager.   Click on Create a Script.  Give the script a meaningful name and then select footer for location, select Order confirmation , Essential and Script for the remaining options, then paste your new script in the contents area and save.

The end result is displayed on our Order Confirmation page.

Order Confirmation Image

Hide a Payment Option

Once again, we are going to use the Mutation Observer script that we used earlier.  This time, we’ll wait for the payment options to load in the DOM and hide any payment types that we don’t want the customer to see.  For our fictitious sample store, we’ll allow returning customers to use any of our payment methods, but guests will be forced to use a credit card at checkout.

				
					<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
  (function (win) {
    'use strict';

    var listeners = [],
        doc = win.document,
        MutationObserver = win.MutationObserver || win.WebKitMutationObserver,
        observer;

    function ready(selector, fn) {
        // Store the selector and callback to be monitored
        listeners.push({
            selector: selector,
            fn: fn
        });
        if (!observer) {
            // Watch for changes in the document
            observer = new MutationObserver(check);
            observer.observe(doc.documentElement, {
                childList: true,
                subtree: true
            });
        }
        // Check if the element is currently in the DOM
        check();
    }

    function check() {
        // Check the DOM for elements matching a stored selector
        for (var i = 0, len = listeners.length, listener, elements; i < len; i++) {
            listener = listeners[i];
            // Query for elements matching the specified selector
            elements = doc.querySelectorAll(listener.selector);
            for (var j = 0, jLen = elements.length, element; j < jLen; j++) {
                element = elements[j];
                // Make sure the callback isn't invoked with the
                // same element more than once
                if (!element.ready) {
                    element.ready = true;
                    // Invoke the callback with the element
                    listener.fn.call(element, element);
                }
            }
        }
    }

    function blockAlternativePayment() {
     //   console.log("--- blockAlternativePayment");
            var paymentWay = $('.optimizedCheckout-form-checklist-item [name="paymentProviderRadio"]');
            if (paymentWay && paymentWay.length) {
                $.each(paymentWay, function (index, item) {
               //     console.log(item);

                    if (item.id ===  'radio-bigpaypay' ) { //radio-cd, radio-bigpaypay, radio-paypalcommerce, radio-braintree
                        $(item).trigger('click');
                    } else {
                        $(item).parent().parent().parent().hide();
                    }

                })
            }
    }

    // Expose `ready`
    win.ready = ready;
    win.blockAlternativePayment = blockAlternativePayment;

})(this);

ready('.optimizedCheckout-form-checklist-item [name="paymentProviderRadio"]', function (element) {
   	 console.log("Payment methods loaded!");
      if (!window.logged_in) {
            console.log("Guest User: Block alternative payment options!");
            blockAlternativePayment();
        } else {
            console.log("Customer: Allow all payment options!");
        }
});


</script>





				
			

Notice we added a JavaScript method to the global scope to block certain payment methods from displaying (i.e. lines 48-63, and line 67).  Once the payment section is loaded to the page, we can check for a logged in user and determine if we want to hide any payment methods.

Again, you’ll need to login to your BigCommerce store and navigate to Storefront -> Script Manager.   Click on Create a Script.  Give the script a meaningful name and then select footer for location, select Checkout , Essential and Script for the remaining options, then paste your new script in the contents area and save.

Add 3rd party tracking scripts

You are likely already familiar with adding basic tracking for services like Google Analytics and Facebook Pixel.  BigCommerce makes configuring the most popular tracking tools very simple.  You’ll find those configurations in your store console under Advanced Settings -> Data Solutions (formerly Web Analytics) .  If you don’t see the tracking service listed here, then you may need to add your 3rd party tracking script to your theme or storefront manually. To do this, simply navigate to Storefront->Script Manager in your store console.  You can add a custom script here.  Click on the “Create a Script”.  Give the script a meaningful name and then select footer for location, select All pages , Essential and Script for the remaining options, then paste your new script in the contents area and save.

Reach Out!

Have you faced other challenges on BigCommerce that you’d like us to address? Let us know!

If you found Quick Wins for BigCommerce developers a bit too technical and need some help making these types of changes, please reach out!

Quick Wins for BigCommerce Developers

More To Explore

AI to Write Requirements

How We Use AI to Write Requirements

At ArgonDigital, we’ve been writing requirements for 22 years. I’ve watched our teams waste hours translating notes into requirements. Now, we’ve cut the nonsense with AI. Our teams can spend

ArgonDigital | Making Technology a Strategic Advantage