Automatically detect browser language

Hi dudes, it’s my first post on the community. I have to say I’m pretty much engaged with Ghost CMS and I’m starting out and having a blast.

I am writing this because I’m in need of some way of automatically detecting the user’s browser and redirecting him to a translated version of any of my posts. Of course, I’m planning to translate them by myself.

I’ve already followed a few guides, like this one https://ghost.org/tutorials/multi-language-content/ and it seems I lack a script.

TLDR: I’m not looking for a dropdown, but a way of automatically detecting browser language and redirecting to correct post language
Excuse my bad english,

Thanks!

Hey @Nicolas_Gutierrez :wave:

I think this can be done with some JavaScript. If you’re following the guide you’ll hopefully be putting those alternative translations in the head of the counter part articles, like this:

<!-- All the translations that have been noted for this article -->
<link rel="alternate" hreflang="en" href="https://site.com/article/" />
<link rel="alternate" hreflang="us" href="https://site.com/us/article/" />
<link rel="alternate" hreflang="fr" href="https://site.com/fr/article/" />
<link rel="alternate" hreflang="es" href="https://site.com/es/article/" />

By having these in the head that should hopefully be noted by search bots like Google so your readers will end up on the right translation for them. If they land on a page that isn’t their preferred translation then we can use the information in the head to redirect them to the right translation. Here’s some JavaScript I put together as a concept:

<script>
var userLang = navigator.language || navigator.userLanguage; // Browser language

const translations = [...document.querySelectorAll("[hreflang]")]; // All the translations

switch(userLang) {

	// If they speak american english
    case 'en-US': 
		// Redirect them to the US translation noted in the head
        window.location.href = translations.filter(item => item.hreflang == 'us');
        break;

	// If they speak french…
	case 'fr-FR':
		// Redirect them to the french translation noted in the head
        window.location.href = translations.filter(item => item.hreflang == 'fr');
        break;

	// If they speak spanish…
	case 'es-ES':
		
		// Redirect them to the spanish translation noted in the head
        window.location.href = translations.filter(item => item.hreflang == 'es');
        break;
	// By default do nothing, or redirect them to the default language if you wish
	default:
		break;
}
</script>

After you’ve modified this to your preferred translations this JavaScript can go into your site code injection area. This does require that you have all the translations already added to the page, and if there isn’t one then it could cause an error.

Is this the kind of thing you’re looking for?