api-remote-spec.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. import * as path from 'path';
  2. import { expect } from 'chai';
  3. import { closeAllWindows } from './window-helpers';
  4. import { ifdescribe } from './spec-helpers';
  5. import { ipcMain, BrowserWindow, nativeImage, NativeImage } from 'electron';
  6. import { emittedOnce } from './events-helpers';
  7. import { serialize, deserialize } from '../lib/common/type-utils';
  8. const features = process.electronBinding('features');
  9. const expectPathsEqual = (path1: string, path2: string) => {
  10. if (process.platform === 'win32') {
  11. path1 = path1.toLowerCase();
  12. path2 = path2.toLowerCase();
  13. }
  14. expect(path1).to.equal(path2);
  15. };
  16. function makeRemotely (windowGetter: () => BrowserWindow) {
  17. async function remotely (script: Function, ...args: any[]) {
  18. // executeJavaScript obfuscates the error if the script throws, so catch any
  19. // errors manually.
  20. const assembledScript = `(async function() {
  21. try {
  22. return { result: await Promise.resolve((${script})(...${JSON.stringify(args)})) }
  23. } catch (e) {
  24. return { error: e.message, stack: e.stack }
  25. }
  26. })()`;
  27. const { result, error, stack } = await windowGetter().webContents.executeJavaScript(assembledScript);
  28. if (error) {
  29. const e = new Error(error);
  30. e.stack = stack;
  31. throw e;
  32. }
  33. return result;
  34. }
  35. remotely.it = (...vars: any[]) => (name: string, fn: Function) => {
  36. it(name, async () => {
  37. await remotely(fn, ...vars);
  38. });
  39. };
  40. return remotely;
  41. }
  42. function makeWindow () {
  43. let w: BrowserWindow;
  44. before(async () => {
  45. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableRemoteModule: true } });
  46. await w.loadURL('about:blank');
  47. await w.webContents.executeJavaScript(`{
  48. const chai_1 = window.chai_1 = require('chai')
  49. chai_1.use(require('chai-as-promised'))
  50. chai_1.use(require('dirty-chai'))
  51. null
  52. }`);
  53. });
  54. after(closeAllWindows);
  55. return () => w;
  56. }
  57. function makeEachWindow () {
  58. let w: BrowserWindow;
  59. beforeEach(async () => {
  60. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, enableRemoteModule: true } });
  61. await w.loadURL('about:blank');
  62. await w.webContents.executeJavaScript(`{
  63. const chai_1 = window.chai_1 = require('chai')
  64. chai_1.use(require('chai-as-promised'))
  65. chai_1.use(require('dirty-chai'))
  66. null
  67. }`);
  68. });
  69. afterEach(closeAllWindows);
  70. return () => w;
  71. }
  72. describe('typeUtils serialization/deserialization', () => {
  73. it('serializes and deserializes an empty NativeImage', () => {
  74. const image = nativeImage.createEmpty();
  75. const serializedImage = serialize(image);
  76. const empty = deserialize(serializedImage);
  77. expect(empty.isEmpty()).to.be.true();
  78. expect(empty.getAspectRatio()).to.equal(1);
  79. expect(empty.toDataURL()).to.equal('data:image/png;base64,');
  80. expect(empty.toDataURL({ scaleFactor: 2.0 })).to.equal('data:image/png;base64,');
  81. expect(empty.getSize()).to.deep.equal({ width: 0, height: 0 });
  82. expect(empty.getBitmap()).to.be.empty();
  83. expect(empty.getBitmap({ scaleFactor: 2.0 })).to.be.empty();
  84. expect(empty.toBitmap()).to.be.empty();
  85. expect(empty.toBitmap({ scaleFactor: 2.0 })).to.be.empty();
  86. expect(empty.toJPEG(100)).to.be.empty();
  87. expect(empty.toPNG()).to.be.empty();
  88. expect(empty.toPNG({ scaleFactor: 2.0 })).to.be.empty();
  89. });
  90. it('serializes and deserializes a non-empty NativeImage', () => {
  91. const dataURL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==';
  92. const image = nativeImage.createFromDataURL(dataURL);
  93. const serializedImage = serialize(image);
  94. const nonEmpty = deserialize(serializedImage);
  95. expect(nonEmpty.isEmpty()).to.be.false();
  96. expect(nonEmpty.getAspectRatio()).to.equal(1);
  97. expect(nonEmpty.toDataURL()).to.not.be.empty();
  98. expect(nonEmpty.toBitmap({ scaleFactor: 1.0 })).to.deep.equal(image.toBitmap({ scaleFactor: 1.0 }));
  99. expect(nonEmpty.getSize()).to.deep.equal({ width: 2, height: 2 });
  100. expect(nonEmpty.getBitmap()).to.not.be.empty();
  101. expect(nonEmpty.toPNG()).to.not.be.empty();
  102. });
  103. it('serializes and deserializes a non-empty NativeImage with multiple representations', () => {
  104. const image = nativeImage.createEmpty();
  105. const dataURL1 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYlWNgAAIAAAUAAdafFs0AAAAASUVORK5CYII=';
  106. image.addRepresentation({ scaleFactor: 1.0, dataURL: dataURL1 });
  107. const dataURL2 = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==';
  108. image.addRepresentation({ scaleFactor: 2.0, dataURL: dataURL2 });
  109. const serializedImage = serialize(image);
  110. const nonEmpty = deserialize(serializedImage);
  111. expect(nonEmpty.isEmpty()).to.be.false();
  112. expect(nonEmpty.getAspectRatio()).to.equal(1);
  113. expect(nonEmpty.getSize()).to.deep.equal({ width: 1, height: 1 });
  114. expect(nonEmpty.getBitmap()).to.not.be.empty();
  115. expect(nonEmpty.getBitmap({ scaleFactor: 1.0 })).to.not.be.empty();
  116. expect(nonEmpty.getBitmap({ scaleFactor: 2.0 })).to.not.be.empty();
  117. expect(nonEmpty.toBitmap()).to.not.be.empty();
  118. expect(nonEmpty.toBitmap({ scaleFactor: 1.0 })).to.deep.equal(image.toBitmap({ scaleFactor: 1.0 }));
  119. expect(nonEmpty.toBitmap({ scaleFactor: 2.0 })).to.deep.equal(image.toBitmap({ scaleFactor: 2.0 }));
  120. expect(nonEmpty.toPNG()).to.not.be.empty();
  121. expect(nonEmpty.toPNG({ scaleFactor: 1.0 })).to.not.be.empty();
  122. expect(nonEmpty.toPNG({ scaleFactor: 2.0 })).to.not.be.empty();
  123. expect(nonEmpty.toDataURL()).to.not.be.empty();
  124. });
  125. it('serializes and deserializes an Array', () => {
  126. const array = [1, 2, 3, 4, 5];
  127. const serialized = serialize(array);
  128. const deserialized = deserialize(serialized);
  129. expect(deserialized).to.deep.equal(array);
  130. });
  131. it('serializes and deserializes a Buffer', () => {
  132. const buffer = Buffer.from('hello world!', 'utf-8');
  133. const serialized = serialize(buffer);
  134. const deserialized = deserialize(serialized);
  135. expect(deserialized).to.deep.equal(buffer);
  136. });
  137. it('serializes and deserializes a Boolean', () => {
  138. const bool = true;
  139. const serialized = serialize(bool);
  140. const deserialized = deserialize(serialized);
  141. expect(deserialized).to.equal(bool);
  142. });
  143. it('serializes and deserializes a Date', () => {
  144. const date = new Date();
  145. const serialized = serialize(date);
  146. const deserialized = deserialize(serialized);
  147. expect(deserialized).to.equal(date);
  148. });
  149. it('serializes and deserializes a Number', () => {
  150. const number = 42;
  151. const serialized = serialize(number);
  152. const deserialized = deserialize(serialized);
  153. expect(deserialized).to.equal(number);
  154. });
  155. it('serializes and deserializes a Regexp', () => {
  156. const regex = new RegExp('ab+c');
  157. const serialized = serialize(regex);
  158. const deserialized = deserialize(serialized);
  159. expect(deserialized).to.equal(regex);
  160. });
  161. it('serializes and deserializes a String', () => {
  162. const str = 'hello world';
  163. const serialized = serialize(str);
  164. const deserialized = deserialize(serialized);
  165. expect(deserialized).to.equal(str);
  166. });
  167. it('serializes and deserializes an Error', () => {
  168. const err = new Error('oh crap');
  169. const serialized = serialize(err);
  170. const deserialized = deserialize(serialized);
  171. expect(deserialized).to.equal(err);
  172. });
  173. it('serializes and deserializes a simple Object', () => {
  174. const obj = { hello: 'world', 'answer-to-everything': 42 };
  175. const serialized = serialize(obj);
  176. const deserialized = deserialize(serialized);
  177. expect(deserialized).to.deep.equal(obj);
  178. });
  179. });
  180. ifdescribe(features.isRemoteModuleEnabled())('remote module', () => {
  181. const fixtures = path.join(__dirname, 'fixtures');
  182. describe('', () => {
  183. const w = makeWindow();
  184. const remotely = makeRemotely(w);
  185. describe('remote.getGlobal filtering', () => {
  186. it('can return custom values', async () => {
  187. w().webContents.once('remote-get-global', (event, name) => {
  188. event.returnValue = name;
  189. });
  190. expect(await remotely(() => require('electron').remote.getGlobal('test'))).to.equal('test');
  191. });
  192. it('throws when no returnValue set', async () => {
  193. w().webContents.once('remote-get-global', (event) => {
  194. event.preventDefault();
  195. });
  196. await expect(remotely(() => require('electron').remote.getGlobal('test'))).to.eventually.be.rejected(`Blocked remote.getGlobal('test')`);
  197. });
  198. });
  199. describe('remote.getBuiltin filtering', () => {
  200. it('can return custom values', async () => {
  201. w().webContents.once('remote-get-builtin', (event, name) => {
  202. event.returnValue = name;
  203. });
  204. expect(await remotely(() => (require('electron').remote as any).getBuiltin('test'))).to.equal('test');
  205. });
  206. it('throws when no returnValue set', async () => {
  207. w().webContents.once('remote-get-builtin', (event) => {
  208. event.preventDefault();
  209. });
  210. await expect(remotely(() => (require('electron').remote as any).getBuiltin('test'))).to.eventually.be.rejected(`Blocked remote.getGlobal('test')`);
  211. });
  212. });
  213. describe('remote.require filtering', () => {
  214. it('can return custom values', async () => {
  215. w().webContents.once('remote-require', (event, name) => {
  216. event.returnValue = name;
  217. });
  218. expect(await remotely(() => require('electron').remote.require('test'))).to.equal('test');
  219. });
  220. it('throws when no returnValue set', async () => {
  221. w().webContents.once('remote-require', (event) => {
  222. event.preventDefault();
  223. });
  224. await expect(remotely(() => require('electron').remote.require('test'))).to.eventually.be.rejected(`Blocked remote.require('test')`);
  225. });
  226. });
  227. describe('remote.getCurrentWindow filtering', () => {
  228. it('can return custom value', async () => {
  229. w().webContents.once('remote-get-current-window', (e) => {
  230. e.returnValue = 'some window';
  231. });
  232. expect(await remotely(() => require('electron').remote.getCurrentWindow())).to.equal('some window');
  233. });
  234. it('throws when no returnValue set', async () => {
  235. w().webContents.once('remote-get-current-window', (event) => {
  236. event.preventDefault();
  237. });
  238. await expect(remotely(() => require('electron').remote.getCurrentWindow())).to.eventually.be.rejected(`Blocked remote.getCurrentWindow()`);
  239. });
  240. });
  241. describe('remote.getCurrentWebContents filtering', () => {
  242. it('can return custom value', async () => {
  243. w().webContents.once('remote-get-current-web-contents', (event) => {
  244. event.returnValue = 'some web contents';
  245. });
  246. expect(await remotely(() => require('electron').remote.getCurrentWebContents())).to.equal('some web contents');
  247. });
  248. it('throws when no returnValue set', async () => {
  249. w().webContents.once('remote-get-current-web-contents', (event) => {
  250. event.preventDefault();
  251. });
  252. await expect(remotely(() => require('electron').remote.getCurrentWebContents())).to.eventually.be.rejected(`Blocked remote.getCurrentWebContents()`);
  253. });
  254. });
  255. });
  256. describe('remote references', () => {
  257. const w = makeEachWindow();
  258. it('render-view-deleted is sent when page is destroyed', (done) => {
  259. w().webContents.once('render-view-deleted' as any, () => {
  260. done();
  261. });
  262. w().destroy();
  263. });
  264. // The ELECTRON_BROWSER_CONTEXT_RELEASE message relies on this to work.
  265. it('message can be sent on exit when page is being navigated', async () => {
  266. after(() => { ipcMain.removeAllListeners('SENT_ON_EXIT'); });
  267. w().webContents.once('did-finish-load', () => {
  268. w().webContents.loadURL('about:blank');
  269. });
  270. w().loadFile(path.join(fixtures, 'api', 'send-on-exit.html'));
  271. await emittedOnce(ipcMain, 'SENT_ON_EXIT');
  272. });
  273. });
  274. describe('remote function in renderer', () => {
  275. afterEach(() => {
  276. ipcMain.removeAllListeners('done');
  277. });
  278. afterEach(closeAllWindows);
  279. it('works when created in preload script', async () => {
  280. const preload = path.join(fixtures, 'module', 'preload-remote-function.js');
  281. const w = new BrowserWindow({
  282. show: false,
  283. webPreferences: {
  284. preload
  285. }
  286. });
  287. w.loadURL('about:blank');
  288. await emittedOnce(ipcMain, 'done');
  289. });
  290. });
  291. describe('remote objects registry', () => {
  292. it('does not dereference until the render view is deleted (regression)', (done) => {
  293. const w = new BrowserWindow({
  294. show: false,
  295. webPreferences: {
  296. nodeIntegration: true
  297. }
  298. });
  299. ipcMain.once('error-message', (event, message) => {
  300. expect(message).to.match(/^Cannot call method 'getURL' on missing remote object/);
  301. done();
  302. });
  303. w.loadFile(path.join(fixtures, 'api', 'render-view-deleted.html'));
  304. });
  305. });
  306. describe('nativeImage serialization', () => {
  307. const w = makeWindow();
  308. const remotely = makeRemotely(w);
  309. it('can serialize an empty nativeImage from renderer to main', async () => {
  310. const getImageEmpty = (img: NativeImage) => img.isEmpty();
  311. w().webContents.once('remote-get-global', (event) => {
  312. event.returnValue = getImageEmpty;
  313. });
  314. await expect(remotely(() => {
  315. const emptyImage = require('electron').nativeImage.createEmpty();
  316. return require('electron').remote.getGlobal('someFunction')(emptyImage);
  317. })).to.eventually.be.true();
  318. });
  319. it('can serialize an empty nativeImage from main to renderer', async () => {
  320. w().webContents.once('remote-get-global', (event) => {
  321. const emptyImage = require('electron').nativeImage.createEmpty();
  322. event.returnValue = emptyImage;
  323. });
  324. await expect(remotely(() => {
  325. const image = require('electron').remote.getGlobal('someFunction');
  326. return image.isEmpty();
  327. })).to.eventually.be.true();
  328. });
  329. it('can serialize a non-empty nativeImage from renderer to main', async () => {
  330. const getImageSize = (img: NativeImage) => img.getSize();
  331. w().webContents.once('remote-get-global', (event) => {
  332. event.returnValue = getImageSize;
  333. });
  334. await expect(remotely(() => {
  335. const { nativeImage } = require('electron');
  336. const nonEmptyImage = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==');
  337. return require('electron').remote.getGlobal('someFunction')(nonEmptyImage);
  338. })).to.eventually.deep.equal({ width: 2, height: 2 });
  339. });
  340. it('can serialize a non-empty nativeImage from main to renderer', async () => {
  341. w().webContents.once('remote-get-global', (event) => {
  342. const nonEmptyImage = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==');
  343. event.returnValue = nonEmptyImage;
  344. });
  345. await expect(remotely(() => {
  346. const image = require('electron').remote.getGlobal('someFunction');
  347. return image.getSize();
  348. })).to.eventually.deep.equal({ width: 2, height: 2 });
  349. });
  350. it('can properly create a menu with an nativeImage icon in the renderer', async () => {
  351. await expect(remotely(() => {
  352. const { remote, nativeImage } = require('electron');
  353. remote.Menu.buildFromTemplate([
  354. {
  355. label: 'hello',
  356. icon: nativeImage.createEmpty()
  357. }
  358. ]);
  359. })).to.be.fulfilled();
  360. });
  361. });
  362. describe('remote listeners', () => {
  363. afterEach(closeAllWindows);
  364. it('detaches listeners subscribed to destroyed renderers, and shows a warning', async () => {
  365. const w = new BrowserWindow({
  366. show: false,
  367. webPreferences: {
  368. nodeIntegration: true
  369. }
  370. });
  371. await w.loadFile(path.join(fixtures, 'api', 'remote-event-handler.html'));
  372. w.webContents.reload();
  373. await emittedOnce(w.webContents, 'did-finish-load');
  374. const expectedMessage = [
  375. 'Attempting to call a function in a renderer window that has been closed or released.',
  376. 'Function provided here: remote-event-handler.html:11:33',
  377. 'Remote event names: remote-handler, other-remote-handler'
  378. ].join('\n');
  379. expect(w.webContents.listenerCount('remote-handler')).to.equal(2);
  380. let warnMessage: string | null = null;
  381. const originalWarn = console.warn;
  382. let warned: Function;
  383. const warnPromise = new Promise(resolve => {
  384. warned = resolve;
  385. });
  386. try {
  387. console.warn = (message: string) => {
  388. warnMessage = message;
  389. warned();
  390. };
  391. w.webContents.emit('remote-handler', { sender: w.webContents });
  392. await warnPromise;
  393. } finally {
  394. console.warn = originalWarn;
  395. }
  396. expect(w.webContents.listenerCount('remote-handler')).to.equal(1);
  397. expect(warnMessage).to.equal(expectedMessage);
  398. });
  399. });
  400. describe('remote.require', () => {
  401. const w = makeWindow();
  402. const remotely = makeRemotely(w);
  403. remotely.it()('should returns same object for the same module', () => {
  404. const { remote } = require('electron');
  405. const a = remote.require('electron');
  406. const b = remote.require('electron');
  407. expect(a).to.equal(b);
  408. });
  409. remotely.it(path.join(fixtures, 'module', 'id.js'))('should work when object contains id property', (module: string) => {
  410. const { id } = require('electron').remote.require(module);
  411. expect(id).to.equal(1127);
  412. });
  413. remotely.it(path.join(fixtures, 'module', 'no-prototype.js'))('should work when object has no prototype', (module: string) => {
  414. const a = require('electron').remote.require(module);
  415. expect(a.foo.constructor.name).to.equal('');
  416. expect(a.foo.bar).to.equal('baz');
  417. expect(a.foo.baz).to.equal(false);
  418. expect(a.bar).to.equal(1234);
  419. expect(a.anonymous.constructor.name).to.equal('');
  420. expect(a.getConstructorName(Object.create(null))).to.equal('');
  421. expect(a.getConstructorName(new (class {})())).to.equal('');
  422. });
  423. it('should search module from the user app', async () => {
  424. expectPathsEqual(
  425. path.normalize(await remotely(() => require('electron').remote.process.mainModule!.filename)),
  426. path.resolve(__dirname, 'index.js')
  427. );
  428. expectPathsEqual(
  429. path.normalize(await remotely(() => require('electron').remote.process.mainModule!.paths[0])),
  430. path.resolve(__dirname, 'node_modules')
  431. );
  432. });
  433. remotely.it(fixtures)('should work with function properties', (fixtures: string) => {
  434. const path = require('path');
  435. {
  436. const a = require('electron').remote.require(path.join(fixtures, 'module', 'export-function-with-properties.js'));
  437. expect(typeof a).to.equal('function');
  438. expect(a.bar).to.equal('baz');
  439. }
  440. {
  441. const a = require('electron').remote.require(path.join(fixtures, 'module', 'function-with-properties.js'));
  442. expect(typeof a).to.equal('object');
  443. expect(a.foo()).to.equal('hello');
  444. expect(a.foo.bar).to.equal('baz');
  445. expect(a.foo.nested.prop).to.equal('yes');
  446. expect(a.foo.method1()).to.equal('world');
  447. expect(a.foo.method1.prop1()).to.equal(123);
  448. }
  449. {
  450. const a = require('electron').remote.require(path.join(fixtures, 'module', 'function-with-missing-properties.js')).setup();
  451. expect(a.bar()).to.equal(true);
  452. expect(a.bar.baz).to.be.undefined();
  453. }
  454. });
  455. remotely.it(fixtures)('should work with static class members', (fixtures: string) => {
  456. const path = require('path');
  457. const a = require('electron').remote.require(path.join(fixtures, 'module', 'remote-static.js'));
  458. expect(typeof a.Foo).to.equal('function');
  459. expect(a.Foo.foo()).to.equal(3);
  460. expect(a.Foo.bar).to.equal('baz');
  461. expect(new a.Foo().baz()).to.equal(123);
  462. });
  463. remotely.it(fixtures)('includes the length of functions specified as arguments', (fixtures: string) => {
  464. const path = require('path');
  465. const a = require('electron').remote.require(path.join(fixtures, 'module', 'function-with-args.js'));
  466. /* eslint-disable @typescript-eslint/no-unused-vars */
  467. expect(a((a: any, b: any, c: any) => {})).to.equal(3);
  468. expect(a((a: any) => {})).to.equal(1);
  469. expect(a((...args: any[]) => {})).to.equal(0);
  470. /* eslint-enable @typescript-eslint/no-unused-vars */
  471. });
  472. remotely.it(fixtures)('handles circular references in arrays and objects', (fixtures: string) => {
  473. const path = require('path');
  474. const a = require('electron').remote.require(path.join(fixtures, 'module', 'circular.js'));
  475. let arrayA: any[] = ['foo'];
  476. const arrayB = [arrayA, 'bar'];
  477. arrayA.push(arrayB);
  478. expect(a.returnArgs(arrayA, arrayB)).to.deep.equal([
  479. ['foo', [null, 'bar']],
  480. [['foo', null], 'bar']
  481. ]);
  482. let objectA: any = { foo: 'bar' };
  483. const objectB = { baz: objectA };
  484. objectA.objectB = objectB;
  485. expect(a.returnArgs(objectA, objectB)).to.deep.equal([
  486. { foo: 'bar', objectB: { baz: null } },
  487. { baz: { foo: 'bar', objectB: null } }
  488. ]);
  489. arrayA = [1, 2, 3];
  490. expect(a.returnArgs({ foo: arrayA }, { bar: arrayA })).to.deep.equal([
  491. { foo: [1, 2, 3] },
  492. { bar: [1, 2, 3] }
  493. ]);
  494. objectA = { foo: 'bar' };
  495. expect(a.returnArgs({ foo: objectA }, { bar: objectA })).to.deep.equal([
  496. { foo: { foo: 'bar' } },
  497. { bar: { foo: 'bar' } }
  498. ]);
  499. arrayA = [];
  500. arrayA.push(arrayA);
  501. expect(a.returnArgs(arrayA)).to.deep.equal([
  502. [null]
  503. ]);
  504. objectA = {};
  505. objectA.foo = objectA;
  506. objectA.bar = 'baz';
  507. expect(a.returnArgs(objectA)).to.deep.equal([
  508. { foo: null, bar: 'baz' }
  509. ]);
  510. objectA = {};
  511. objectA.foo = { bar: objectA };
  512. objectA.bar = 'baz';
  513. expect(a.returnArgs(objectA)).to.deep.equal([
  514. { foo: { bar: null }, bar: 'baz' }
  515. ]);
  516. });
  517. });
  518. describe('remote.createFunctionWithReturnValue', () => {
  519. const remotely = makeRemotely(makeWindow());
  520. remotely.it(fixtures)('should be called in browser synchronously', async (fixtures: string) => {
  521. const { remote } = require('electron');
  522. const path = require('path');
  523. const buf = Buffer.from('test');
  524. const call = remote.require(path.join(fixtures, 'module', 'call.js'));
  525. const result = call.call((remote as any).createFunctionWithReturnValue(buf));
  526. expect(result).to.be.an.instanceOf(Uint8Array);
  527. });
  528. });
  529. describe('remote modules', () => {
  530. const remotely = makeRemotely(makeWindow());
  531. const mainModules = Object.keys(require('electron'));
  532. remotely.it(mainModules)('includes browser process modules as properties', (mainModules: string[]) => {
  533. const { remote } = require('electron');
  534. const remoteModules = mainModules.filter(name => (remote as any)[name]);
  535. expect(remoteModules).to.be.deep.equal(mainModules);
  536. });
  537. remotely.it(fixtures)('returns toString() of original function via toString()', (fixtures: string) => {
  538. const path = require('path');
  539. const { readText } = require('electron').remote.clipboard;
  540. expect(readText.toString().startsWith('function')).to.be.true();
  541. const { functionWithToStringProperty } = require('electron').remote.require(path.join(fixtures, 'module', 'to-string-non-function.js'));
  542. expect(functionWithToStringProperty.toString).to.equal('hello');
  543. });
  544. });
  545. describe('remote object in renderer', () => {
  546. const remotely = makeRemotely(makeWindow());
  547. remotely.it(fixtures)('can change its properties', (fixtures: string) => {
  548. const module = require('path').join(fixtures, 'module', 'property.js');
  549. const property = require('electron').remote.require(module);
  550. expect(property.property).to.equal(1127);
  551. property.property = null;
  552. expect(property.property).to.equal(null);
  553. property.property = undefined;
  554. expect(property.property).to.equal(undefined);
  555. property.property = 1007;
  556. expect(property.property).to.equal(1007);
  557. expect(property.getFunctionProperty()).to.equal('foo-browser');
  558. property.func.property = 'bar';
  559. expect(property.getFunctionProperty()).to.equal('bar-browser');
  560. property.func.property = 'foo'; // revert back
  561. const property2 = require('electron').remote.require(module);
  562. expect(property2.property).to.equal(1007);
  563. property.property = 1127; // revert back
  564. });
  565. remotely.it(fixtures)('rethrows errors getting/setting properties', (fixtures: string) => {
  566. const foo = require('electron').remote.require(require('path').join(fixtures, 'module', 'error-properties.js'));
  567. expect(() => {
  568. // eslint-disable-next-line
  569. foo.bar
  570. }).to.throw('getting error');
  571. expect(() => {
  572. foo.bar = 'test';
  573. }).to.throw('setting error');
  574. });
  575. remotely.it(fixtures)('can set a remote property with a remote object', (fixtures: string) => {
  576. const { remote } = require('electron');
  577. const foo = remote.require(require('path').join(fixtures, 'module', 'remote-object-set.js'));
  578. foo.bar = remote.getCurrentWindow();
  579. });
  580. remotely.it(fixtures)('can construct an object from its member', (fixtures: string) => {
  581. const call = require('electron').remote.require(require('path').join(fixtures, 'module', 'call.js'));
  582. const obj = new call.constructor();
  583. expect(obj.test).to.equal('test');
  584. });
  585. remotely.it(fixtures)('can reassign and delete its member functions', (fixtures: string) => {
  586. const remoteFunctions = require('electron').remote.require(require('path').join(fixtures, 'module', 'function.js'));
  587. expect(remoteFunctions.aFunction()).to.equal(1127);
  588. remoteFunctions.aFunction = () => { return 1234; };
  589. expect(remoteFunctions.aFunction()).to.equal(1234);
  590. expect(delete remoteFunctions.aFunction).to.equal(true);
  591. });
  592. remotely.it('is referenced by its members', () => {
  593. const stringify = require('electron').remote.getGlobal('JSON').stringify;
  594. global.gc();
  595. stringify({});
  596. });
  597. });
  598. describe('remote value in browser', () => {
  599. const remotely = makeRemotely(makeWindow());
  600. const print = path.join(fixtures, 'module', 'print_name.js');
  601. remotely.it(print)('preserves NaN', (print: string) => {
  602. const printName = require('electron').remote.require(print);
  603. expect(printName.getNaN()).to.be.NaN();
  604. expect(printName.echo(NaN)).to.be.NaN();
  605. });
  606. remotely.it(print)('preserves Infinity', (print: string) => {
  607. const printName = require('electron').remote.require(print);
  608. expect(printName.getInfinity()).to.equal(Infinity);
  609. expect(printName.echo(Infinity)).to.equal(Infinity);
  610. });
  611. remotely.it(print)('keeps its constructor name for objects', (print: string) => {
  612. const printName = require('electron').remote.require(print);
  613. const buf = Buffer.from('test');
  614. expect(printName.print(buf)).to.equal('Buffer');
  615. });
  616. remotely.it(print)('supports instanceof Boolean', (print: string) => {
  617. const printName = require('electron').remote.require(print);
  618. const obj = Boolean(true);
  619. expect(printName.print(obj)).to.equal('Boolean');
  620. expect(printName.echo(obj)).to.deep.equal(obj);
  621. });
  622. remotely.it(print)('supports instanceof Number', (print: string) => {
  623. const printName = require('electron').remote.require(print);
  624. const obj = Number(42);
  625. expect(printName.print(obj)).to.equal('Number');
  626. expect(printName.echo(obj)).to.deep.equal(obj);
  627. });
  628. remotely.it(print)('supports instanceof String', (print: string) => {
  629. const printName = require('electron').remote.require(print);
  630. const obj = String('Hello World!');
  631. expect(printName.print(obj)).to.equal('String');
  632. expect(printName.echo(obj)).to.deep.equal(obj);
  633. });
  634. remotely.it(print)('supports instanceof Date', (print: string) => {
  635. const printName = require('electron').remote.require(print);
  636. const now = new Date();
  637. expect(printName.print(now)).to.equal('Date');
  638. expect(printName.echo(now)).to.deep.equal(now);
  639. });
  640. remotely.it(print)('supports instanceof RegExp', (print: string) => {
  641. const printName = require('electron').remote.require(print);
  642. const regexp = RegExp('.*');
  643. expect(printName.print(regexp)).to.equal('RegExp');
  644. expect(printName.echo(regexp)).to.deep.equal(regexp);
  645. });
  646. remotely.it(print)('supports instanceof Buffer', (print: string) => {
  647. const printName = require('electron').remote.require(print);
  648. const buffer = Buffer.from('test');
  649. expect(buffer.equals(printName.echo(buffer))).to.be.true();
  650. const objectWithBuffer = { a: 'foo', b: Buffer.from('bar') };
  651. expect(objectWithBuffer.b.equals(printName.echo(objectWithBuffer).b)).to.be.true();
  652. const arrayWithBuffer = [1, 2, Buffer.from('baz')];
  653. expect((arrayWithBuffer[2] as Buffer).equals(printName.echo(arrayWithBuffer)[2])).to.be.true();
  654. });
  655. remotely.it(print)('supports instanceof ArrayBuffer', (print: string) => {
  656. const printName = require('electron').remote.require(print);
  657. const buffer = new ArrayBuffer(8);
  658. const view = new DataView(buffer);
  659. view.setFloat64(0, Math.PI);
  660. expect(printName.echo(buffer)).to.deep.equal(buffer);
  661. expect(printName.print(buffer)).to.equal('ArrayBuffer');
  662. });
  663. const arrayTests: [string, number[]][] = [
  664. ['Int8Array', [1, 2, 3, 4]],
  665. ['Uint8Array', [1, 2, 3, 4]],
  666. ['Uint8ClampedArray', [1, 2, 3, 4]],
  667. ['Int16Array', [0x1234, 0x2345, 0x3456, 0x4567]],
  668. ['Uint16Array', [0x1234, 0x2345, 0x3456, 0x4567]],
  669. ['Int32Array', [0x12345678, 0x23456789]],
  670. ['Uint32Array', [0x12345678, 0x23456789]],
  671. ['Float32Array', [0.5, 1.0, 1.5]],
  672. ['Float64Array', [0.5, 1.0, 1.5]]
  673. ];
  674. arrayTests.forEach(([arrayType, values]) => {
  675. remotely.it(print, arrayType, values)(`supports instanceof ${arrayType}`, (print: string, arrayType: string, values: number[]) => {
  676. const printName = require('electron').remote.require(print);
  677. expect([...printName.typedArray(arrayType, values)]).to.deep.equal(values);
  678. const int8values = new ((window as any)[arrayType])(values);
  679. expect(printName.typedArray(arrayType, int8values)).to.deep.equal(int8values);
  680. expect(printName.print(int8values)).to.equal(arrayType);
  681. });
  682. });
  683. describe('constructing a Uint8Array', () => {
  684. remotely.it()('does not crash', () => {
  685. const RUint8Array = require('electron').remote.getGlobal('Uint8Array');
  686. new RUint8Array() // eslint-disable-line
  687. });
  688. });
  689. });
  690. describe('remote promise', () => {
  691. const remotely = makeRemotely(makeWindow());
  692. remotely.it(fixtures)('can be used as promise in each side', async (fixtures: string) => {
  693. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'promise.js'));
  694. const value = await promise.twicePromise(Promise.resolve(1234));
  695. expect(value).to.equal(2468);
  696. });
  697. remotely.it(fixtures)('handles rejections via catch(onRejected)', async (fixtures: string) => {
  698. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'rejected-promise.js'));
  699. const error = await new Promise<Error>(resolve => {
  700. promise.reject(Promise.resolve(1234)).catch(resolve);
  701. });
  702. expect(error.message).to.equal('rejected');
  703. });
  704. remotely.it(fixtures)('handles rejections via then(onFulfilled, onRejected)', async (fixtures: string) => {
  705. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'rejected-promise.js'));
  706. const error = await new Promise<Error>(resolve => {
  707. promise.reject(Promise.resolve(1234)).then(() => {}, resolve);
  708. });
  709. expect(error.message).to.equal('rejected');
  710. });
  711. it('does not emit unhandled rejection events in the main process', (done) => {
  712. function onUnhandledRejection () {
  713. done(new Error('Unexpected unhandledRejection event'));
  714. }
  715. process.once('unhandledRejection', onUnhandledRejection);
  716. remotely(async (fixtures: string) => {
  717. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'unhandled-rejection.js'));
  718. return new Promise((resolve, reject) => {
  719. promise.reject().then(() => {
  720. reject(new Error('Promise was not rejected'));
  721. }).catch((error: Error) => {
  722. resolve(error);
  723. });
  724. });
  725. }, fixtures).then(error => {
  726. try {
  727. expect(error.message).to.equal('rejected');
  728. done();
  729. } catch (e) {
  730. done(e);
  731. } finally {
  732. process.off('unhandledRejection', onUnhandledRejection);
  733. }
  734. });
  735. });
  736. it('emits unhandled rejection events in the renderer process', (done) => {
  737. remotely((module: string) => new Promise((resolve, reject) => {
  738. const promise = require('electron').remote.require(module);
  739. window.addEventListener('unhandledrejection', function handler (event) {
  740. event.preventDefault();
  741. window.removeEventListener('unhandledrejection', handler);
  742. resolve(event.reason.message);
  743. });
  744. promise.reject().then(() => {
  745. reject(new Error('Promise was not rejected'));
  746. });
  747. }), path.join(fixtures, 'module', 'unhandled-rejection.js')).then(
  748. (message) => {
  749. try {
  750. expect(message).to.equal('rejected');
  751. done();
  752. } catch (e) {
  753. done(e);
  754. }
  755. },
  756. done
  757. );
  758. });
  759. before(() => {
  760. (global as any).returnAPromise = (value: any) => new Promise((resolve) => setTimeout(() => resolve(value), 100));
  761. });
  762. after(() => {
  763. delete (global as any).returnAPromise;
  764. });
  765. remotely.it()('using a promise based method resolves correctly when global Promise is overridden', async () => {
  766. const { remote } = require('electron');
  767. const original = global.Promise;
  768. try {
  769. expect(await remote.getGlobal('returnAPromise')(123)).to.equal(123);
  770. global.Promise = { resolve: () => ({}) } as any;
  771. expect(await remote.getGlobal('returnAPromise')(456)).to.equal(456);
  772. } finally {
  773. global.Promise = original;
  774. }
  775. });
  776. });
  777. describe('remote webContents', () => {
  778. const remotely = makeRemotely(makeWindow());
  779. it('can return same object with different getters', async () => {
  780. const equal = await remotely(() => {
  781. const { remote } = require('electron');
  782. const contents1 = remote.getCurrentWindow().webContents;
  783. const contents2 = remote.getCurrentWebContents();
  784. return contents1 === contents2;
  785. });
  786. expect(equal).to.be.true();
  787. });
  788. });
  789. describe('remote class', () => {
  790. const remotely = makeRemotely(makeWindow());
  791. remotely.it(fixtures)('can get methods', (fixtures: string) => {
  792. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  793. expect(base.method()).to.equal('method');
  794. });
  795. remotely.it(fixtures)('can get properties', (fixtures: string) => {
  796. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  797. expect(base.readonly).to.equal('readonly');
  798. });
  799. remotely.it(fixtures)('can change properties', (fixtures: string) => {
  800. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  801. expect(base.value).to.equal('old');
  802. base.value = 'new';
  803. expect(base.value).to.equal('new');
  804. base.value = 'old';
  805. });
  806. remotely.it(fixtures)('has unenumerable methods', (fixtures: string) => {
  807. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  808. expect(base).to.not.have.ownProperty('method');
  809. expect(Object.getPrototypeOf(base)).to.have.ownProperty('method');
  810. });
  811. remotely.it(fixtures)('keeps prototype chain in derived class', (fixtures: string) => {
  812. const { derived } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  813. expect(derived.method()).to.equal('method');
  814. expect(derived.readonly).to.equal('readonly');
  815. expect(derived).to.not.have.ownProperty('method');
  816. const proto = Object.getPrototypeOf(derived);
  817. expect(proto).to.not.have.ownProperty('method');
  818. expect(Object.getPrototypeOf(proto)).to.have.ownProperty('method');
  819. });
  820. remotely.it(fixtures)('is referenced by methods in prototype chain', (fixtures: string) => {
  821. let { derived } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  822. const method = derived.method;
  823. derived = null;
  824. global.gc();
  825. expect(method()).to.equal('method');
  826. });
  827. });
  828. describe('remote exception', () => {
  829. const remotely = makeRemotely(makeWindow());
  830. remotely.it(fixtures)('throws errors from the main process', (fixtures: string) => {
  831. const throwFunction = require('electron').remote.require(require('path').join(fixtures, 'module', 'exception.js'));
  832. expect(() => {
  833. throwFunction();
  834. }).to.throw(/undefined/);
  835. });
  836. remotely.it(fixtures)('tracks error cause', (fixtures: string) => {
  837. const throwFunction = require('electron').remote.require(require('path').join(fixtures, 'module', 'exception.js'));
  838. try {
  839. throwFunction(new Error('error from main'));
  840. expect.fail();
  841. } catch (e) {
  842. expect(e.message).to.match(/Could not call remote function/);
  843. expect(e.cause.message).to.equal('error from main');
  844. }
  845. });
  846. });
  847. });