How to rewrite my JavaScript Language Switcher code so that I can still switch languages manually

I am using HubSpot to build my website which contains multi-language variants on some pages. The default pages are written in UK English while the variants are written in US English. The default URLs generate like this: https://example.com/blog/example-post while the US URLS generate like this: https://example.com/en-us/blog/example-post

Currently, I have implemented the following JavaScript code that shows the user the correct URL based on their browser language settings. So when the browser language settings are set to “English-United States” this URL generates: https://example.com/en-us/blog/example-post, and when the browser language settings are set to anything else this URL generates: https://example.com/blog/example-post

<script type="text/javascript">
 // set a HubL variable to pull in languages of available translated pages
 {% set languages = content.translated_content.values()|selectattr('published')|map('language') %}
 // append the current page's language to our languages HubL variable
 {% do languages.append(content.language) %}

 // add toLowerCase to userLang because some browsers use capitals and JavaScript is case sensitive
 const userLang = (navigator.language || navigator.userLanguage).toLowerCase();
 // set our languages HubL variable as our supportedLanguages
 const supportedLanguages = {{ languages|tojson }};
 // set our default language
 const defaultLanguage = "en";
 // get current path
 let path = window.location.pathname;

 // Check if the userLang is "en-GB" and set it to "en" (default language) if true
 if (userLang === "en-gb") {
 userLang = defaultLanguage;
 }

 // get first path (where the language is usually set)
 let pathFirstString = path.split('/')[1];

 // check if first path matches one of our supported languages
 // if it does, update the path variable to remove the first path
 if (supportedLanguages.indexOf(pathFirstString) !== -1) {
 path = '/' + path.split('/').slice(2).join('/');
 }

 // If userLang is not in supported languages
 if (supportedLanguages.indexOf(userLang) === -1) {
 // and current path does not equal default path
 // go to default URL
 if (path !== window.location.pathname) {
 window.location.href = window.location.origin + path;
 }
 // else if our language path does not match the userLang
 } else if (pathFirstString !== userLang) {
 // if userLang does not equal the defaultLanguage, go to userLang URL
 if (userLang !== defaultLanguage) {
 window.location.href = window.location.origin + '/' + userLang + path;
 // else if user is not currently on the default page, go to the default page
 } else if (path !== window.location.pathname) {
 window.location.href = window.location.origin + path;
 }
 }
</script>

The problem is that I also have a language switcher module on the site. So when I manually click on the language switcher icon to switch to either the UK or US version of the page the code overrides this action and keeps it at the URL that it was told to generate based on the browser language settings.

How can I fix this?

I would like users to be redirected to the correct page based on their browser language settings, however, I would also like them to have the option to switch the language themselves.

Hi @DigitalCloud. You can add a local storage variable and check/change that based on user action. If it’s null do the automatic language switch, if it has a value don’t execute the auto switch.

const languageManualOverride = localStorage.getItem('language-manual-override')
if (languageManualOverride === 'false' || languageManualOverride === null) {
 // If userLang is not in supported languages
 if (supportedLanguages.indexOf(userLang) === -1) {
 // and current path does not equal default path
 // go to default URL
 if (path !== window.location.pathname) {
 window.location.href = window.location.origin + path;
 }
 // else if our language path does not match the userLang
 } else if (pathFirstString !== userLang) {
 // if userLang does not equal the defaultLanguage, go to userLang URL
 if (userLang !== defaultLanguage) {
 window.location.href = window.location.origin + '/' + userLang + path;
 // else if user is not currently on the default page, go to the default page
 } else if (path !== window.location.pathname) {
 window.location.href = window.location.origin + path;
 }
 }
}

Add an event listener to the manual switcher

const languages = document.getElementsByClassName('lang-switch');
for (language of langauges) {
 language.addEventListener('click', e => {
 localStorage.setItem('language-manual-override', 'true');
 });
}

Hello, @piersg Thank you so much for your help thus far. I am struggling to figure out where to implement this code or if I am using the wrong information (class name etc).

I added the code to the header HTML of my blog paste template. I did of course use html <script></script> tags. I added the event listener to the navbar module (module.js) in the Design Manager. I also tried changing the class name of the event listener to class name of the language switcher module. So far I haven’t achieved any success.
Do you know where and how to correctly input this code within HubSpot?

I was also advised that a Javascript event listener won’t work here because the page is essentially reloading when you select a different language in the language switcher, defaulting to the original condition of “Redirect according to the user’s browser language”.

Therefore we would need to have something to override that condition upon page load, such as a cookie or URL parameter. For example, we could add an URL parameter like ?or=1 (Override = true) to each of the language switcher options. In the Javascript, we’d then just tell it not to redirect if the URL contains that parameter.

@piersg Do you have any insight on this?

Local storage will work across page redirection/refresh so that solves the reloading issue. For the first issue can you link an example page so I can give more specific help on where to put the event listener for the language switcher?

The language switching logic should go something like this:

<script type="text/javascript">
 // set a HubL variable to pull in languages of available translated pages
 {% set languages = content.translated_content.values()|selectattr('published')|map('language') %}
 // append the current page's language to our languages HubL variable
 {% do languages.append(content.language) %}

 // variable for when user chooses their language manually using language switcher
 const languageManualOverride = localStorage.getItem('language-manual-override')
 // add toLowerCase to userLang because some browsers use capitals and JavaScript is case sensitive
 const userLang = (navigator.language || navigator.userLanguage).toLowerCase();
 // set our languages HubL variable as our supportedLanguages
 const supportedLanguages = {{ languages|tojson }};
 // set our default language
 const defaultLanguage = "en";
 // get current path
 let path = window.location.pathname;

 // Check if the userLang is "en-GB" and set it to "en" (default language) if true
 if (userLang === "en-gb") {
 userLang = defaultLanguage;
 }

 // get first path (where the language is usually set)
 let pathFirstString = path.split('/')[1];

 // check if first path matches one of our supported languages
 // if it does, update the path variable to remove the first path
 if (supportedLanguages.indexOf(pathFirstString) !== -1) {
 path = '/' + path.split('/').slice(2).join('/');
 }

 // if the user has not manually selected their language
 if (languageManualOverride === 'false' || languageManualOverride === null) {
 // If userLang is not in supported languages
 if (supportedLanguages.indexOf(userLang) === -1) {
 // and current path does not equal default path
 // go to default URL
 if (path !== window.location.pathname) {
 window.location.href = window.location.origin + path;
 }
 // else if our language path does not match the userLang
 } else if (pathFirstString !== userLang) {
 // if userLang does not equal the defaultLanguage, go to userLang URL
 if (userLang !== defaultLanguage) {
 window.location.href = window.location.origin + '/' + userLang + path;
 // else if user is not currently on the default page, go to the default page
 } else if (path !== window.location.pathname) {
 window.location.href = window.location.origin + path;
 }
 }
 }
</script>

Hi @piersg Here is a link to a blog post Klipboard Blog

So the click event to write to local storage should be:

const langaugeLinks = document.getElementsByClassName('lang_switcher_link');
for (language of langaugeLinks) {
 language.addEventListener('click', e => {
 localStorage.setItem('language-manual-override', 'true');
 });
}