Geolocation feature of Consent Solution

Modified on Thu, 30 Jul at 9:03 AM

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="XXXXXXXXX" async></script>

<!-- Termageddon Geolocation Script - Optimized Version (with consent-persistence fix) -->
<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
            });

            // Only force the first layer open if consent is actually still
            // required (visitor hasn't responded yet, or Usercentrics has
            // flagged a resurface as due). isConsentRequired() covers BOTH
            // "accept" and "deny" outcomes.
            if (window.UC_UI?.showFirstLayer && window.UC_UI?.isConsentRequired?.()) {
                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;
            }

            // On a first-ever (cold) page load, Usercentrics' IP-based
            // geolocation lookup can still be in flight when UC_UI_INITIALIZED
            // fires, so "uc_user_country" may not be in session storage yet.
            // Poll briefly instead of checking once and giving up - this is
            // why the banner previously worked only after a refresh (by then
            // the lookup from the first load had already completed and cached).
            const maxAttempts = 20;      // 20 x 150ms = up to 3 seconds
            const intervalMs = 150;
            let attempts = 0;

            const tryGetLocation = () => {
                const locationData = getSessionStorage("uc_user_country");

                if (locationData?.regionCode && locationData?.countryCode) {
                    const { countryCode, regionCode } = locationData;
                    const shouldShow = shouldShowBasedOnLocation(countryCode, regionCode);

                    if (shouldShow) {
                        showConsentWidget();
                    } else {
                        hideConsentWidget();
                    }
                    return;
                }

                attempts++;
                if (attempts < maxAttempts) {
                    setTimeout(tryGetLocation, intervalMs);
                } else {
                    console.warn("UC: No valid location data found after waiting. Ensure Usercentrics v2 is being used.");
                }
            };

            // Small initial delay for initialization, then start polling
            setTimeout(tryGetLocation, 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.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article