lang.js 1.0 KB

1234567891011121314151617181920212223242526
  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 = langAlias[userPreferredLang] || (supportedLangs.includes(userPreferredLang) ? userPreferredLang : defaultLang)
  14. localStorage.setItem(cacheKey, language)
  15. userPreferredLang = language
  16. if (!location.pathname.startsWith(`/${userPreferredLang}`)) {
  17. const toPath = [`/${userPreferredLang}`].concat(location.pathname.split('/').slice(2)).join('/')
  18. location.pathname = toPath.endsWith('.html') || toPath.endsWith('/') ? toPath : toPath.concat('/')
  19. }
  20. if (navigator && navigator.serviceWorker.controller) {
  21. navigator.serviceWorker.controller.postMessage({
  22. type: 'LANG',
  23. lang: userPreferredLang,
  24. })
  25. }
  26. })()