api-ipc-spec.ts 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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.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.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.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<void>(resolve => {
  302. port2.start();
  303. port2.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<void>(resolve => {
  315. port2.start();
  316. port2.onclose = resolve;
  317. require('electron').ipcRenderer.postMessage('nobody-listening', null, [port1]);
  318. require('electron').ipcRenderer.send('do-a-gc');
  319. });
  320. }})()`);
  321. });
  322. });
  323. describe('when context destroyed', () => {
  324. it('does not crash', async () => {
  325. let count = 0;
  326. const server = http.createServer((req, res) => {
  327. switch (req.url) {
  328. case '/index.html':
  329. res.setHeader('content-type', 'text/html');
  330. res.statusCode = 200;
  331. count = count + 1;
  332. res.end(`
  333. <title>Hello${count}</title>
  334. <script>
  335. var sharedWorker = new SharedWorker('worker.js');
  336. sharedWorker.port.addEventListener('close', function(event) {
  337. console.log('close event', event.data);
  338. });
  339. </script>`);
  340. break;
  341. case '/worker.js':
  342. res.setHeader('content-type', 'application/javascript; charset=UTF-8');
  343. res.statusCode = 200;
  344. res.end(`
  345. self.addEventListener('connect', function(event) {
  346. var port = event.ports[0];
  347. port.addEventListener('message', function(event) {
  348. console.log('Message from main:', event.data);
  349. port.postMessage('Hello from SharedWorker!');
  350. });
  351. });`);
  352. break;
  353. default:
  354. throw new Error(`unsupported endpoint: ${req.url}`);
  355. }
  356. });
  357. const { port } = await listen(server);
  358. defer(() => {
  359. server.close();
  360. });
  361. const w = new BrowserWindow({ show: false });
  362. await w.loadURL(`http://localhost:${port}/index.html`);
  363. expect(w.webContents.getTitle()).to.equal('Hello1');
  364. // Before the fix, it would crash if reloaded, but now it doesn't
  365. await w.loadURL(`http://localhost:${port}/index.html`);
  366. expect(w.webContents.getTitle()).to.equal('Hello2');
  367. // const crashEvent = emittedOnce(w.webContents, 'render-process-gone');
  368. // await crashEvent;
  369. });
  370. });
  371. });
  372. describe('MessageChannelMain', () => {
  373. it('can be created', () => {
  374. const { port1, port2 } = new MessageChannelMain();
  375. expect(port1).not.to.be.null();
  376. expect(port2).not.to.be.null();
  377. });
  378. it('throws an error when an invalid parameter is sent to postMessage', () => {
  379. const { port1 } = new MessageChannelMain();
  380. expect(() => {
  381. const buffer = new ArrayBuffer(10) as any;
  382. port1.postMessage(null, [buffer]);
  383. }).to.throw(/Port at index 0 is not a valid port/);
  384. expect(() => {
  385. port1.postMessage(null, ['1' as any]);
  386. }).to.throw(/Port at index 0 is not a valid port/);
  387. expect(() => {
  388. port1.postMessage(null, [new Date() as any]);
  389. }).to.throw(/Port at index 0 is not a valid port/);
  390. });
  391. it('throws when postMessage transferables contains the source port', () => {
  392. const { port1 } = new MessageChannelMain();
  393. expect(() => {
  394. port1.postMessage(null, [port1]);
  395. }).to.throw(/Port at index 0 contains the source port./);
  396. });
  397. it('can send messages within the process', async () => {
  398. const { port1, port2 } = new MessageChannelMain();
  399. port2.postMessage('hello');
  400. port1.start();
  401. const [ev] = await once(port1, 'message');
  402. expect(ev.data).to.equal('hello');
  403. });
  404. it('can pass one end to a WebContents', async () => {
  405. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  406. w.loadURL('about:blank');
  407. await w.webContents.executeJavaScript(`(${function () {
  408. const { ipcRenderer } = require('electron');
  409. ipcRenderer.on('port', ev => {
  410. const [port] = ev.ports;
  411. port.onmessage = () => {
  412. ipcRenderer.send('done');
  413. };
  414. });
  415. }})()`);
  416. const { port1, port2 } = new MessageChannelMain();
  417. port1.postMessage('hello');
  418. w.webContents.postMessage('port', null, [port2]);
  419. await once(ipcMain, 'done');
  420. });
  421. it('can be passed over another channel', async () => {
  422. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  423. w.loadURL('about:blank');
  424. await w.webContents.executeJavaScript(`(${function () {
  425. const { ipcRenderer } = require('electron');
  426. ipcRenderer.on('port', e1 => {
  427. e1.ports[0].onmessage = e2 => {
  428. e2.ports[0].onmessage = e3 => {
  429. ipcRenderer.send('done', e3.data);
  430. };
  431. };
  432. });
  433. }})()`);
  434. const { port1, port2 } = new MessageChannelMain();
  435. const { port1: port3, port2: port4 } = new MessageChannelMain();
  436. port1.postMessage(null, [port4]);
  437. port3.postMessage('hello');
  438. w.webContents.postMessage('port', null, [port2]);
  439. const [, message] = await once(ipcMain, 'done');
  440. expect(message).to.equal('hello');
  441. });
  442. it('can send messages to a closed port', () => {
  443. const { port1, port2 } = new MessageChannelMain();
  444. port2.start();
  445. port2.on('message', () => { throw new Error('unexpected message received'); });
  446. port1.close();
  447. port1.postMessage('hello');
  448. });
  449. it('can send messages to a port whose remote end is closed', () => {
  450. const { port1, port2 } = new MessageChannelMain();
  451. port2.start();
  452. port2.on('message', () => { throw new Error('unexpected message received'); });
  453. port2.close();
  454. port1.postMessage('hello');
  455. });
  456. it('throws when passing null ports', () => {
  457. const { port1 } = new MessageChannelMain();
  458. expect(() => {
  459. port1.postMessage(null, [null] as any);
  460. }).to.throw(/Port at index 0 is not a valid port/);
  461. });
  462. it('throws when passing duplicate ports', () => {
  463. const { port1 } = new MessageChannelMain();
  464. const { port1: port3 } = new MessageChannelMain();
  465. expect(() => {
  466. port1.postMessage(null, [port3, port3]);
  467. }).to.throw(/duplicate/);
  468. });
  469. it('throws when passing ports that have already been neutered', () => {
  470. const { port1 } = new MessageChannelMain();
  471. const { port1: port3 } = new MessageChannelMain();
  472. port1.postMessage(null, [port3]);
  473. expect(() => {
  474. port1.postMessage(null, [port3]);
  475. }).to.throw(/already neutered/);
  476. });
  477. it('throws when passing itself', () => {
  478. const { port1 } = new MessageChannelMain();
  479. expect(() => {
  480. port1.postMessage(null, [port1]);
  481. }).to.throw(/contains the source port/);
  482. });
  483. describe('GC behavior', () => {
  484. it('is not collected while it could still receive messages', async () => {
  485. let trigger: Function;
  486. const promise = new Promise(resolve => { trigger = resolve; });
  487. const port1 = (() => {
  488. const { port1, port2 } = new MessageChannelMain();
  489. port2.on('message', (e) => { trigger(e.data); });
  490. port2.start();
  491. return port1;
  492. })();
  493. v8Util.requestGarbageCollectionForTesting();
  494. port1.postMessage('hello');
  495. expect(await promise).to.equal('hello');
  496. });
  497. });
  498. });
  499. const generateTests = (title: string, postMessage: (contents: WebContents) => WebContents['postMessage']) => {
  500. describe(title, () => {
  501. it('sends a message', async () => {
  502. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  503. w.loadURL('about:blank');
  504. await w.webContents.executeJavaScript(`(${function () {
  505. const { ipcRenderer } = require('electron');
  506. ipcRenderer.on('foo', (_e, msg) => {
  507. ipcRenderer.send('bar', msg);
  508. });
  509. }})()`);
  510. postMessage(w.webContents)('foo', { some: 'message' });
  511. const [, msg] = await once(ipcMain, 'bar');
  512. expect(msg).to.deep.equal({ some: 'message' });
  513. });
  514. describe('error handling', () => {
  515. it('throws on missing channel', async () => {
  516. const w = new BrowserWindow({ show: false });
  517. await w.loadURL('about:blank');
  518. expect(() => {
  519. (postMessage(w.webContents) as any)();
  520. }).to.throw(/Insufficient number of arguments/);
  521. });
  522. it('throws on invalid channel', async () => {
  523. const w = new BrowserWindow({ show: false });
  524. await w.loadURL('about:blank');
  525. expect(() => {
  526. postMessage(w.webContents)(null as any, '', []);
  527. }).to.throw(/Error processing argument at index 0/);
  528. });
  529. it('throws on missing message', async () => {
  530. const w = new BrowserWindow({ show: false });
  531. await w.loadURL('about:blank');
  532. expect(() => {
  533. (postMessage(w.webContents) as any)('channel');
  534. }).to.throw(/Insufficient number of arguments/);
  535. });
  536. it('throws on non-serializable message', async () => {
  537. const w = new BrowserWindow({ show: false });
  538. await w.loadURL('about:blank');
  539. expect(() => {
  540. postMessage(w.webContents)('channel', w);
  541. }).to.throw(/An object could not be cloned/);
  542. });
  543. it('throws on invalid transferable list', async () => {
  544. const w = new BrowserWindow({ show: false });
  545. await w.loadURL('about:blank');
  546. expect(() => {
  547. postMessage(w.webContents)('', '', null as any);
  548. }).to.throw(/Invalid value for transfer/);
  549. });
  550. it('throws on transferring non-transferable', async () => {
  551. const w = new BrowserWindow({ show: false });
  552. await w.loadURL('about:blank');
  553. expect(() => {
  554. (postMessage(w.webContents) as any)('channel', '', [123]);
  555. }).to.throw(/Invalid value for transfer/);
  556. });
  557. it('throws when passing null ports', async () => {
  558. const w = new BrowserWindow({ show: false });
  559. await w.loadURL('about:blank');
  560. expect(() => {
  561. postMessage(w.webContents)('foo', null, [null] as any);
  562. }).to.throw(/Invalid value for transfer/);
  563. });
  564. it('throws when passing duplicate ports', async () => {
  565. const w = new BrowserWindow({ show: false });
  566. await w.loadURL('about:blank');
  567. const { port1 } = new MessageChannelMain();
  568. expect(() => {
  569. postMessage(w.webContents)('foo', null, [port1, port1]);
  570. }).to.throw(/duplicate/);
  571. });
  572. it('throws when passing ports that have already been neutered', async () => {
  573. const w = new BrowserWindow({ show: false });
  574. await w.loadURL('about:blank');
  575. const { port1 } = new MessageChannelMain();
  576. postMessage(w.webContents)('foo', null, [port1]);
  577. expect(() => {
  578. postMessage(w.webContents)('foo', null, [port1]);
  579. }).to.throw(/already neutered/);
  580. });
  581. });
  582. });
  583. };
  584. generateTests('WebContents.postMessage', contents => contents.postMessage.bind(contents));
  585. generateTests('WebFrameMain.postMessage', contents => contents.mainFrame.postMessage.bind(contents.mainFrame));
  586. });
  587. describe('WebContents.ipc', () => {
  588. afterEach(closeAllWindows);
  589. it('receives ipc messages sent from the WebContents', async () => {
  590. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  591. w.loadURL('about:blank');
  592. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  593. const [, num] = await once(w.webContents.ipc, 'test');
  594. expect(num).to.equal(42);
  595. });
  596. it('receives sync-ipc messages sent from the WebContents', async () => {
  597. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  598. w.loadURL('about:blank');
  599. w.webContents.ipc.on('test', (event, arg) => {
  600. event.returnValue = arg * 2;
  601. });
  602. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
  603. expect(result).to.equal(42 * 2);
  604. });
  605. it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
  606. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  607. w.loadURL('about:blank');
  608. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
  609. const [event] = await once(w.webContents.ipc, 'test');
  610. expect(event.ports.length).to.equal(1);
  611. });
  612. it('handles invoke messages sent from the WebContents', async () => {
  613. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  614. w.loadURL('about:blank');
  615. w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
  616. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  617. expect(result).to.equal(42 * 2);
  618. });
  619. it('cascades to ipcMain', async () => {
  620. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  621. w.loadURL('about:blank');
  622. let gotFromIpcMain = false;
  623. const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
  624. const ipcReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { resolve(gotFromIpcMain); }));
  625. defer(() => ipcMain.removeAllListeners('test'));
  626. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  627. // assert that they are delivered in the correct order
  628. expect(await ipcReceived).to.be.false();
  629. await ipcMainReceived;
  630. });
  631. it('overrides ipcMain handlers', async () => {
  632. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  633. w.loadURL('about:blank');
  634. w.webContents.ipc.handle('test', (_event, arg) => arg * 2);
  635. ipcMain.handle('test', () => { throw new Error('should not be called'); });
  636. defer(() => ipcMain.removeHandler('test'));
  637. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  638. expect(result).to.equal(42 * 2);
  639. });
  640. it('falls back to ipcMain handlers', async () => {
  641. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  642. w.loadURL('about:blank');
  643. ipcMain.handle('test', (_event, arg) => { return arg * 2; });
  644. defer(() => ipcMain.removeHandler('test'));
  645. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  646. expect(result).to.equal(42 * 2);
  647. });
  648. it('receives ipcs from child frames', async () => {
  649. const server = http.createServer((req, res) => {
  650. res.setHeader('content-type', 'text/html');
  651. res.end('');
  652. });
  653. const { port } = await listen(server);
  654. defer(() => {
  655. server.close();
  656. });
  657. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
  658. // Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
  659. await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
  660. w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
  661. const [, arg] = await once(w.webContents.ipc, 'test');
  662. expect(arg).to.equal(42);
  663. });
  664. });
  665. describe('WebFrameMain.ipc', () => {
  666. afterEach(closeAllWindows);
  667. it('responds to ipc messages in the main frame', async () => {
  668. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  669. w.loadURL('about:blank');
  670. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  671. const [, arg] = await once(w.webContents.mainFrame.ipc, 'test');
  672. expect(arg).to.equal(42);
  673. });
  674. it('responds to sync ipc messages in the main frame', async () => {
  675. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  676. w.loadURL('about:blank');
  677. w.webContents.mainFrame.ipc.on('test', (event, arg) => {
  678. event.returnValue = arg * 2;
  679. });
  680. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.sendSync(\'test\', 42)');
  681. expect(result).to.equal(42 * 2);
  682. });
  683. it('receives postMessage messages sent from the WebContents, w/ MessagePorts', async () => {
  684. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  685. w.loadURL('about:blank');
  686. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.postMessage(\'test\', null, [(new MessageChannel).port1])');
  687. const [event] = await once(w.webContents.mainFrame.ipc, 'test');
  688. expect(event.ports.length).to.equal(1);
  689. });
  690. it('handles invoke messages sent from the WebContents', async () => {
  691. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  692. w.loadURL('about:blank');
  693. w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
  694. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  695. expect(result).to.equal(42 * 2);
  696. });
  697. it('cascades to WebContents and ipcMain', async () => {
  698. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  699. w.loadURL('about:blank');
  700. let gotFromIpcMain = false;
  701. let gotFromWebContents = false;
  702. const ipcMainReceived = new Promise<void>(resolve => ipcMain.on('test', () => { gotFromIpcMain = true; resolve(); }));
  703. const ipcWebContentsReceived = new Promise<boolean>(resolve => w.webContents.ipc.on('test', () => { gotFromWebContents = true; resolve(gotFromIpcMain); }));
  704. const ipcReceived = new Promise<boolean>(resolve => w.webContents.mainFrame.ipc.on('test', () => { resolve(gotFromWebContents); }));
  705. defer(() => ipcMain.removeAllListeners('test'));
  706. w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.send(\'test\', 42)');
  707. // assert that they are delivered in the correct order
  708. expect(await ipcReceived).to.be.false();
  709. expect(await ipcWebContentsReceived).to.be.false();
  710. await ipcMainReceived;
  711. });
  712. it('overrides ipcMain handlers', async () => {
  713. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  714. w.loadURL('about:blank');
  715. w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
  716. ipcMain.handle('test', () => { throw new Error('should not be called'); });
  717. defer(() => ipcMain.removeHandler('test'));
  718. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  719. expect(result).to.equal(42 * 2);
  720. });
  721. it('overrides WebContents handlers', async () => {
  722. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  723. w.loadURL('about:blank');
  724. w.webContents.ipc.handle('test', () => { throw new Error('should not be called'); });
  725. w.webContents.mainFrame.ipc.handle('test', (_event, arg) => arg * 2);
  726. ipcMain.handle('test', () => { throw new Error('should not be called'); });
  727. defer(() => ipcMain.removeHandler('test'));
  728. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  729. expect(result).to.equal(42 * 2);
  730. });
  731. it('falls back to WebContents handlers', async () => {
  732. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  733. w.loadURL('about:blank');
  734. w.webContents.ipc.handle('test', (_event, arg) => { return arg * 2; });
  735. const result = await w.webContents.executeJavaScript('require(\'electron\').ipcRenderer.invoke(\'test\', 42)');
  736. expect(result).to.equal(42 * 2);
  737. });
  738. it('receives ipcs from child frames', async () => {
  739. const server = http.createServer((req, res) => {
  740. res.setHeader('content-type', 'text/html');
  741. res.end('');
  742. });
  743. const { port } = await listen(server);
  744. defer(() => {
  745. server.close();
  746. });
  747. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, preload: path.resolve(fixturesPath, 'preload-expose-ipc.js') } });
  748. // Preloads don't run in about:blank windows, and file:// urls can't be loaded in iframes, so use a blank http page.
  749. await w.loadURL(`data:text/html,<iframe src="http://localhost:${port}"></iframe>`);
  750. w.webContents.mainFrame.frames[0].executeJavaScript('ipc.send(\'test\', 42)');
  751. w.webContents.mainFrame.ipc.on('test', () => { throw new Error('should not be called'); });
  752. const [, arg] = await once(w.webContents.mainFrame.frames[0].ipc, 'test');
  753. expect(arg).to.equal(42);
  754. });
  755. });
  756. });