lang.js 1.0 KB

12345678910111213141516171819202122232425
  1. ;(() => {
  2. const supportedLangs = window.supportedLangs
  3. const cacheKey = 'preferred_lang'
  4. const defaultLang = 'zh-CN'
  5. // docs supported languages
  6. const langAlias = {
  7. en: 'en-US',
  8. fr: 'fr-FR',
  9. es: 'es-ES',
  10. }
  11. let userPreferredLang = localStorage.getItem(cacheKey) || navigator.language
  12. const language = langAlias[userPreferredLang] || (supportedLangs.includes(userPreferredLang) ? userPreferredLang : defaultLang)
  13. localStorage.setItem(cacheKey, language)
  14. userPreferredLang = language
  15. if (!location.pathname.startsWith(`/${userPreferredLang}`)) {
  16. const toPath = [`/${userPreferredLang}`].concat(location.pathname.split('/').slice(2)).join('/')
  17. location.pathname = toPath.endsWith('.html') || toPath.endsWith('/') ? toPath : toPath.concat('/')
  18. }
  19. if (navigator && navigator.serviceWorker.controller) {
  20. navigator.serviceWorker.controller.postMessage({
  21. type: 'LANG',
  22. lang: userPreferredLang,
  23. })
  24. }
  25. })()