api-remote-spec.ts 38 KB

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