IE11下使用navigator.language进行语言检测失效问题排查
Hey there, let's break down why your language detection code fails in IE11 while working smoothly in modern browsers. The core issue is simple: IE11 doesn't support the navigator.languages property — this is a modern browser feature available in Chrome, Firefox, and Edge, but IE11 only provides the single navigator.language string. When your code tries to access navigator.languages[0], it's attempting to grab the 0th index of an undefined value, which triggers the TypeError you're seeing.
Here's how to fix it step by step:
- Add a compatibility check for
navigator.languages
First, safely retrieve the primary browser language without assumingnavigator.languagesexists. Fall back tonavigator.languageif the array property isn't available. - Optimize language matching logic
Instead of checking for exact string matches, use string prefix checks to cover more valid language variants (like regional subcodes) while still targeting your supported locales.
Fixed Code
function* setLanguageFromBrowserSettings() { let lang = null; // Safely get primary browser language with IE11 fallback const primaryLang = navigator.languages ? navigator.languages[0] : navigator.language; if (primaryLang) { // Match all English variants (en, en-US, en-GB, etc.) if (primaryLang.startsWith('en')) { lang = 'en-US'; console.log("Language set to en-US"); } // Match all Simplified Chinese variants (zh, zh-CN, zh-Hans, etc.) else if (primaryLang.startsWith('zh')) { // Optional: Add stricter check if you want to target only Simplified Chinese specifically // if (primaryLang.includes('Hans') || primaryLang === 'zh' || primaryLang === 'zh-CN') lang = 'zh-Hans'; console.log("Language set to zh-Hans"); } } // Only update locale if we detected a supported language (keep default en-GB otherwise) if (lang) { yield put({ type: "Translations/SetLocale", payload: lang }); } }
Key Improvements:
- IE11 Compatibility: We first verify if
navigator.languagesexists before accessing its 0th index. If not, we usenavigator.languagewhich IE11 fully supports. - Robust Matching: Using
startsWith()covers more valid language codes (likeen-GBwill still map toen-USif that's your desired behavior, or you can tweak the check for stricter matching). - Cleaner Logic: Reduced redundant code by consolidating language checks into a single block after safely retrieving the primary language.
This code will work reliably in Chrome, Firefox, and IE11, updating the locale only when it detects a supported English or Simplified Chinese variant, and sticking to your default en-GB otherwise.
内容的提问来源于stack exchange,提问作者Michael Smith

