拼字檢查器
自 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
的文件,以瞭解有關從何處取得字典檔案以及如何託管它們的更多資訊。