lang.js 1018 B

12345678910111213141516171819202122232425262728293031323334
  1. ;(() => {
  2. const supportedLangs = window.supportedLangs
  3. const cacheKey = 'preferred_lang'
  4. const defaultLang = 'en-US'
  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 =
  13. langAlias[userPreferredLang] ||
  14. (supportedLangs.includes(userPreferredLang)
  15. ? userPreferredLang
  16. : defaultLang)
  17. localStorage.setItem(cacheKey, language)
  18. userPreferredLang = language
  19. if (!location.pathname.startsWith(`/${userPreferredLang}`)) {
  20. const toPath = [`/${userPreferredLang}`]
  21. .concat(location.pathname.split('/').slice(2))
  22. .join('/')
  23. location.pathname =
  24. toPath.endsWith('.html') || toPath.endsWith('/')
  25. ? toPath
  26. : toPath.concat('/')
  27. }
  28. if (navigator && navigator.serviceWorker.controller) {
  29. navigator.serviceWorker.controller.postMessage({
  30. type: 'LANG',
  31. lang: userPreferredLang,
  32. })
  33. }
  34. })()