codecamp

Electron 拼写检查器

自 Electron 8 以来已内置支持 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 来设置拼写检查器的语言。

// 设置拼写检查器以检查英语 和 法语
myWindow.session.setSpellCheckerLanguages(['en-US', 'fr'])

// 所有可用语言代码的数组
const possibleLanguages = myWindow.session.availableSpellCheckerLanguages

默认情况下,拼写检查器将启用与当前操作系统区域匹配的语言。

如何将拼写检查器的结果放在上下文菜单中?

生成上下文菜单所需的所有信息都在每个 webContents 实例的 context-menu 事件中提供。 下面提供了一个小的示例,如何用此信息制作上下文菜单。

const { Menu, MenuItem } = require('electron')

myWindow.webContents.on('context-menu', (event, params) => {
  const menu = new Menu()

  // 添加每个拼写建议
  for (const suggestion of params.dictionarySuggestions) {
    menu.append(new MenuItem({
      label: suggestion,
      click: () => mainWindow.webContents.replaceMisspelling(suggestion)
    }))
  }

  // 允许用户 将拼错的单词添加到字典中
  if (params.misspelledWord) {
    menu.append(
      new MenuItem({
        label: 'Add to dictionary',
        click: () => mainWindow.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord)
      })
    )
  }

  menu.popup()
})

拼写检查器是否使用任何谷歌服务?

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

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


Electron 在 BrowserWindow 中展示文件
Electron Tray
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }