拼写检查
从 Electron 8 开始,Electron 就内置了对 Chromium 拼写检查器的支持。在 Windows 和 Linux 上,这是由 Hunspell 词典提供支持的,而在 macOS 上,它利用了原生拼写检查器 API。
如何启用拼写检查器?
对于 Electron 9 及更高版本,拼写检查器默认启用。对于 Electron 8,您需要在 webPreferences
中启用它。
const myWindow = new BrowserWindow({
webPreferences: {
spellcheck: true
}
})
如何设置拼写检查器使用的语言?
在 macOS 上,由于我们使用了原生 API,因此无法设置拼写检查器使用的语言。在 macOS 上,原生拼写检查器将自动为您检测正在使用的语言。
对于 Windows 和 Linux,您应该使用一些 Electron API 来设置拼写检查器的语言。
// Sets the spellchecker to check English US and French
myWindow.webContents.session.setSpellCheckerLanguages(['en-US', 'fr'])
// An array of all available language codes
const possibleLanguages = myWindow.webContents.session.availableSpellCheckerLanguages
默认情况下,拼写检查器将启用与当前操作系统区域设置匹配的语言。
如何将拼写检查器的结果放入我的上下文菜单?
生成上下文菜单所需的所有信息都包含在每个 webContents
实例的 context-menu
事件中。下面提供了一个使用此信息创建上下文菜单的小示例。
const { Menu, MenuItem } = require('electron')
myWindow.webContents.on('context-menu', (event, params) => {
const menu = new Menu()
// Add each spelling suggestion
for (const suggestion of params.dictionarySuggestions) {
menu.append(new MenuItem({
label: suggestion,
click: () => myWindow.webContents.replaceMisspelling(suggestion)
}))
}
// Allow users to add the misspelled word to the dictionary
if (params.misspelledWord) {
menu.append(
new MenuItem({
label: 'Add to dictionary',
click: () => myWindow.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord)
})
)
}
menu.popup()
})
拼写检查器是否使用任何 Google 服务?
虽然拼写检查器本身不向 Google 服务发送任何输入的字符、单词或用户输入,但默认情况下,hunspell 词典文件是从 Google CDN 下载的。如果您想避免这种情况,可以提供一个备用 URL 来下载词典。
myWindow.webContents.session.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')
请参阅 session.setSpellCheckerDictionaryDownloadURL
的文档,了解有关从何处获取词典文件以及如何托管它们的更多信息。