api-ipc-main-spec.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { expect } from 'chai';
  2. import * as path from 'node:path';
  3. import * as cp from 'node:child_process';
  4. import { closeAllWindows } from './lib/window-helpers';
  5. import { defer } from './lib/spec-helpers';
  6. import { ipcMain, BrowserWindow } from 'electron/main';
  7. import { once } from 'node:events';
  8. describe('ipc main module', () => {
  9. const fixtures = path.join(__dirname, 'fixtures');
  10. afterEach(closeAllWindows);
  11. describe('ipc.sendSync', () => {
  12. afterEach(() => { ipcMain.removeAllListeners('send-sync-message'); });
  13. it('does not crash when reply is not sent and browser is destroyed', (done) => {
  14. const w = new BrowserWindow({
  15. show: false,
  16. webPreferences: {
  17. nodeIntegration: true,
  18. contextIsolation: false
  19. }
  20. });
  21. ipcMain.once('send-sync-message', (event) => {
  22. event.returnValue = null;
  23. done();
  24. });
  25. w.loadFile(path.join(fixtures, 'api', 'send-sync-message.html'));
  26. });
  27. it('does not crash when reply is sent by multiple listeners', (done) => {
  28. const w = new BrowserWindow({
  29. show: false,
  30. webPreferences: {
  31. nodeIntegration: true,
  32. contextIsolation: false
  33. }
  34. });
  35. ipcMain.on('send-sync-message', (event) => {
  36. event.returnValue = null;
  37. });
  38. ipcMain.on('send-sync-message', (event) => {
  39. event.returnValue = null;
  40. done();
  41. });
  42. w.loadFile(path.join(fixtures, 'api', 'send-sync-message.html'));
  43. });
  44. });
  45. describe('ipcMain.on', () => {
  46. it('is not used for internals', async () => {
  47. const appPath = path.join(fixtures, 'api', 'ipc-main-listeners');
  48. const electronPath = process.execPath;
  49. const appProcess = cp.spawn(electronPath, [appPath]);
  50. let output = '';
  51. appProcess.stdout.on('data', (data) => { output += data; });
  52. await once(appProcess.stdout, 'end');
  53. output = JSON.parse(output);
  54. expect(output).to.deep.equal(['error']);
  55. });
  56. it('can be replied to', async () => {
  57. ipcMain.on('test-echo', (e, arg) => {
  58. e.reply('test-echo', arg);
  59. });
  60. defer(() => {
  61. ipcMain.removeAllListeners('test-echo');
  62. });
  63. const w = new BrowserWindow({
  64. show: false,
  65. webPreferences: {
  66. nodeIntegration: true,
  67. contextIsolation: false
  68. }
  69. });
  70. w.loadURL('about:blank');
  71. const v = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  72. const { ipcRenderer } = require('electron')
  73. ipcRenderer.send('test-echo', 'hello')
  74. ipcRenderer.on('test-echo', (e, v) => {
  75. resolve(v)
  76. })
  77. })`);
  78. expect(v).to.equal('hello');
  79. });
  80. });
  81. });