Browser-Language Redirects With JavaScript

XMLans Posted on 2025-07-01 16 Views


A browser’s preferred language can help suggest a localized page without guessing from its IP address. That can be useful for travelers and VPN users, but a preference is still only a hint: the person may want a different language.

For a public multilingual site, visible language links are the best foundation. Google’s multilingual-site guidance recommends separate accessible URLs and advises against automatically redirecting visitors based on a guessed language. A suggestion banner often works better than a forced redirect.

An optional landing-page example

If you deliberately use automatic routing on a dedicated entry page, keep it out of article pages and localized destinations. Replace these example domains with your own. This sample recognizes common Simplified and Traditional Chinese language tags, leaves other languages on the entry page, and respects a stored manual choice.

// Run only on your language-selection homepage.
if (location.hostname === 'www.example.com' && location.pathname === '/') {
  let chosen = false;
  try { chosen = !!localStorage.getItem('preferredLanguage'); } catch (_) {}
  if (!chosen) {
    const lang = (navigator.languages?.[0] || navigator.language || 'en').toLowerCase();
    let target = null;
    if (/^zh-(cn|sg|hans)(-|$)/.test(lang)) target = 'https://cn.example.com/';
    else if (/^zh-(tw|hk|mo|hant)(-|$)/.test(lang)) target = 'https://tw.example.com/';
    if (target && location.href !== target) location.replace(target);
  }
}

Your language selector can save preferredLanguage on the entry page’s origin. localStorage is scoped to an origin; a value written on one subdomain does not automatically exist on another. The source-host and path checks are what keep this example from sending localized pages back through the same routing logic.

navigator.language is a browser API value, not direct access to an HTTP request header. JavaScript navigation also does not create a server-side 301 response, and avoiding a 301 does not automatically preserve rankings. Add appropriate hreflang annotations, keep the language versions crawlable, and offer an obvious way to choose another language.

Adapted from the original Chinese article, published on July 1, 2025.

Hi! I frequently update with various articles about technology, practical tips, and cutting-edge news. I hope it will be helpful to you!
Last updated on 2026-09-30