拼写检查器

自 Electron 8 以来已内置支持 Chromium 拼写检查器。 On Windows and Linux this is powered by Hunspell dictionaries, and on macOS it makes use of the native spellchecker APIs.

How to enable the spellchecker?

对于 Electron 9 及以上,默认启用拼写检查器。 For Electron 8 you need to enable it in webPreferences.

  1. const myWindow = new BrowserWindow({
  2. webPreferences: {
  3. spellcheck: true
  4. }
  5. })

How to set the languages the spellchecker uses?

On macOS as we use the native APIs there is no way to set the language that the spellchecker uses. 默认情况下,macOS 本机拼写检查器会自动检测您使用的语言。

对于 Windows 和 Linux,你应该使用一些 Electron API 来设置拼写检查器的语言。

  1. // Sets the spellchecker to check English US and French
  2. myWindow.session.setSpellCheckerLanguages(['en-US', 'fr'])
  3. // An array of all available language codes
  4. const possibleLanguages = myWindow.session.availableSpellCheckerLanguages

By default the spellchecker will enable the language matching the current OS locale.

How do I put the results of the spellchecker in my context menu?

All the required information to generate a context menu is provided in the context-menu event on each webContents instance. 下面提供了一个小的示例,如何用此信息制作上下文菜单。

  1. const { Menu, MenuItem } = require('electron')
  2. myWindow.webContents.on('context-menu', (event, params) => {
  3. const menu = new Menu()
  4. // Add each spelling suggestion
  5. for (const suggestion of params.dictionarySuggestions) {
  6. menu.append(new MenuItem({
  7. label: suggestion,
  8. click: () => mainWindow.webContents.replaceMisspelling(suggestion)
  9. }))
  10. }
  11. // Allow users to add the misspelled word to the dictionary
  12. if (params.misspelledWord) {
  13. menu.append(
  14. new MenuItem({
  15. label: 'Add to dictionary',
  16. click: () => mainWindow.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord)
  17. })
  18. )
  19. }
  20. menu.popup()
  21. })

Does the spellchecker use any Google services?

虽然拼写检查器本身没有发送任何输入, 单词或用户输入到谷歌服务中,hunspell 字典文件默认从谷歌 CDN 下载。 如果你想要避免这种情况,你可以提供一个替代 URL 来下载字典。

  1. myWindow.session.setSpellCheckerDictionaryDownloadURL('https://example.com/dictionaries/')

Check out the docs for session.setSpellCheckerDictionaryDownloadURL for more information on where to get the dictionary files from and how you need to host them.