跳至主要内容

拼写检查器

自 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 的文档,了解有关从何处获取字典文件以及如何托管它们的更多信息。