拼写检查器¶
自 Electron 8 起,Electron 内置了对 Chromium 拼写检查器的支持。在 Windows 和 Linux 上,它由 Hunspell 词典提供支持;在 macOS 上,它使用原生拼写检查器 API。
如何启用拼写检查器?¶
对于 Electron 9 及更高版本,拼写检查器默认启用。对于 Electron 8,你需要在 webPreferences 中启用它。
如何设置拼写检查器使用的语言?¶
在 macOS 上,由于我们使用原生 API,无法设置拼写检查器使用的语言。默认情况下,macOS 上的原生拼写检查器会自动为你检测正在使用的语言。
对于 Windows 和 Linux,有几个 Electron API 可用于设置拼写检查器的语言。
```js @ts-type={myWindow:Electron.BrowserWindow} // 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
默认情况下,拼写检查器会启用与当前操作系统区域设置匹配的语言。
## 如何将拼写检查器的结果放入我的上下文菜单? {#how-do-i-put-the-results-of-the-spellchecker-in-my-context-menu}
生成上下文菜单所需的所有信息都会通过每个 `webContents` 实例上的 [`context-menu`](../api/web-contents.md#event-context-menu) 事件提供。下面提供了一个使用这些信息创建上下文菜单的简单示例。
```js @ts-type={myWindow:Electron.BrowserWindow}
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 来下载词典。
js @ts-type={myWindow:Electron.BrowserWindow}
myWindow.webContents.session.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')
查看 session.setSpellCheckerDictionaryDownloadURL 的文档,了解从哪里获取词典文件以及如何托管这些文件的更多信息。
本页原文 Markdown:在 AtomGit 查看·内容源自开源项目 el/electron