Open Widget Based on Query Parameter

by SebastianV

HTML

<script type="module" src="https://cdn.checkout.ventrata.com/v3/production/ventrata-checkout.min.js" data-config='{"apiKey": "22ef3562-d793-456f-ba00-49e21e17c2e8"}'></script>

JavaScript

// Description
// This function checks the page URL for two query parameters:
// - openWidget – triggers the widget to open. You can assign any value to this parameter. It does not need to be strictly true or false.
// - promoCode – allows you to pass a promotional code that will be automatically applied when the widget opens.
// When called, the function returns an object containing the values of both parameters.

function openWidgetFromURL() {
    // For production use, this line must be uncommented.
    //const urlParams = new URLSearchParams(window.location.search);

    // For production use, these two lines need to be deleted.
    // It is just code used to help with testing on jsfiddle.
    const temporaryURL = new URL('https://example.com/page?openWidget=true&promoCode=QLSGZC')
    const urlParams = new URLSearchParams(temporaryURL.search)

    const openWidget = urlParams.get('openWidget')
    const promoCode = urlParams.get('promoCode');
    return {openWidget, promoCode};
}

window.addEventListener('load', function() {
    const { openWidget, promoCode } = openWidgetFromURL();

    if (openWidget) {
        if (typeof window.Ventrata === 'function') {
            // The Ventrata function takes same parameters as data-config, so you can pass in the productID 
            // and other necessary values. So, for example, if you want to apply a promo code right
            // on the first view, you just need to use this.
            window.Ventrata({"productID": "a870745f-3455-44d6-bb79-c6cf61e41e58", "promoCode": promoCode});
        } else {
            console.error('Ventrata checkout did not load.');
        }
    }
});