refactor: implement chrome.i18n.getMessage() without the remote module (#16739)

* refactor: implement chrome.i18n.getMessage() without the remote module

* replace navigator.language with app.getLocale()
This commit is contained in:
Milan Burda 2019-02-08 21:07:09 +01:00 committed by Shelley Vohr
parent b97f6bd7d4
commit 1632c4b837
2 changed files with 34 additions and 38 deletions

View file

@ -4,6 +4,7 @@ const { app, webContents, BrowserWindow } = require('electron')
const { getAllWebContents } = process.atomBinding('web_contents')
const renderProcessPreferences = process.atomBinding('render_process_preferences').forAllWebContents()
const { ipcMainInternal } = require('@electron/internal/browser/ipc-main-internal')
const ipcMainUtils = require('@electron/internal/browser/ipc-main-internal-utils')
const { Buffer } = require('buffer')
const fs = require('fs')
@ -166,10 +167,6 @@ ipcMainInternal.on('CHROME_RUNTIME_CONNECT', function (event, extensionId, conne
page.webContents._sendInternalToAll(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, event.sender.id, portId, connectInfo)
})
ipcMainInternal.on('CHROME_I18N_MANIFEST', function (event, extensionId) {
event.returnValue = manifestMap[extensionId]
})
let resultID = 1
ipcMainInternal.on('CHROME_RUNTIME_SENDMESSAGE', function (event, extensionId, message, originResultID) {
const page = backgroundPages[extensionId]
@ -201,6 +198,34 @@ ipcMainInternal.on('CHROME_TABS_SEND_MESSAGE', function (event, tabId, extension
resultID++
})
const getLanguage = () => {
return app.getLocale().replace(/-.*$/, '').toLowerCase()
}
const getMessagesPath = (extensionId) => {
const metadata = manifestMap[extensionId]
if (!metadata) {
throw new Error(`Invalid extensionId: ${extensionId}`)
}
const localesDirectory = path.join(metadata.srcDirectory, '_locales')
const language = getLanguage()
try {
const filename = path.join(localesDirectory, language, 'messages.json')
fs.accessSync(filename, fs.constants.R_OK)
return filename
} catch (err) {
const defaultLocale = metadata.default_locale || 'en'
return path.join(localesDirectory, defaultLocale, 'messages.json')
}
}
ipcMainUtils.handleSync('CHROME_GET_MESSAGES', function (event, extensionId) {
const messagesPath = getMessagesPath(extensionId)
return fs.readFileSync(messagesPath)
})
const isChromeExtension = function (pageURL) {
const { protocol } = url.parse(pageURL)
return protocol === 'chrome-extension:'