From 84960af793d0a43166400f5024c469ba762cfc1e Mon Sep 17 00:00:00 2001 From: Kevin Sawicki Date: Tue, 7 Jun 2016 15:34:17 -0700 Subject: [PATCH] Add initial chrome.i18n.getMessage API --- filenames.gypi | 1 + lib/browser/chrome-extension.js | 4 ++++ lib/renderer/chrome-api.js | 2 ++ lib/renderer/extensions/i18n.js | 34 +++++++++++++++++++++++++++++++++ 4 files changed, 41 insertions(+) create mode 100644 lib/renderer/extensions/i18n.js diff --git a/filenames.gypi b/filenames.gypi index 5f1fdc3b141..af1942fc369 100644 --- a/filenames.gypi +++ b/filenames.gypi @@ -63,6 +63,7 @@ 'lib/renderer/api/remote.js', 'lib/renderer/api/screen.js', 'lib/renderer/api/web-frame.js', + 'lib/renderer/extensions/i18n.js', ], 'js2c_sources': [ 'lib/common/asar.js', diff --git a/lib/browser/chrome-extension.js b/lib/browser/chrome-extension.js index fc49f5e06be..97bf292f9e2 100644 --- a/lib/browser/chrome-extension.js +++ b/lib/browser/chrome-extension.js @@ -115,6 +115,10 @@ ipcMain.on('CHROME_RUNTIME_CONNECT', function (event, extensionId, connectInfo) page.webContents.sendToAll(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, event.sender.id, portId, connectInfo) }) +ipcMain.on('CHROME_I18N_MANIFEST', function (event, extensionId) { + event.returnValue = manifestMap[extensionId] +}) + ipcMain.on('CHROME_RUNTIME_SENDMESSAGE', function (event, extensionId, message) { const page = backgroundPages[extensionId] if (!page) { diff --git a/lib/renderer/chrome-api.js b/lib/renderer/chrome-api.js index 17c3f5bfbd1..b22fe743fd2 100644 --- a/lib/renderer/chrome-api.js +++ b/lib/renderer/chrome-api.js @@ -199,4 +199,6 @@ exports.injectTo = function (extensionId, isBackgroundPage, context) { setPopup () {}, getPopup () {} } + + chrome.i18n = require('./extensions/i18n.js') } diff --git a/lib/renderer/extensions/i18n.js b/lib/renderer/extensions/i18n.js new file mode 100644 index 00000000000..34a559bedb3 --- /dev/null +++ b/lib/renderer/extensions/i18n.js @@ -0,0 +1,34 @@ +const {ipcRenderer} = require('electron') +const fs = require('fs') +const path = require('path') + +const getMessagesPath = (language) => { + const manifest = ipcRenderer.sendSync('CHROME_I18N_MANIFEST', chrome.runtime.id) + let messagesPath = path.join(manifest.srcDirectory, '_locales', language, 'messages.json') + if (!fs.statSyncNoException(messagesPath)) { + messagesPath = path.join(manifest.srcDirectory, '_locales', manifest.default_locale, 'messages.json') + } + return messagesPath +} + +const getMessages = (language) => { + try { + return JSON.parse(fs.readFileSync(getMessagesPath(language))) || {} + } catch (error) { + return {} + } +} + +const getLanguage = () => { + return navigator.language.replace(/-.*$/, '').toLowerCase() +} + +module.exports = { + getMessage (messageName, substitutions) { + const language = getLanguage() + const messages = getMessages(language) + if (messages.hasOwnProperty(messageName)) { + return messages[messageName].message + } + } +}