api-ipc-spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. import { EventEmitter, once } from 'node:events';
  2. import { expect } from 'chai';
  3. import { BrowserWindow, ipcMain, IpcMainInvokeEvent, MessageChannelMain, WebContents } from 'electron/main';
  4. import { closeAllWindows } from './lib/window-helpers';
  5. import { defer, listen } from './lib/spec-helpers';
  6. import * as path from 'node:path';
  7. import * as http from 'node:http';
  8. const v8Util = process._linkedBinding('electron_common_v8_util');
  9. const fixturesPath = path.resolve(__dirname, 'fixtures');
  10. describe('ipc module', () => {
  11. describe('invoke', () => {
  12. let w: BrowserWindow;
  13. before(async () => {
  14. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  15. await w.loadURL('about:blank');
  16. });
  17. after(async () => {
  18. w.destroy();
  19. });
  20. async function rendererInvoke (...args: any[]) {
  21. const { ipcRenderer } = require('electron');
  22. try {
  23. const result = await ipcRenderer.invoke('test', ...args);
  24. ipcRenderer.send('result', { result });
  25. } catch (e) {
  26. ipcRenderer.send('result', { error: (e as Error).message });
  27. }
  28. }
  29. it('receives a response from a synchronous handler', async () => {
  30. ipcMain.handleOnce('test', (e: IpcMainInvokeEvent, arg: number) => {
  31. expect(arg).to.equal(123);
  32. return 3;
  33. });
  34. const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
  35. expect(arg).to.deep.equal({ result: 3 });
  36. resolve();
  37. }));
  38. await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`);
  39. await done;
  40. });
  41. it('receives a response from an asynchronous handler', async () => {
  42. ipcMain.handleOnce('test', async (e: IpcMainInvokeEvent, arg: number) => {
  43. expect(arg).to.equal(123);
  44. await new Promise(setImmediate);
  45. return 3;
  46. });
  47. const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
  48. expect(arg).to.deep.equal({ result: 3 });
  49. resolve();
  50. }));
  51. await w.webContents.executeJavaScript(`(${rendererInvoke})(123)`);
  52. await done;
  53. });
  54. it('receives an error from a synchronous handler', async () => {
  55. ipcMain.handleOnce('test', () => {
  56. throw new Error('some error');
  57. });
  58. const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
  59. expect(arg.error).to.match(/some error/);
  60. resolve();
  61. }));
  62. await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
  63. await done;
  64. });
  65. it('receives an error from an asynchronous handler', async () => {
  66. ipcMain.handleOnce('test', async () => {
  67. await new Promise(setImmediate);
  68. throw new Error('some error');
  69. });
  70. const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
  71. expect(arg.error).to.match(/some error/);
  72. resolve();
  73. }));
  74. await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
  75. await done;
  76. });
  77. it('throws an error if no handler is registered', async () => {
  78. const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
  79. expect(arg.error).to.match(/No handler registered/);
  80. resolve();
  81. }));
  82. await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
  83. await done;
  84. });
  85. it('throws an error when invoking a handler that was removed', async () => {
  86. ipcMain.handle('test', () => { });
  87. ipcMain.removeHandler('test');
  88. const done = new Promise<void>(resolve => ipcMain.once('result', (e, arg) => {
  89. expect(arg.error).to.match(/No handler registered/);
  90. resolve();
  91. }));
  92. await w.webContents.executeJavaScript(`(${rendererInvoke})()`);
  93. await done;
  94. });
  95. it('forbids multiple handlers', async () => {
  96. ipcMain.handle('test', () => { });
  97. try {
  98. expect(() => { ipcMain.handle('test', () => { }); }).to.throw(/second handler/);
  99. } finally {
  100. ipcMain.removeHandler('test');
  101. }
  102. });
  103. it('throws an error in the renderer if the reply callback is dropped', async () => {
  104. ipcMain.handleOnce('test', () => new Promise(() => {
  105. setTimeout(() => v8Util.requestGarbageCollectionForTesting());
  106. /* never resolve */
  107. }));
  108. w.webContents.executeJavaScript(`(${rendererInvoke})()`);
  109. const [, { error }] = await once(ipcMain, 'result');
  110. expect(error).to.match(/reply was never sent/);
  111. });
  112. });
  113. describe('ordering', () => {
  114. let w: BrowserWindow;
  115. before(async () => {
  116. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  117. await w.loadURL('about:blank');
  118. });
  119. after(async () => {
  120. w.destroy();
  121. });
  122. it('between send and sendSync is consistent', async () => {
  123. const received: number[] = [];
  124. ipcMain.on('test-async', (e, i) => { received.push(i); });
  125. ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; });
  126. const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); }));
  127. function rendererStressTest () {
  128. const { ipcRenderer } = require('electron');
  129. for (let i = 0; i < 1000; i++) {
  130. switch ((Math.random() * 2) | 0) {
  131. case 0:
  132. ipcRenderer.send('test-async', i);
  133. break;
  134. case 1:
  135. ipcRenderer.sendSync('test-sync', i);
  136. break;
  137. }
  138. }
  139. ipcRenderer.send('done');
  140. }
  141. try {
  142. w.webContents.executeJavaScript(`(${rendererStressTest})()`);
  143. await done;
  144. } finally {
  145. ipcMain.removeAllListeners('test-async');
  146. ipcMain.removeAllListeners('test-sync');
  147. }
  148. expect(received).to.have.lengthOf(1000);
  149. expect(received).to.deep.equal([...received].sort((a, b) => a - b));
  150. });
  151. it('between send, sendSync, and invoke is consistent', async () => {
  152. const received: number[] = [];
  153. ipcMain.handle('test-invoke', (e, i) => { received.push(i); });
  154. ipcMain.on('test-async', (e, i) => { received.push(i); });
  155. ipcMain.on('test-sync', (e, i) => { received.push(i); e.returnValue = null; });
  156. const done = new Promise<void>(resolve => ipcMain.once('done', () => { resolve(); }));
  157. function rendererStressTest () {
  158. const { ipcRenderer } = require('electron');
  159. for (let i = 0; i < 1000; i++) {
  160. switch ((Math.random() * 3) | 0) {
  161. case 0:
  162. ipcRenderer.send('test-async', i);
  163. break;
  164. case 1:
  165. ipcRenderer.sendSync('test-sync', i);
  166. break;
  167. case 2:
  168. ipcRenderer.invoke('test-invoke', i);
  169. break;
  170. }
  171. }
  172. ipcRenderer.send('done');
  173. }
  174. try {
  175. w.webContents.executeJavaScript(`(${rendererStressTest})()`);
  176. await done;
  177. } finally {
  178. ipcMain.removeHandler('test-invoke');
  179. ipcMain.removeAllListeners('test-async');
  180. ipcMain.removeAllListeners('test-sync');
  181. }
  182. expect(received).to.have.lengthOf(1000);
  183. expect(received).to.deep.equal([...received].sort((a, b) => a - b));
  184. });
  185. });
  186. describe('MessagePort', () => {
  187. afterEach(closeAllWindows);
  188. it('can send a port to the main process', async () => {
  189. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  190. w.loadURL('about:blank');
  191. const p = once(ipcMain, 'port');
  192. await w.webContents.executeJavaScript(`(${function () {
  193. const channel = new MessageChannel();
  194. require('electron').ipcRenderer.postMessage('port', 'hi', [channel.port1]);
  195. }})()`);
  196. const [ev, msg] = await p;
  197. expect(msg).to.equal('hi');
  198. expect(ev.ports).to.have.length(1);
  199. expect(ev.senderFrame.parent).to.be.null();
  200. expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
  201. const [port] = ev.ports;
  202. expect(port).to.be.an.instanceOf(EventEmitter);
  203. });
  204. it('can sent a message without a transfer', async () => {
  205. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  206. w.loadURL('about:blank');
  207. const p = once(ipcMain, 'port');
  208. await w.webContents.executeJavaScript(`(${function () {
  209. require('electron').ipcRenderer.postMessage('port', 'hi');
  210. }})()`);
  211. const [ev, msg] = await p;
  212. expect(msg).to.equal('hi');
  213. expect(ev.ports).to.deep.equal([]);
  214. expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
  215. });
  216. it('can communicate between main and renderer', async () => {
  217. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  218. w.loadURL('about:blank');
  219. const p = once(ipcMain, 'port');
  220. await w.webContents.executeJavaScript(`(${function () {
  221. const channel = new MessageChannel();
  222. (channel.port2 as any).onmessage = (ev: any) => {
  223. channel.port2.postMessage(ev.data * 2);
  224. };
  225. require('electron').ipcRenderer.postMessage('port', '', [channel.port1]);
  226. }})()`);
  227. const [ev] = await p;
  228. expect(ev.ports).to.have.length(1);
  229. expect(ev.senderFrame.routingId).to.equal(w.webContents.mainFrame.routingId);
  230. const [port] = ev.ports;
  231. port.start();
  232. port.postMessage(42);
  233. const [ev2] = await once(port, 'message');
  234. expect(ev2.data).to.equal(84);
  235. });
  236. it('can receive a port from a renderer over a MessagePort connection', async () => {
  237. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  238. w.loadURL('about:blank');
  239. function fn () {
  240. const channel1 = new MessageChannel();
  241. const channel2 = new MessageChannel();
  242. channel1.port2.postMessage('', [channel2.port1]);
  243. channel2.port2.postMessage('matryoshka');
  244. require('electron').ipcRenderer.postMessage('port', '', [channel1.port1]);
  245. }
  246. w.webContents.executeJavaScript(`(${fn})()`);
  247. const [{ ports: [port1] }] = await once(ipcMain, 'port');
  248. port1.start();
  249. const [{ ports: [port2] }] = await once(port1, 'message');
  250. port2.start();
  251. const [{ data }] = await once(port2, 'message');
  252. expect(data).to.equal('matryoshka');
  253. });
  254. it('can forward a port from one renderer to another renderer', async () => {
  255. const w1 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  256. const w2 = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  257. w1.loadURL('about:blank');
  258. w2.loadURL('about:blank');
  259. w1.webContents.executeJavaScript(`(${function () {
  260. const channel = new MessageChannel();
  261. (channel.port2 as any).onmessage = (ev: any) => {
  262. require('electron').ipcRenderer.send('message received', ev.data);
  263. };
  264. require('electron').ipcRenderer.postMessage('port', '', [channel.port1]);
  265. }})()`);
  266. const [{ ports: [port] }] = await once(ipcMain, 'port');
  267. await w2.webContents.executeJavaScript(`(${function () {
  268. require('electron').ipcRenderer.on('port', ({ ports: [port] }: any) => {
  269. port.postMessage('a message');
  270. });
  271. }})()`);
  272. w2.webContents.postMessage('port', '', [port]);
  273. const [, data] = await once(ipcMain, 'message received');
  274. expect(data).to.equal('a message');
  275. });
  276. describe('close event', () => {
  277. describe('in renderer', () => {
  278. it('is emitted when the main process closes its end of the port', async () => {
  279. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  280. w.loadURL('about:blank');
  281. await w.webContents.executeJavaScript(`(${function () {
  282. const { ipcRenderer } = require('electron');
  283. ipcRenderer.on('port', e => {
  284. const [port] = e.ports;
  285. port.start();
  286. (port as any).onclose = () => {
  287. ipcRenderer.send('closed');
  288. };
  289. });
  290. }})()`);
  291. const { port1, port2 } = new MessageChannelMain();
  292. w.webContents.postMessage('port', null, [port2]);
  293. port1.close();
  294. await once(ipcMain, 'closed');
  295. });
  296. it('is emitted when the other end of a port is garbage-collected', async () => {
  297. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  298. w.loadURL('about:blank');
  299. await w.webContents.executeJavaScript(`(${async function () {
  300. const { port2 } = new MessageChannel();
  301. await new Promise(resolve => {
  302. port2.start();
  303. (port2 as any).onclose = resolve;
  304. process._linkedBinding('electron_common_v8_util').requestGarbageCollectionForTesting();
  305. });
  306. }})()`);
  307. });
  308. it('is emitted when the other end of a port is sent to nowhere', async () => {
  309. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  310. w.loadURL('about:blank');
  311. ipcMain.once('do-a-gc', () => v8Util.requestGarbageCollectionForTesting());
  312. await w.webContents.executeJavaScript(`(${async function () {
  313. const { port1, port2 } = new MessageChannel();
  314. await new Promise(resolve => {
  315. port2.start();
  316. (port2 as any).onclose = resolve;
  317. require('electron').ipcRenderer.postMessage('nobody-listening', null, [port1]);
  318. require('electron').ipcRenderer.send('do-a-gc');
  319. });
  320. }})()`);
  321. });
  322. });
  323. });
  324. describe('MessageChannelMain', () => {
  325. it('can be created', () => {
  326. const { port1, port2 } = new MessageChannelMain();
  327. expect(port1).not.to.be.null();
  328. expect(port2).not.to.be.null();
  329. });
  330. it('throws an error when an invalid parameter is sent to postMessage', () => {
  331. const { port1 } = new MessageChannelMain();
  332. expect(() => {
  333. const buffer = new ArrayBuffer(10) as any;
  334. port1.postMessage(null, [buffer]);
  335. }).to.throw(/Port at index 0 is not a valid port/);
  336. expect(() => {
  337. port1.postMessage(null, ['1' as any]);
  338. }).to.throw(/Port at index 0 is not a valid port/);
  339. expect(() => {
  340. port1.postMessage(null, [new Date() as any]);
  341. }).to.throw(/Port at index 0 is not a valid port/);
  342. });
  343. it('throws when postMessage transferables contains the source port', () => {
  344. const { port1 } = new MessageChannelMain();
  345. expect(() => {
  346. port1.postMessage(null, [port1]);
  347. }).to.throw(/Port at index 0 contains the source port./);
  348. });
  349. it('can send messages within the process', async () => {
  350. const { port1, port2 } = new MessageChannelMain();
  351. port2.postMessage('hello');
  352. port1.start();
  353. const [ev] = await once(port1, 'message');
  354. expect(ev.data).to.equal('hello');
  355. });
  356. it('can pass one end to a WebContents', async () => {
  357. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  358. w.loadURL('about:blank');
  359. await w.webContents.executeJavaScript(`(${function () {
  360. const { ipcRenderer } = require('electron');
  361. ipcRenderer.on('port', ev => {
  362. const [port] = ev.ports;
  363. port.onmessage = () => {
  364. ipcRenderer.send('done');
  365. };
  366. });
  367. }})()`);
  368. const { port1, port2 } = new MessageChannelMain();
  369. port1.postMessage('hello');
  370. w.webContents.postMessage('port', null, [port2]);
  371. await once(ipcMain, 'done');
  372. });
  373. it('can be passed over another channel', async () => {
  374. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  375. w.loadURL('about:blank');
  376. await w.webContents.executeJavaScript(`(${function () {
  377. const { ipcRenderer } = require('electron');
  378. ipcRenderer.on('port', e1 => {
  379. e1.ports[0].onmessage = e2 => {
  380. e2.ports[0].onmessage = e3 => {
  381. ipcRenderer.send('done', e3.data);
  382. };
  383. };
  384. });
  385. }})()`);
  386. const { port1, port2 } = new MessageChannelMain();
  387. const { port1: port3, port2: port4 } = new MessageChannelMain();
  388. port1.postMessage(null, [port4]);
  389. port3.postMessage('hello');
  390. w.webContents.postMessage('port', null, [port2]);
  391. const [, message] = await once(ipcMain, 'done');
  392. expect(message).to.equal('hello');
  393. });
  394. it('can send messages to a closed port', () => {
  395. const { port1, port2 } = new MessageChannelMain();
  396. port2.start();
  397. port2.on('message', () => { throw new Error('unexpected message received'); });
  398. port1.close();
  399. port1.postMessage('hello');
  400. });
  401. it('can send messages to a port whose remote end is closed', () => {
  402. const { port1, port2 } = new MessageChannelMain();
  403. port2.start();
  404. port2.on('message', () => { throw new Error('unexpected message received'); });
  405. port2.close();
  406. port1.postMessage('hello');
  407. });
  408. it('throws when passing null ports', () => {
  409. const { port1 } = new MessageChannelMain();
  410. expect(() => {
  411. port1.postMessage(null, [null] as any);
  412. }).to.throw(/Port at index 0 is not a valid port/);
  413. });
  414. it('throws when passing duplicate ports', () => {
  415. const { port1 } = new MessageChannelMain();
  416. const { port1: port3 } = new MessageChannelMain();
  417. expect(() => {
  418. port1.postMessage(null, [port3, port3]);
  419. }).to.throw(/duplicate/);
  420. });
  421. it('throws when passing ports that have already been neutered', () => {
  422. const { port1 } = new MessageChannelMain();
  423. const { port1: port3 } = new MessageChannelMain();
  424. port1.postMessage(null, [port3]);
  425. expect(() => {
  426. port1.postMessage(null, [port3]);
  427. }).to.throw(/already neutered/);
  428. });
  429. it('throws when passing itself', () => {
  430. const { port1 } = new MessageChannelMain();
  431. expect(() => {
  432. port1.postMessage(null, [port1]);
  433. }).to.throw(/contains the source port/);
  434. });
  435. describe('GC behavior', () => {
  436. it('is not collected while it could still receive messages', async () => {
  437. let trigger: Function;
  438. const promise = new Promise(resolve => { trigger = resolve; });
  439. const port1 = (() => {
  440. const { port1, port2 } = new MessageChannelMain();
  441. port2.on('message', (e) => { trigger(e.data); });
  442. port2.start();
  443. return port1;
  444. })();
  445. v8Util.requestGarbageCollectionForTesting();
  446. port1.postMessage('hello');
  447. expect(await promise).to.equal('hello');
  448. });
  449. });
  450. });
  451. const generateTests = (title: string, postMessage: (contents: WebContents) => WebContents['postMessage']) => {
  452. describe(title, () => {
  453. it('sends a message', async () => {
  454. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  455. w.loadURL('about:blank');
  456. await w.webContents.executeJavaScript(`(${function () {
  457. const { ipcRenderer } = require('electron');
  458. ipcRenderer.on('foo', (_e, msg) => {
  459. ipcRenderer.send('bar', msg);
  460. });
  461. }})()`);
  462. postMessage(w.webContents)('foo', { some: 'message' });
  463. const [, msg] = await once(ipcMain, 'bar');
  464. expect(msg).to.deep.equal({ some: 'message' });
  465. });
  466. describe('error handling', () => {
  467. it('throws on missing channel', async () => {
  468. const w = new BrowserWindow({ show: false });
  469. await w.loadURL('about:blank');
  470. expect(() => {
  471. (postMessage(w.webContents) as any)();
  472. }).to.throw(/Insufficient number of arguments/);
  473. });
  474. it('throws on invalid channel', async () => {
  475. const w = new BrowserWindow({ show: false });
  476. await w.loadURL('about:blank');
  477. expect(() => {
  478. postMessage(w.webContents)(null as any, '', []);
  479. }).to.throw(/Error processing argument at index 0/);
  480. });
  481. it('throws on missing message', async () => {
  482. const w = new BrowserWindow({ show: false });
  483. await w.loadURL('about:blank');
  484. expect(() => {
  485. (postMessage(w.webContents) as any)('channel');
  486. }).to.throw(/Insufficient number of arguments/);
  487. });
  488. it('throws on non-serializable message', async () => {
  489. const w = new BrowserWindow({ show: false });
  490. await w.loadURL('about:blank');
  491. expect(() => {
  492. postMessage(w.webContents)('channel', w);
  493. }).to.throw(/An object could not be cloned/);
  494. });
  495. it('throws on invalid transferable list', async () => {
  496. const w = new BrowserWindow({ show: false });
  497. await w.loadURL('about:blank');
  498. expect(() => {
  499. postMessage(w.webContents)('', '', null as any);
  500. }).to.throw(/Invalid value for transfer/);
  501. });
  502. it('throws on transferring non-transferable', async () => {
  503. const w = new BrowserWindow({ show: false });
  504. await w.loadURL('about:blank');
  505. expect(() => {
  506. (postMessage(w.webContents) as any)('channel', '', [123]);
  507. }).to.throw(/Invalid value for transfer/);
  508. });
  509. it('throws when passing null ports', async () => {
  510. const w = new BrowserWindow({ show: false });
  511. await w.loadURL('about:blank');
  512. expect(() => {
  513. postMessage(w.webContents)('foo', null, [null] as any);
  514. }).to.throw(/Invalid value for transfer/);
  515. });
  516. it('throws when passing duplicate ports', async () => {
  517. const w = new BrowserWindow({ show: false });
  518. await w.loadURL('about:blank');
  519. const { port1 } = new MessageChannelMain();
  520. expect(() => {
  521. postMessage(w.webContents)('foo', null, [port1, port1]);
  522. }).to.throw(/duplicate/);
  523. });
  524. it('throws when passing ports that have already been neutered', async () => {
  525. const w = new BrowserWindow({ show: false });
  526. await w.loadURL('about:blank');
  527. const { port1 } = new MessageChannelMain();
  528. postMessage(w.webContents)('foo', null, [port1]);
  529. expect(() => {
  530. postMessage(w.webContents)('foo', null, [port1]);
  531. }).to.throw(/already neutered/);
  532. });
  533. });
  534. });
  535. };
  536. generateTests('WebContents.postMessage', contents => contents.postMessage.bind(contents));
  537. generateTests('WebFrameMain.postMessage', contents => contents.mainFrame.postMessage.bind(contents.mainFrame));
  538. });
  539. describe('WebContents.ipc', () => {
  540. afterEach(closeAllWindows);
  541. it('receives ipc messages sent from the WebContents', async () => {
  542. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  543. w.loadURL('about:blank');
  544. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  545. const [, num] = await once(w.webContents.ipc, 'test');
  546. expect(num).to.equal(42);
  547. });
  548. it('receives sync-ipc messages sent from the WebContents', async () => {
  549. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  550. w.loadURL('about:blank');
  551. w.webContents.ipc.on('test', (event, arg) => {
  552. event.returnValue = arg * 2;
  553. });
  554. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
  555. expect(result).to.equal(42 * 2);
  556. });
  557. it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
  558. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  559. w.loadURL('about:blank');
  560. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
  561. const [event] = await once(w.webContents.ipc, 'test');
  562. expect(event.ports.length).to.equal(1);
  563. });
  564. it('handles invoke messages sent from the WebContents', async () => {
  565. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  566. w.loadURL('about:blank');
  567. w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
  568. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  569. expect(result).to.equal(42 * 2);
  570. });
  571. it('cascades to ipcMain', async () => {
  572. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  573. w.loadURL('about:blank');
  574. let gotFromIpcMain = false;
  575. const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
  576. const ipcReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { resolve(gotFromIpcMain); }));
  577. defer(() => ipcMain.removeAllListeners('test'));
  578. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  579. // assert that they are delivered in the correct order
  580. expect(await ipcReceived).to.be.false();
  581. await ipcMainReceived;
  582. });
  583. it('overrides ipcMain handlers', async () => {
  584. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  585. w.loadURL('about:blank');
  586. w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
  587. ipcMain.handle('test', () => { throw new Error('should not be called'); });
  588. defer(() => ipcMain.removeHandler('test'));
  589. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  590. expect(result).to.equal(42 * 2);
  591. });
  592. it('falls back to ipcMain handlers', async () => {
  593. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  594. w.loadURL('about:blank');
  595. ipcMain.handle('test', (_event, arg) => { return arg * 2; });
  596. defer(() => ipcMain.removeHandler('test'));
  597. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  598. expect(result).to.equal(42 * 2);
  599. });
  600. it('receives ipcs from child frames', async () => {
  601. const server = http.createServer((req, res) => {
  602. res.setHeader('content-type', 'text/html');
  603. res.end('');
  604. });
  605. const { port } = await listen(server);
  606. defer(() => {
  607. server.close();
  608. });
  609. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
  610. // Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
  611. await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
  612. w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
  613. const [, arg] = await once(w.webContents.ipc, 'test');
  614. expect(arg).to.equal(42);
  615. });
  616. });
  617. describe('WebFrameMain.ipc', () => {
  618. afterEach(closeAllWindows);
  619. it('responds to ipc messages in the main frame', async () => {
  620. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  621. w.loadURL('about:blank');
  622. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  623. const [, arg] = await once(w.webContents.mainFrame.ipc, 'test');
  624. expect(arg).to.equal(42);
  625. });
  626. it('responds to sync ipc messages in the main frame', async () => {
  627. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  628. w.loadURL('about:blank');
  629. w.webContents.mainFrame.ipc.on('test', (event, arg) => {
  630. event.returnValue = arg * 2;
  631. });
  632. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
  633. expect(result).to.equal(42 * 2);
  634. });
  635. it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
  636. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  637. w.loadURL('about:blank');
  638. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
  639. const [event] = await once(w.webContents.mainFrame.ipc, 'test');
  640. expect(event.ports.length).to.equal(1);
  641. });
  642. it('handles invoke messages sent from the WebContents', async () => {
  643. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  644. w.loadURL('about:blank');
  645. w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
  646. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  647. expect(result).to.equal(42 * 2);
  648. });
  649. it('cascades to WebContents and ipcMain', async () => {
  650. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  651. w.loadURL('about:blank');
  652. let gotFromIpcMain = false;
  653. let gotFromWebContents = false;
  654. const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
  655. const ipcWebContentsReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { gotFromWebContents = true; resolve(gotFromIpcMain); }));
  656. const ipcReceived = new Promise<boolean>(resolve => w.webContents.mainFrame.ipc.on('test', () => { resolve(gotFromWebContents); }));
  657. defer(() => ipcMain.removeAllListeners('test'));
  658. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  659. // assert that they are delivered in the correct order
  660. expect(await ipcReceived).to.be.false();
  661. expect(await ipcWebContentsReceived).to.be.false();
  662. await ipcMainReceived;
  663. });
  664. it('overrides ipcMain handlers', async () => {
  665. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  666. w.loadURL('about:blank');
  667. w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
  668. ipcMain.handle('test', () => { throw new Error('should not be called'); });
  669. defer(() => ipcMain.removeHandler('test'));
  670. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  671. expect(result).to.equal(42 * 2);
  672. });
  673. it('overrides WebContents handlers', async () => {
  674. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  675. w.loadURL('about:blank');
  676. w.webContents.ipc.handle('test', () => { throw new Error('should not be called'); });
  677. w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
  678. ipcMain.handle('test', () => { throw new Error('should not be called'); });
  679. defer(() => ipcMain.removeHandler('test'));
  680. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  681. expect(result).to.equal(42 * 2);
  682. });
  683. it('falls back to WebContents handlers', async () => {
  684. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  685. w.loadURL('about:blank');
  686. w.webContents.ipc.handle('test', (_event, arg) => { return arg * 2; });
  687. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  688. expect(result).to.equal(42 * 2);
  689. });
  690. it('receives ipcs from child frames', async () => {
  691. const server = http.createServer((req, res) => {
  692. res.setHeader('content-type', 'text/html');
  693. res.end('');
  694. });
  695. const { port } = await listen(server);
  696. defer(() => {
  697. server.close();
  698. });
  699. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
  700. // Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
  701. await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
  702. w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
  703. w.webContents.mainFrame.ipc.on('test', () => { throw new Error('should not be called'); });
  704. const [, arg] = await once(w.webContents.mainFrame.frames[0].ipc, 'test');
  705. expect(arg).to.equal(42);
  706. });
  707. });
  708. });