Skip to content

Instantly share code, notes, and snippets.

@jordanmaslyn
Created October 23, 2024 18:11
Show Gist options
  • Save jordanmaslyn/dd05c9cab5c4f5bae5316ce801cc8286 to your computer and use it in GitHub Desktop.
Save jordanmaslyn/dd05c9cab5c4f5bae5316ce801cc8286 to your computer and use it in GitHub Desktop.
This snippet will read the preferred language out of a visitor's browser, and based on a mapping you define, redirect them to a matching locale prefix for subdirectory based localization.
<!--
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<script>
const defaultLang = "en";
const languageLocales = {
// browser language : site subdirectory
[defaultLang]: "",
"en-ca": "en-ca",
"es": "es",
"de": "de",
"fr": "fr",
// Add more language mappings as needed
};
function redirectToLocaleBasedOnBrowserLanguage() {
// Get the current URL path
const path = window.location.pathname;
if (path === "/") {
// don't need to redirect on homepage
return;
}
const localePrefix = getLocale();
if (shouldRedirect(path, localePrefix)) {
redirect(path, localePrefix);
}
}
function getLocale() {
// Get the user's preferred languages from the browser
const userLanguages = navigator.languages || [navigator.language || navigator.userLanguage];
let userLang = userLanguages[0];
if (!userLang) {
// Default if no language is specified
userLang = defaultLang;
} else {
if (userLang.includes("-") && languageLocales.hasOwnProperty(userLang.toLowerCase())) {
// Use regional localization
userLang = userLang.toLowerCase();
} else {
// Extract the primary language code (e.g., "en" from "en-US")
userLang = userLang.split('-')[0];
}
}
return languageLocales[userLang];
}
function shouldRedirect(path, localePrefix) {
// Split the path to check if it already includes a locale prefix
const pathSegments = path.split('/');
const firstSegment = pathSegments[1]; // First segment after the leading '/'
// Check if visitor is explicitly requesting a specific locale
const alreadyInSpecificLocale = Object.values(languageLocales).includes(firstSegment);
// Check if their preferred language already matches the default locale
const isDefaultLocale = localePrefix === "";
return !isDefaultLocale && !alreadyInSpecificLocale;
}
function redirect(path, localePrefix) {
// Construct the new path with the locale prefix
const newPath = '/' + localePrefix + path;
// Preserve query parameters and hash fragments
const search = window.location.search;
const hash = window.location.hash;
// Build the complete new URL
const newUrl = newPath + search + hash;
// Redirect to the new URL without affecting browser history
window.location.replace(newUrl);
}
redirectToLocaleBasedOnBrowserLanguage();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment