spellchecker-spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import { BrowserWindow, Session, session } from 'electron/main';
  2. import { expect } from 'chai';
  3. import * as path from 'path';
  4. import * as fs from 'fs';
  5. import * as http from 'http';
  6. import { closeWindow } from './lib/window-helpers';
  7. import { ifit, ifdescribe, listen } from './lib/spec-helpers';
  8. import { once } from 'events';
  9. import { setTimeout } from 'timers/promises';
  10. const features = process._linkedBinding('electron_common_features');
  11. const v8Util = process._linkedBinding('electron_common_v8_util');
  12. ifdescribe(features.isBuiltinSpellCheckerEnabled())('spellchecker', function () {
  13. this.timeout((process.env.IS_ASAN ? 200 : 20) * 1000);
  14. let w: BrowserWindow;
  15. async function rightClick () {
  16. const contextMenuPromise = once(w.webContents, 'context-menu');
  17. w.webContents.sendInputEvent({
  18. type: 'mouseDown',
  19. button: 'right',
  20. x: 43,
  21. y: 42
  22. });
  23. return (await contextMenuPromise)[1] as Electron.ContextMenuParams;
  24. }
  25. // When the page is just loaded, the spellchecker might not be ready yet. Since
  26. // there is no event to know the state of spellchecker, the only reliable way
  27. // to detect spellchecker is to keep checking with a busy loop.
  28. async function rightClickUntil (fn: (params: Electron.ContextMenuParams) => boolean) {
  29. const now = Date.now();
  30. const timeout = (process.env.IS_ASAN ? 180 : 10) * 1000;
  31. let contextMenuParams = await rightClick();
  32. while (!fn(contextMenuParams) && (Date.now() - now < timeout)) {
  33. await setTimeout(100);
  34. contextMenuParams = await rightClick();
  35. }
  36. return contextMenuParams;
  37. }
  38. // Setup a server to download hunspell dictionary.
  39. const server = http.createServer((req, res) => {
  40. // The provided is minimal dict for testing only, full list of words can
  41. // be found at src/third_party/hunspell_dictionaries/xx_XX.dic.
  42. fs.readFile(path.join(__dirname, '/../../third_party/hunspell_dictionaries/xx-XX-3-0.bdic'), function (err, data) {
  43. if (err) {
  44. console.error('Failed to read dictionary file');
  45. res.writeHead(404);
  46. res.end(JSON.stringify(err));
  47. return;
  48. }
  49. res.writeHead(200);
  50. res.end(data);
  51. });
  52. });
  53. let serverUrl: string;
  54. before(async () => {
  55. serverUrl = (await listen(server)).url;
  56. });
  57. after(() => server.close());
  58. const fixtures = path.resolve(__dirname, 'fixtures');
  59. const preload = path.join(fixtures, 'module', 'preload-electron.js');
  60. const generateSpecs = (description: string, sandbox: boolean) => {
  61. describe(description, () => {
  62. beforeEach(async () => {
  63. w = new BrowserWindow({
  64. show: false,
  65. webPreferences: {
  66. partition: `unique-spell-${Date.now()}`,
  67. contextIsolation: false,
  68. preload,
  69. sandbox
  70. }
  71. });
  72. w.webContents.session.setSpellCheckerDictionaryDownloadURL(serverUrl);
  73. w.webContents.session.setSpellCheckerLanguages(['en-US']);
  74. await w.loadFile(path.resolve(__dirname, './fixtures/chromium/spellchecker.html'));
  75. });
  76. afterEach(async () => {
  77. await closeWindow(w);
  78. });
  79. // Context menu test can not run on Windows.
  80. const shouldRun = process.platform !== 'win32';
  81. ifit(shouldRun)('should detect correctly spelled words as correct', async () => {
  82. await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typography"');
  83. await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()');
  84. const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.selectionText.length > 0);
  85. expect(contextMenuParams.misspelledWord).to.eq('');
  86. expect(contextMenuParams.dictionarySuggestions).to.have.lengthOf(0);
  87. });
  88. ifit(shouldRun)('should detect incorrectly spelled words as incorrect', async () => {
  89. await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"');
  90. await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()');
  91. const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0);
  92. expect(contextMenuParams.misspelledWord).to.eq('typograpy');
  93. expect(contextMenuParams.dictionarySuggestions).to.have.length.of.at.least(1);
  94. });
  95. ifit(shouldRun)('should detect incorrectly spelled words as incorrect after disabling all languages and re-enabling', async () => {
  96. w.webContents.session.setSpellCheckerLanguages([]);
  97. await setTimeout(500);
  98. w.webContents.session.setSpellCheckerLanguages(['en-US']);
  99. await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"');
  100. await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()');
  101. const contextMenuParams = await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0);
  102. expect(contextMenuParams.misspelledWord).to.eq('typograpy');
  103. expect(contextMenuParams.dictionarySuggestions).to.have.length.of.at.least(1);
  104. });
  105. ifit(shouldRun)('should expose webFrame spellchecker correctly', async () => {
  106. await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"');
  107. await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()');
  108. await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0);
  109. const callWebFrameFn = (expr: string) => w.webContents.executeJavaScript(`electron.webFrame.${expr}`);
  110. expect(await callWebFrameFn('isWordMisspelled("typography")')).to.equal(false);
  111. expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(true);
  112. expect(await callWebFrameFn('getWordSuggestions("typography")')).to.be.empty();
  113. expect(await callWebFrameFn('getWordSuggestions("typograpy")')).to.not.be.empty();
  114. });
  115. describe('spellCheckerEnabled', () => {
  116. it('is enabled by default', async () => {
  117. expect(w.webContents.session.spellCheckerEnabled).to.be.true();
  118. });
  119. ifit(shouldRun)('can be dynamically changed', async () => {
  120. await w.webContents.executeJavaScript('document.body.querySelector("textarea").value = "typograpy"');
  121. await w.webContents.executeJavaScript('document.body.querySelector("textarea").focus()');
  122. await rightClickUntil((contextMenuParams) => contextMenuParams.misspelledWord.length > 0);
  123. const callWebFrameFn = (expr: string) => w.webContents.executeJavaScript(`electron.webFrame.${expr}`);
  124. w.webContents.session.spellCheckerEnabled = false;
  125. v8Util.runUntilIdle();
  126. expect(w.webContents.session.spellCheckerEnabled).to.be.false();
  127. // spellCheckerEnabled is sent to renderer asynchronously and there is
  128. // no event notifying when it is finished, so wait a little while to
  129. // ensure the setting has been changed in renderer.
  130. await setTimeout(500);
  131. expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(false);
  132. w.webContents.session.spellCheckerEnabled = true;
  133. v8Util.runUntilIdle();
  134. expect(w.webContents.session.spellCheckerEnabled).to.be.true();
  135. await setTimeout(500);
  136. expect(await callWebFrameFn('isWordMisspelled("typograpy")')).to.equal(true);
  137. });
  138. });
  139. describe('custom dictionary word list API', () => {
  140. let ses: Session;
  141. beforeEach(async () => {
  142. // ensure a new session runs on each test run
  143. ses = session.fromPartition(`persist:customdictionary-test-${Date.now()}`);
  144. });
  145. afterEach(async () => {
  146. if (ses) {
  147. await ses.clearStorageData();
  148. ses = null as any;
  149. }
  150. });
  151. describe('ses.listWordsFromSpellCheckerDictionary', () => {
  152. it('should successfully list words in custom dictionary', async () => {
  153. const words = ['foo', 'bar', 'baz'];
  154. const results = words.map(word => ses.addWordToSpellCheckerDictionary(word));
  155. expect(results).to.eql([true, true, true]);
  156. const wordList = await ses.listWordsInSpellCheckerDictionary();
  157. expect(wordList).to.have.deep.members(words);
  158. });
  159. it('should return an empty array if no words are added', async () => {
  160. const wordList = await ses.listWordsInSpellCheckerDictionary();
  161. expect(wordList).to.have.length(0);
  162. });
  163. });
  164. describe('ses.addWordToSpellCheckerDictionary', () => {
  165. it('should successfully add word to custom dictionary', async () => {
  166. const result = ses.addWordToSpellCheckerDictionary('foobar');
  167. expect(result).to.equal(true);
  168. const wordList = await ses.listWordsInSpellCheckerDictionary();
  169. expect(wordList).to.eql(['foobar']);
  170. });
  171. it('should fail for an empty string', async () => {
  172. const result = ses.addWordToSpellCheckerDictionary('');
  173. expect(result).to.equal(false);
  174. const wordList = await ses.listWordsInSpellCheckerDictionary;
  175. expect(wordList).to.have.length(0);
  176. });
  177. // remove API will always return false because we can't add words
  178. it('should fail for non-persistent sessions', async () => {
  179. const tempSes = session.fromPartition('temporary');
  180. const result = tempSes.addWordToSpellCheckerDictionary('foobar');
  181. expect(result).to.equal(false);
  182. });
  183. });
  184. describe('ses.setSpellCheckerLanguages', () => {
  185. const isMac = process.platform === 'darwin';
  186. ifit(isMac)('should be a no-op when setSpellCheckerLanguages is called on macOS', () => {
  187. expect(() => {
  188. w.webContents.session.setSpellCheckerLanguages(['i-am-a-nonexistent-language']);
  189. }).to.not.throw();
  190. });
  191. ifit(!isMac)('should throw when a bad language is passed', () => {
  192. expect(() => {
  193. w.webContents.session.setSpellCheckerLanguages(['i-am-a-nonexistent-language']);
  194. }).to.throw(/Invalid language code provided: "i-am-a-nonexistent-language" is not a valid language code/);
  195. });
  196. ifit(!isMac)('should not throw when a recognized language is passed', () => {
  197. expect(() => {
  198. w.webContents.session.setSpellCheckerLanguages(['es']);
  199. }).to.not.throw();
  200. });
  201. });
  202. describe('SetSpellCheckerDictionaryDownloadURL', () => {
  203. const isMac = process.platform === 'darwin';
  204. ifit(isMac)('should be a no-op when a bad url is passed on macOS', () => {
  205. expect(() => {
  206. w.webContents.session.setSpellCheckerDictionaryDownloadURL('i-am-not-a-valid-url');
  207. }).to.not.throw();
  208. });
  209. ifit(!isMac)('should throw when a bad url is passed', () => {
  210. expect(() => {
  211. w.webContents.session.setSpellCheckerDictionaryDownloadURL('i-am-not-a-valid-url');
  212. }).to.throw(/The URL you provided to setSpellCheckerDictionaryDownloadURL is not a valid URL/);
  213. });
  214. });
  215. describe('ses.removeWordFromSpellCheckerDictionary', () => {
  216. it('should successfully remove words to custom dictionary', async () => {
  217. const result1 = ses.addWordToSpellCheckerDictionary('foobar');
  218. expect(result1).to.equal(true);
  219. const wordList1 = await ses.listWordsInSpellCheckerDictionary();
  220. expect(wordList1).to.eql(['foobar']);
  221. const result2 = ses.removeWordFromSpellCheckerDictionary('foobar');
  222. expect(result2).to.equal(true);
  223. const wordList2 = await ses.listWordsInSpellCheckerDictionary();
  224. expect(wordList2).to.have.length(0);
  225. });
  226. it('should fail for words not in custom dictionary', () => {
  227. const result2 = ses.removeWordFromSpellCheckerDictionary('foobar');
  228. expect(result2).to.equal(false);
  229. });
  230. });
  231. });
  232. });
  233. };
  234. generateSpecs('without sandbox', false);
  235. generateSpecs('with sandbox', true);
  236. });