lang.js 1.0 KB

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