How to Use Geolocation with Usercentrics V2 (all web platforms)


If you are using WordPress, you can utilize the Termageddon plugin's geolocation feature to show/hide the consent tool based on location. This is within the "Geolocation" tab of the plugin. 


If you have a non-WordPress site, we offer the ability to utilize geolocation via an enhanced script, which you will find below. 


STEPS:
1. Copy the code below
2. You must change the 'data-settings-id' to your license's specific SettingsID. This can be found on the 'embed codes' page of your Termageddon license.  Replace "XXXXXXXXXX" with your SettingsID.

3. Towards the bottom of the script, we provide the areas to display the consent tool to. The consent tool will only be displayed to the areas listed (all other areas will hide the consent tool).  By default, this consent tool is set to only display to visitors in California, Canada, EU and UK (by far the most popular option for most small business owners).  If you would like to add an additional state to this list, you can do so by adding the different states (following the format of ["CA", "IL", "AR"] for example).

4. Paste this code at the top of the <head> of your website (remove any previously pasted consent code).

5. Save and test in a fresh incognito window.


If you are testing in an area that is set to *hide* the consent tool, and you would like to see the consent display for testing purposes, you can add in your state/country (see item #3 above for steps) and then visit your website in a fresh incognito window to confirm teh consetn . 



<!-- Usercentrics V2 Embed -->
<script id="usercentrics-cmp" src="https://app.usercentrics.eu/browser-ui/latest/loader.js"
    data-settings-id="XXXXXXXXXX" async></script>

<!-- Termageddon Geolocation Script - Optimized Version -->
<script id="termageddon_usercentrics_geolocation">
    const termageddon_usercentrics_geolocation = (config = {}) => {
        const {
            debug = false,
            psl_hide = true,
            show_locations = {}
        } = config;

        const EU_COUNTRIES = ["AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", "NO", "IS", "LI"];
        const WIDGET_SELECTORS = "div#usercentrics-root, aside#usercentrics-cmp-ui";
        const PSL_SELECTORS = "#usercentrics-psl, .usercentrics-psl";

        // Utility functions
        const getSessionStorage = (key) => {
            try {
                const value = sessionStorage.getItem(key);
                return value ? JSON.parse(value) : null;
            } catch (error) {
                console.warn("Failed to parse session storage:", error);
                return null;
            }
        };

        const getQueryParam = (param) => {
            try {
                return new URLSearchParams(window.location.search).get(param);
            } catch (error) {
                return null;
            }
        };

        const shouldShowBasedOnLocation = (countryCode, regionCode) => {
            // Handle EU countries
            if (show_locations.EU) {
                if (show_locations.EU === true && EU_COUNTRIES.includes(countryCode)) {
                    return true;
                }
                if (Array.isArray(show_locations.EU) && show_locations.EU.includes(countryCode)) {
                    return true;
                }
            }

            // Check specific country configuration
            const countryConfig = show_locations[countryCode];
            if (!countryConfig) return false;
            if (countryConfig === true) return true;
            if (Array.isArray(countryConfig)) return countryConfig.includes(regionCode);
            
            return false;
        };

        const setElementStyles = (elements, styles) => {
            elements.forEach(element => {
                Object.entries(styles).forEach(([property, value]) => {
                    if (value === null) {
                        element.style.removeProperty(property);
                    } else {
                        element.style.setProperty(property, value, 'important');
                    }
                });
            });
        };

        const showConsentWidget = () => {
            // Show privacy settings links
            if (psl_hide) {
                document.querySelectorAll(PSL_SELECTORS).forEach(el => {
                    el.style.display = '';
                });
            }

            // Remove forced hiding styles
            const widgets = document.querySelectorAll(WIDGET_SELECTORS);
            setElementStyles(widgets, {
                'display': null,
                'visibility': null,
                'opacity': null,
                'pointer-events': null
            });

            // Let Usercentrics show the widget
            if (window.UC_UI?.showFirstLayer) {
                try {
                    UC_UI.showFirstLayer();
                } catch (error) {
                    // Fallback: ensure widgets are visible
                    widgets.forEach(el => el.style.display = '');
                }
            }
        };

        const hideConsentWidget = () => {
            // Hide privacy settings links
            if (psl_hide) {
                document.querySelectorAll(PSL_SELECTORS).forEach(el => {
                    el.style.display = 'none';
                });
            }

            // Forcefully hide consent widgets
            const widgets = document.querySelectorAll(WIDGET_SELECTORS);
            setElementStyles(widgets, {
                'display': 'none',
                'visibility': 'hidden',
                'opacity': '0',
                'pointer-events': 'none'
            });

            // Auto-accept consents if not already accepted
            if (window.UC_UI?.areAllConsentsAccepted && window.UC_UI?.acceptAllConsents) {
                try {
                    if (!UC_UI.areAllConsentsAccepted()) {
                        UC_UI.acceptAllConsents().then(() => {
                            UC_UI.closeCMP?.();
                        }).catch(() => {
                            // Silent fail - consent management will handle this
                        });
                    }
                } catch (error) {
                    // Silent fail - consent management will handle this
                }
            }
        };

        const processGeolocation = () => {
            // Verify Usercentrics is loaded
            if (!window.UC_UI) {
                console.error("Usercentrics not loaded");
                return;
            }

            // Check for query parameter override
            if (getQueryParam("enable-usercentrics") === "") {
                showConsentWidget();
                return;
            }

            // Get location data from session storage
            const locationData = getSessionStorage("uc_user_country");
            if (!locationData?.regionCode || !locationData?.countryCode) {
                console.warn("UC: No valid location data found. Ensure Usercentrics v2 is being used.");
                return;
            }

            const { countryCode, regionCode } = locationData;
            const shouldShow = shouldShowBasedOnLocation(countryCode, regionCode);

            // Apply geolocation logic with small delay for initialization
            setTimeout(() => {
                if (shouldShow) {
                    showConsentWidget();
                } else {
                    hideConsentWidget();
                }
            }, 50);
        };

        // Initialize when Usercentrics is ready
        if (window.UC_UI) {
            processGeolocation();
        } else {
            window.addEventListener("UC_UI_INITIALIZED", processGeolocation);
        }
    };
</script>

<script>
    // Initialize geolocation - only show for California
    termageddon_usercentrics_geolocation({
        debug: false,
        psl_hide: true,
        show_locations: {
            US: ["CA"], // Only California for US states - add comma separated abbreviations to add more states
            CA: true,   // All of Canada
            GB: true,   // All of Great Britain
            EU: true,   // All EU countries
        },
    });
</script>





If you have questions or need help, contact Termageddon support.