How to Use Geolocation with Usercentrics V2 (all web platforms)
TL;DR: the code below can be copy/pasted into the <head> of the website which will enable the geolocation feature (this code replaces the original usercentrics script that we provide by default). You can update the locations in the embed codes (towards the bottom), and you can add in your Usercentrics SettingsID into the respective area as well (bold and underlinedbelow). The rest of this article provides more extensive details: <!-- 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 --> <script id="termageddon_usercentrics_geolocation"> const termageddon_usercentrics_geolocation=(config={})=>{const tuSessionStorageName="uc_user_country",tuDebug=config.debug||!1,tuPSLHide=config.psl_hide||!0,tuToggle="div#usercentrics-root,aside#usercentrics-cmp-ui";tuDebug&&console.log("UC: Local Geolocation AJAX script initialized");const getSessionStorage=name=>{const value=sessionStorage.getItem(name);return value?JSON.parse(value):null},getQueryParams=param=>{const params=new Proxy(new URLSearchParams(window.location.search),{get:(searchParams,prop)=>searchParams.get(prop)});return params[param]},shouldShowBasedOnLocation=(countryCode,regionCode)=>{if(config.show_locations.EU){const euCountries=["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"];if(!0===config.show_locations.EU&&euCountries.includes(countryCode))return tuDebug&&console.log("UC: Showing consent widget for all EU countries",countryCode),!0;if(Array.isArray(config.show_locations.EU)&&config.show_locations.EU.includes(countryCode))return tuDebug&&console.log("UC: Showing consent widget for specific EU country",countryCode),!0}return!(!config.show_locations[countryCode]||!(!0===config.show_locations[countryCode]||Array.isArray(config.show_locations[countryCode])&&config.show_locations[countryCode].includes(regionCode)))&&(tuDebug&&console.log("UC: Showing consent widget for specific country & region",countryCode,regionCode),!0)},updateCookieConsent=hide=>{if(!hide)return tuDebug&&console.log("UC: Showing consent widget"),tuPSLHide&&jQuery("#usercentrics-psl, .usercentrics-psl").show(),jQuery(tuToggle).show(),UC_UI.isConsentRequired()?UC_UI.showFirstLayer():UC_UI.closeCMP();tuDebug&&console.log("UC: Hiding consent widget"),tuPSLHide&&jQuery("#usercentrics-psl, .usercentrics-psl").hide(),jQuery(tuToggle).hide(),UC_UI.areAllConsentsAccepted()||UC_UI.acceptAllConsents().then(()=>{tuDebug&&console.log("UC: All consents have been accepted."),UC_UI.closeCMP().then(()=>{tuDebug&&console.log("UC: CMP Widget has been closed.")})})},main=()=>{if("undefined"==typeof UC_UI)return console.error("Usercentrics not loaded");const query_hide=""===getQueryParams("enable-usercentrics"),sessionStorageData=getSessionStorage("uc_user_country");if(!sessionStorageData)return void console.warn("UC: WARNING - Session storage value for 'uc_user_country' not found. Are you using Usercentrics v2?");if(void 0===sessionStorageData.regionCode)return;const{regionCode:regionCode,countryCode:countryCode}=sessionStorageData;if(tuDebug&&console.log("UC: TERMAGEDDON USERCENTRICS (SESSION STORAGE)\nCountry Code: "+countryCode+"\nRegion Code: "+regionCode),query_hide)return tuDebug&&console.log("UC: Enabling due to query parameter override.","Showing Usercentrics"),updateCookieConsent(!1);const shouldShow=shouldShowBasedOnLocation(countryCode,regionCode);updateCookieConsent(!shouldShow)};window.addEventListener("UC_UI_INITIALIZED",main)}; </script> <script> termageddon_usercentrics_geolocation({ debug: false, show_locations: { US: ["CA", "CO", "CT", "OR", "TX", "UT", "VA"], CA: true, GB: true, EU: true, }, }); </script>
By choosing us for your privacy needs, we offer Usercentrics' consent management tool to our users. If you are using WordPress, we have a WordPress Plugin that includes a popular geolocation feature. This feature hides the consent widget if the user is in an area that does not require the consent popover to be visible. While this is great for WordPress users, we also want to provide this system to other users. Therefore, we have developed a JavaScript script that works automatically with minimal configuration alongside the Usercentrics v2 consent widget script. With this script, you can control where your cookie consent banner appears based on your visitors' location—even if you're not using WordPress. This guide will walk you through how to implement and test the geolocation script on your website.
Note: This method is only compatible with the default implementation of Usercentrics V2. If you're using Usercentrics V3, this script will not work.
What Does the Geolocation Script Do?
The script allows you to:
Show or hide the Usercentrics consent widget based on the visitor's country or region.
Target specific US states, Canadian provinces, UK regions, or EU countries, guided by the Termageddon consent questionnaire.
Optionally hide the privacy settings link when the consent widget is hidden.
How to Implement the Geolocation Script
Add the Usercentrics V2 Embed Code to Your Site
Make sure you have the standard Usercentrics V2 embed code in your site's <head>. It should look like this:
<script
id="usercentrics-cmp"
src="https://app.usercentrics.eu/browser-ui/latest/loader.js"
data-settings-id="XXXXXXXXX"
async
></script>
Please include the entire embed code, following the guide for your web platform here: Cookie Consent Installation Guides.
Check Compatibility with Your Current Site
This method only works for Usercentrics v2. Usercentrics stores the visitor's country and region in the browser's session storage under the key uc_user_country. Let's check for that in one of two ways:
Option 1: Using the Browser Console
Open your browser's DevTools (usually F12 or right-click → Inspect), go to the Console tab, and run:
JSON.parse(sessionStorage.getItem("uc_user_country"));
This should return an object with your current location, such as:
{
"countryCode": "US",
"countryName": "US",
"regionCode": "CA"
}
Note: If it returns null, please ensure you are using Usercentrics v2 and not v3.
Option 2: Using the Application Tab
Open DevTools.
Go to the Application tab.
Under Session Storage, select your site.
Look for the key uc_user_country containing the JSON above.
Note: After installing, you can also check the console for an error to see if the session storage uc_user_country is present. If it is not, please ensure that you are using Usercentrics v2 or contact support.
Add the Script to Your Site
Upload the geolocation script (or minified version) to your local site, and/or copy its contents to a new inline script. Place it after the Usercentrics embed code, ideally just before the closing </body> tag or in your site's JS bundle.
<script src="path/to/termageddon-usercentrics-geolocation.min.js"></script>
OR
<script>
const termageddon_usercentrics_geolocation = (config = {}) => {
...
</script>
Next, we will initialize the script and configure it for your users' needs.
Initialize the Script
In a separate inline <script> tag after both scripts and before the </head> tag, configure the script.
You can customize which countries or regions should see the consent banner. Here's an example configuration, with more information on how to configure the script below.
termageddon_usercentrics_geolocation({
debug: true,
show_locations: {
US: ["CA", "CO", "CT", "OR", "TX", "UT", "VA"], // Only these US states
CA: true, // All of Canada
GB: true, // All of the UK
EU: true, // All EU countries
},
});
Configuration
There are two attributes you can configure: debug and show_locations.
debug (boolean): true or false
When enabled (true), the current user's location will display in the console to validate that it's working. You can learn more about troubleshooting below.
show_locations (string: (string[] | boolean))
For a list of valid country and region codes, refer to this free CSV download of this ISO 3166-2 list. The first column corresponds to the country code, and the third column contains the region code inside a given country.
The value of each key-value pair must either be a boolean or a string array.
BOOLEAN: true to show the consent in this location; false to hide the consent in this location
STRING[]: An array containing a list of region codes (found in the above CSV document). If in the array, the consent will be shown at that location. All locations not in the list will have the consent tool hidden.
How to Test If Geolocation Is Working
Validate the Script Installation
To confirm the geolocation script is running and controlling the consent banner:
Check the Installation of the Script
When enabled, a new function is available in the global context of the website. To validate if it worked, type termageddon_usercentrics_geolocation in the browser console.
Success:
Error:
If the output is "Uncaught ReferenceError: termageddon_usercentrics_geolocation is not defined", ensure the script is being loaded as described in step 3 above.
Check for Usercentrics v2 (Incompatible with v3)
To validate if you are using v2 of Usercentrics, look for this warning in the browser’s console. If no warning is present, it is working as expected.
Check for Debug Messages
If you enabled debug: true in your config, you'll see messages in the Console prefixed with UC:.
For example:
UC: Local Geolocation AJAX script initialized
UC: TERMAGEDDON USERCENTRICS (SESSION STORAGE)
Country Code: US
Region Code: CA
Force the Consent Banner to Show/Hide
The best route to test is to use a VPN to change your location. Alternatively, you can simulate different locations by manually setting the session storage value in the Console:
sessionStorage.setItem(
"uc_user_country",
JSON.stringify({ countryCode: "US", regionCode: "CA" })
);
window.dispatchEvent(new Event("UC_UI_INITIALIZED"));
Then refresh the page or trigger the event as above. The consent banner should appear or disappear based on your configuration.
Note: You may need to close your browser or use an incognito window to clear the session storage cache.
Check Consent Widget Visibility
In the browser console, run:
document.querySelector("div#usercentrics-root,aside#usercentrics-cmp-ui")
.style.display;
If the value is none, the widget is hidden.
If the value is block or empty, the widget is visible.
Troubleshooting
If you don't see the expected behavior, make sure:
The Usercentrics V2 script is loaded before the geolocation script.
Your configuration matches the country/region you're testing.
There are no JavaScript errors in the Console.
Caching Note: Changes to the script or configuration may require a hard refresh (Ctrl+Shift+R or Cmd+Shift+R) or testing in an incognito window.
Example: Full Implementation (Inline)
The following script will set up the consent to only display to visitors in California, Canada, EU and UK.
<!-- 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 -->
<script id="termageddon_usercentrics_geolocation">
const termageddon_usercentrics_geolocation=(config={})=>{const tuSessionStorageName="uc_user_country",tuDebug=config.debug||!1,tuPSLHide=config.psl_hide||!0,tuToggle="div#usercentrics-root,aside#usercentrics-cmp-ui";tuDebug&&console.log("UC: Local Geolocation AJAX script initialized");const getSessionStorage=name=>{const value=sessionStorage.getItem(name);return value?JSON.parse(value):null},getQueryParams=param=>{const params=new Proxy(new URLSearchParams(window.location.search),{get:(searchParams,prop)=>searchParams.get(prop)});return params[param]},shouldShowBasedOnLocation=(countryCode,regionCode)=>{if(config.show_locations.EU){const euCountries=["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"];if(!0===config.show_locations.EU&&euCountries.includes(countryCode))return tuDebug&&console.log("UC: Showing consent widget for all EU countries",countryCode),!0;if(Array.isArray(config.show_locations.EU)&&config.show_locations.EU.includes(countryCode))return tuDebug&&console.log("UC: Showing consent widget for specific EU country",countryCode),!0}return!(!config.show_locations[countryCode]||!(!0===config.show_locations[countryCode]||Array.isArray(config.show_locations[countryCode])&&config.show_locations[countryCode].includes(regionCode)))&&(tuDebug&&console.log("UC: Showing consent widget for specific country & region",countryCode,regionCode),!0)},updateCookieConsent=hide=>{if(!hide)return tuDebug&&console.log("UC: Showing consent widget"),tuPSLHide&&jQuery("#usercentrics-psl, .usercentrics-psl").show(),jQuery(tuToggle).show(),UC_UI.isConsentRequired()?UC_UI.showFirstLayer():UC_UI.closeCMP();tuDebug&&console.log("UC: Hiding consent widget"),tuPSLHide&&jQuery("#usercentrics-psl, .usercentrics-psl").hide(),jQuery(tuToggle).hide(),UC_UI.areAllConsentsAccepted()||UC_UI.acceptAllConsents().then(()=>{tuDebug&&console.log("UC: All consents have been accepted."),UC_UI.closeCMP().then(()=>{tuDebug&&console.log("UC: CMP Widget has been closed.")})})},main=()=>{if("undefined"==typeof UC_UI)return console.error("Usercentrics not loaded");const query_hide=""===getQueryParams("enable-usercentrics"),sessionStorageData=getSessionStorage("uc_user_country");if(!sessionStorageData)return void console.warn("UC: WARNING - Session storage value for 'uc_user_country' not found. Are you using Usercentrics v2?");if(void 0===sessionStorageData.regionCode)return;const{regionCode:regionCode,countryCode:countryCode}=sessionStorageData;if(tuDebug&&console.log("UC: TERMAGEDDON USERCENTRICS (SESSION STORAGE)\nCountry Code: "+countryCode+"\nRegion Code: "+regionCode),query_hide)return tuDebug&&console.log("UC: Enabling due to query parameter override.","Showing Usercentrics"),updateCookieConsent(!1);const shouldShow=shouldShowBasedOnLocation(countryCode,regionCode);updateCookieConsent(!shouldShow)};window.addEventListener("UC_UI_INITIALIZED",main)};
</script>
<script>
termageddon_usercentrics_geolocation({
debug: false,
show_locations: {
US: ["CA", "CO", "CT", "OR", "TX", "UT", "VA"],
CA: true,
GB: true,
EU: true,
},
});
</script>
Example: Full Implementation (Self-Hosted)
For cleaner output, you can self-host the termageddon_usercentrics_geolocation.min.js file.
<!-- 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 -->
<script id="termageddon_usercentrics_geolocation" src="/path/to/termageddon_usercentrics_geolocation.min.js">
</script>
<script>
termageddon_usercentrics_geolocation({
debug: false,
show_locations: {
US: ["CA"],
CA: true,
GB: true,
EU: true,
},
});
</script>
We do recommend keeping debug set to false (or omitting debug entirely) in production environments.
Additional Resources
If you have questions or need help, contact Termageddon support.