i18n.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Implementation of chrome.i18n.getMessage
  2. // https://developer.chrome.com/extensions/i18n#method-getMessage
  3. //
  4. // Does not implement predefined messages:
  5. // https://developer.chrome.com/extensions/i18n#overview-predefined
  6. const {ipcRenderer} = require('electron')
  7. const fs = require('fs')
  8. const path = require('path')
  9. let metadata
  10. const getExtensionMetadata = (extensionId) => {
  11. if (!metadata) {
  12. metadata = ipcRenderer.sendSync('CHROME_I18N_MANIFEST', extensionId)
  13. }
  14. return metadata
  15. }
  16. const getMessagesPath = (extensionId, language) => {
  17. const metadata = getExtensionMetadata(extensionId)
  18. const defaultLocale = metadata.default_locale || 'en'
  19. const localesDirectory = path.join(metadata.srcDirectory, '_locales')
  20. let messagesPath = path.join(localesDirectory, language, 'messages.json')
  21. if (!fs.statSyncNoException(messagesPath)) {
  22. messagesPath = path.join(localesDirectory, defaultLocale, 'messages.json')
  23. }
  24. return messagesPath
  25. }
  26. const getMessages = (extensionId, language) => {
  27. try {
  28. const messagesPath = getMessagesPath(extensionId, language)
  29. return JSON.parse(fs.readFileSync(messagesPath)) || {}
  30. } catch (error) {
  31. return {}
  32. }
  33. }
  34. const getLanguage = () => {
  35. return navigator.language.replace(/-.*$/, '').toLowerCase()
  36. }
  37. const replaceNumberedSubstitutions = (message, substitutions) => {
  38. return message.replace(/\$(\d+)/, (_, number) => {
  39. const index = parseInt(number, 10) - 1
  40. return substitutions[index] || ''
  41. })
  42. }
  43. const replacePlaceholders = (message, placeholders, substitutions) => {
  44. if (typeof substitutions === 'string') {
  45. substitutions = [substitutions]
  46. }
  47. if (!Array.isArray(substitutions)) {
  48. substitutions = []
  49. }
  50. if (placeholders) {
  51. Object.keys(placeholders).forEach((name) => {
  52. let {content} = placeholders[name]
  53. content = replaceNumberedSubstitutions(content, substitutions)
  54. message = message.replace(new RegExp(`\\$${name}\\$`, 'gi'), content)
  55. })
  56. }
  57. return replaceNumberedSubstitutions(message, substitutions)
  58. }
  59. const getMessage = (extensionId, messageName, substitutions) => {
  60. const messages = getMessages(extensionId, getLanguage())
  61. if (messages.hasOwnProperty(messageName)) {
  62. const {message, placeholders} = messages[messageName]
  63. return replacePlaceholders(message, placeholders, substitutions)
  64. }
  65. }
  66. exports.setup = (extensionId) => {
  67. return {
  68. getMessage (messageName, substitutions) {
  69. return getMessage(extensionId, messageName, substitutions)
  70. }
  71. }
  72. }