One-time browser-language auto-detect (default locale only): visitors whose navigator.languages match a locale that actually has pages get location.replace'd to that locale's URL once, stored in localStorage vl-lang; the switcher's manual pick overwrites the flag; crawlers (en-US) and untranslated locales unaffected
deploy / build-and-publish (push) Successful in 40s

This commit is contained in:
Keith
2026-11-22 15:16:56 +01:00
parent 5e299f67b2
commit d873b06c07
+25 -1
View File
@@ -131,6 +131,25 @@ const hasForm = isAudiencePage;
// DOMContentLoaded, not at parse time (found live 2026-11-21: the
// banner never dismissed because it did not exist yet on lookup).
const KEY = "vl-consent";
const LANG_KEY = "vl-lang";
// One-time browser-language detection, default locale only: if the
// visitor's navigator.languages match one of our locales and they
// haven't chosen one (stored flag), hop to that locale's version of
// this page ONCE. Crawlers send en-US, so they never get redirected;
// hreflang/sitemap already handle indexing of every locale URL.
try {
if (${JSON.stringify(locale)} === ${JSON.stringify(DEFAULT_LOCALE)} && !localStorage.getItem(LANG_KEY)) {
const codes = ${JSON.stringify([...new Set(parsePages().map((p) => p.code))])};
const want = (navigator.languages || [navigator.language || ""]).map((l) => String(l).slice(0, 2).toLowerCase());
const hit = want.find((w) => codes.includes(w) && w !== ${JSON.stringify(DEFAULT_LOCALE)});
if (hit) {
localStorage.setItem(LANG_KEY, hit);
const prefix = "/" + hit;
const rest = ${JSON.stringify(pageId)} === "" ? "/" : "/" + ${JSON.stringify(pageId)} + "/";
location.replace(${JSON.stringify(baseUrl)} + prefix + rest);
}
}
} catch {}
const STATS_URL = ${JSON.stringify(site.stats_script_url)};
const STATS_ID = ${JSON.stringify(site.stats_website_id)};
const injectStats = () => {
@@ -207,7 +226,7 @@ const hasForm = isAudiencePage;
<span aria-hidden="true">{strings.switcher_label}</span>
<select aria-label={strings.lang_label}>
{alternates.map((a) => (
<option value={pageUrl(a.code, a.id)} selected={a.code === locale}>
<option value={pageUrl(a.code, a.id)} data-code={a.code} selected={a.code === locale}>
{localeByCode(a.code)?.name ?? a.code}
</option>
))}
@@ -382,6 +401,11 @@ const hasForm = isAudiencePage;
const langSelect = document.querySelector(".switcher select");
if (langSelect) {
langSelect.addEventListener("change", (e) => {
// a manual pick is the visitor's choice - remember it so the
// one-time auto-detect never overrides it
try {
localStorage.setItem("vl-lang", e.target.selectedOptions[0]?.dataset.code || "");
} catch {}
location.href = e.target.value;
});
}