api-remote-spec.ts 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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 { protocol, nativeImage } from 'electron';
  10. const features = process._linkedBinding('electron_common_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. const protocolKeys = Object.getOwnPropertyNames(protocol);
  547. remotely.it(protocolKeys)('remote.protocol returns all keys', (protocolKeys: [string]) => {
  548. const protocol = require('electron').remote.protocol;
  549. const remoteKeys = Object.getOwnPropertyNames(protocol);
  550. expect(remoteKeys).to.deep.equal(protocolKeys);
  551. for (const key of remoteKeys) {
  552. expect(typeof (protocol as any)[key]).to.equal('function');
  553. }
  554. });
  555. });
  556. describe('remote object in renderer', () => {
  557. const win = makeWindow();
  558. const remotely = makeRemotely(win);
  559. remotely.it(fixtures)('can change its properties', (fixtures: string) => {
  560. const module = require('path').join(fixtures, 'module', 'property.js');
  561. const property = require('electron').remote.require(module);
  562. expect(property.property).to.equal(1127);
  563. property.property = null;
  564. expect(property.property).to.equal(null);
  565. property.property = undefined;
  566. expect(property.property).to.equal(undefined);
  567. property.property = 1007;
  568. expect(property.property).to.equal(1007);
  569. expect(property.getFunctionProperty()).to.equal('foo-browser');
  570. property.func.property = 'bar';
  571. expect(property.getFunctionProperty()).to.equal('bar-browser');
  572. property.func.property = 'foo'; // revert back
  573. const property2 = require('electron').remote.require(module);
  574. expect(property2.property).to.equal(1007);
  575. property.property = 1127; // revert back
  576. });
  577. remotely.it(fixtures)('rethrows errors getting/setting properties', (fixtures: string) => {
  578. const foo = require('electron').remote.require(require('path').join(fixtures, 'module', 'error-properties.js'));
  579. expect(() => {
  580. // eslint-disable-next-line
  581. foo.bar
  582. }).to.throw('getting error');
  583. expect(() => {
  584. foo.bar = 'test';
  585. }).to.throw('setting error');
  586. });
  587. remotely.it(fixtures)('can set a remote property with a remote object', (fixtures: string) => {
  588. const { remote } = require('electron');
  589. const foo = remote.require(require('path').join(fixtures, 'module', 'remote-object-set.js'));
  590. foo.bar = remote.getCurrentWindow();
  591. });
  592. remotely.it(fixtures)('can construct an object from its member', (fixtures: string) => {
  593. const call = require('electron').remote.require(require('path').join(fixtures, 'module', 'call.js'));
  594. const obj = new call.constructor();
  595. expect(obj.test).to.equal('test');
  596. });
  597. remotely.it(fixtures)('can reassign and delete its member functions', (fixtures: string) => {
  598. const remoteFunctions = require('electron').remote.require(require('path').join(fixtures, 'module', 'function.js'));
  599. expect(remoteFunctions.aFunction()).to.equal(1127);
  600. remoteFunctions.aFunction = () => { return 1234; };
  601. expect(remoteFunctions.aFunction()).to.equal(1234);
  602. expect(delete remoteFunctions.aFunction).to.equal(true);
  603. });
  604. remotely.it('is referenced by its members', () => {
  605. const stringify = require('electron').remote.getGlobal('JSON').stringify;
  606. global.gc();
  607. stringify({});
  608. });
  609. it('can handle objects without constructors', async () => {
  610. win().webContents.once('remote-get-global', (event) => {
  611. class Foo { bar () { return 'bar'; } }
  612. Foo.prototype.constructor = undefined as any;
  613. event.returnValue = new Foo();
  614. });
  615. expect(await remotely(() => require('electron').remote.getGlobal('test').bar())).to.equal('bar');
  616. });
  617. });
  618. describe('remote value in browser', () => {
  619. const remotely = makeRemotely(makeWindow());
  620. const print = path.join(fixtures, 'module', 'print_name.js');
  621. remotely.it(print)('preserves NaN', (print: string) => {
  622. const printName = require('electron').remote.require(print);
  623. expect(printName.getNaN()).to.be.NaN();
  624. expect(printName.echo(NaN)).to.be.NaN();
  625. });
  626. remotely.it(print)('preserves Infinity', (print: string) => {
  627. const printName = require('electron').remote.require(print);
  628. expect(printName.getInfinity()).to.equal(Infinity);
  629. expect(printName.echo(Infinity)).to.equal(Infinity);
  630. });
  631. remotely.it(print)('keeps its constructor name for objects', (print: string) => {
  632. const printName = require('electron').remote.require(print);
  633. const buf = Buffer.from('test');
  634. expect(printName.print(buf)).to.equal('Buffer');
  635. });
  636. remotely.it(print)('supports instanceof Boolean', (print: string) => {
  637. const printName = require('electron').remote.require(print);
  638. const obj = Boolean(true);
  639. expect(printName.print(obj)).to.equal('Boolean');
  640. expect(printName.echo(obj)).to.deep.equal(obj);
  641. });
  642. remotely.it(print)('supports instanceof Number', (print: string) => {
  643. const printName = require('electron').remote.require(print);
  644. const obj = Number(42);
  645. expect(printName.print(obj)).to.equal('Number');
  646. expect(printName.echo(obj)).to.deep.equal(obj);
  647. });
  648. remotely.it(print)('supports instanceof String', (print: string) => {
  649. const printName = require('electron').remote.require(print);
  650. const obj = String('Hello World!');
  651. expect(printName.print(obj)).to.equal('String');
  652. expect(printName.echo(obj)).to.deep.equal(obj);
  653. });
  654. remotely.it(print)('supports instanceof Date', (print: string) => {
  655. const printName = require('electron').remote.require(print);
  656. const now = new Date();
  657. expect(printName.print(now)).to.equal('Date');
  658. expect(printName.echo(now)).to.deep.equal(now);
  659. });
  660. remotely.it(print)('supports instanceof RegExp', (print: string) => {
  661. const printName = require('electron').remote.require(print);
  662. const regexp = RegExp('.*');
  663. expect(printName.print(regexp)).to.equal('RegExp');
  664. expect(printName.echo(regexp)).to.deep.equal(regexp);
  665. });
  666. remotely.it(print)('supports instanceof Buffer', (print: string) => {
  667. const printName = require('electron').remote.require(print);
  668. const buffer = Buffer.from('test');
  669. expect(buffer.equals(printName.echo(buffer))).to.be.true();
  670. const objectWithBuffer = { a: 'foo', b: Buffer.from('bar') };
  671. expect(objectWithBuffer.b.equals(printName.echo(objectWithBuffer).b)).to.be.true();
  672. const arrayWithBuffer = [1, 2, Buffer.from('baz')];
  673. expect((arrayWithBuffer[2] as Buffer).equals(printName.echo(arrayWithBuffer)[2])).to.be.true();
  674. });
  675. remotely.it(print)('supports instanceof ArrayBuffer', (print: string) => {
  676. const printName = require('electron').remote.require(print);
  677. const buffer = new ArrayBuffer(8);
  678. const view = new DataView(buffer);
  679. view.setFloat64(0, Math.PI);
  680. expect(printName.echo(buffer)).to.deep.equal(buffer);
  681. expect(printName.print(buffer)).to.equal('ArrayBuffer');
  682. });
  683. const arrayTests: [string, number[]][] = [
  684. ['Int8Array', [1, 2, 3, 4]],
  685. ['Uint8Array', [1, 2, 3, 4]],
  686. ['Uint8ClampedArray', [1, 2, 3, 4]],
  687. ['Int16Array', [0x1234, 0x2345, 0x3456, 0x4567]],
  688. ['Uint16Array', [0x1234, 0x2345, 0x3456, 0x4567]],
  689. ['Int32Array', [0x12345678, 0x23456789]],
  690. ['Uint32Array', [0x12345678, 0x23456789]],
  691. ['Float32Array', [0.5, 1.0, 1.5]],
  692. ['Float64Array', [0.5, 1.0, 1.5]]
  693. ];
  694. arrayTests.forEach(([arrayType, values]) => {
  695. remotely.it(print, arrayType, values)(`supports instanceof ${arrayType}`, (print: string, arrayType: string, values: number[]) => {
  696. const printName = require('electron').remote.require(print);
  697. expect([...printName.typedArray(arrayType, values)]).to.deep.equal(values);
  698. const int8values = new ((window as any)[arrayType])(values);
  699. expect(printName.typedArray(arrayType, int8values)).to.deep.equal(int8values);
  700. expect(printName.print(int8values)).to.equal(arrayType);
  701. });
  702. });
  703. describe('constructing a Uint8Array', () => {
  704. remotely.it()('does not crash', () => {
  705. const RUint8Array = require('electron').remote.getGlobal('Uint8Array');
  706. new RUint8Array() // eslint-disable-line
  707. });
  708. });
  709. });
  710. describe('remote promise', () => {
  711. const remotely = makeRemotely(makeWindow());
  712. remotely.it(fixtures)('can be used as promise in each side', async (fixtures: string) => {
  713. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'promise.js'));
  714. const value = await promise.twicePromise(Promise.resolve(1234));
  715. expect(value).to.equal(2468);
  716. });
  717. remotely.it(fixtures)('handles rejections via catch(onRejected)', async (fixtures: string) => {
  718. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'rejected-promise.js'));
  719. const error = await new Promise<Error>(resolve => {
  720. promise.reject(Promise.resolve(1234)).catch(resolve);
  721. });
  722. expect(error.message).to.equal('rejected');
  723. });
  724. remotely.it(fixtures)('handles rejections via then(onFulfilled, onRejected)', async (fixtures: string) => {
  725. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'rejected-promise.js'));
  726. const error = await new Promise<Error>(resolve => {
  727. promise.reject(Promise.resolve(1234)).then(() => {}, resolve);
  728. });
  729. expect(error.message).to.equal('rejected');
  730. });
  731. it('does not emit unhandled rejection events in the main process', (done) => {
  732. function onUnhandledRejection () {
  733. done(new Error('Unexpected unhandledRejection event'));
  734. }
  735. process.once('unhandledRejection', onUnhandledRejection);
  736. remotely(async (fixtures: string) => {
  737. const promise = require('electron').remote.require(require('path').join(fixtures, 'module', 'unhandled-rejection.js'));
  738. return new Promise((resolve, reject) => {
  739. promise.reject().then(() => {
  740. reject(new Error('Promise was not rejected'));
  741. }).catch((error: Error) => {
  742. resolve(error);
  743. });
  744. });
  745. }, fixtures).then(error => {
  746. try {
  747. expect(error.message).to.equal('rejected');
  748. done();
  749. } catch (e) {
  750. done(e);
  751. } finally {
  752. process.off('unhandledRejection', onUnhandledRejection);
  753. }
  754. });
  755. });
  756. it('emits unhandled rejection events in the renderer process', (done) => {
  757. remotely((module: string) => new Promise((resolve, reject) => {
  758. const promise = require('electron').remote.require(module);
  759. window.addEventListener('unhandledrejection', function handler (event) {
  760. event.preventDefault();
  761. window.removeEventListener('unhandledrejection', handler);
  762. resolve(event.reason.message);
  763. });
  764. promise.reject().then(() => {
  765. reject(new Error('Promise was not rejected'));
  766. });
  767. }), path.join(fixtures, 'module', 'unhandled-rejection.js')).then(
  768. (message) => {
  769. try {
  770. expect(message).to.equal('rejected');
  771. done();
  772. } catch (e) {
  773. done(e);
  774. }
  775. },
  776. done
  777. );
  778. });
  779. before(() => {
  780. (global as any).returnAPromise = (value: any) => new Promise((resolve) => setTimeout(() => resolve(value), 100));
  781. });
  782. after(() => {
  783. delete (global as any).returnAPromise;
  784. });
  785. remotely.it()('using a promise based method resolves correctly when global Promise is overridden', async () => {
  786. const { remote } = require('electron');
  787. const original = global.Promise;
  788. try {
  789. expect(await remote.getGlobal('returnAPromise')(123)).to.equal(123);
  790. global.Promise = { resolve: () => ({}) } as any;
  791. expect(await remote.getGlobal('returnAPromise')(456)).to.equal(456);
  792. } finally {
  793. global.Promise = original;
  794. }
  795. });
  796. });
  797. describe('remote webContents', () => {
  798. const remotely = makeRemotely(makeWindow());
  799. it('can return same object with different getters', async () => {
  800. const equal = await remotely(() => {
  801. const { remote } = require('electron');
  802. const contents1 = remote.getCurrentWindow().webContents;
  803. const contents2 = remote.getCurrentWebContents();
  804. return contents1 === contents2;
  805. });
  806. expect(equal).to.be.true();
  807. });
  808. });
  809. describe('remote class', () => {
  810. const remotely = makeRemotely(makeWindow());
  811. remotely.it(fixtures)('can get methods', (fixtures: string) => {
  812. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  813. expect(base.method()).to.equal('method');
  814. });
  815. remotely.it(fixtures)('can get properties', (fixtures: string) => {
  816. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  817. expect(base.readonly).to.equal('readonly');
  818. });
  819. remotely.it(fixtures)('can change properties', (fixtures: string) => {
  820. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  821. expect(base.value).to.equal('old');
  822. base.value = 'new';
  823. expect(base.value).to.equal('new');
  824. base.value = 'old';
  825. });
  826. remotely.it(fixtures)('has unenumerable methods', (fixtures: string) => {
  827. const { base } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  828. expect(base).to.not.have.ownProperty('method');
  829. expect(Object.getPrototypeOf(base)).to.have.ownProperty('method');
  830. });
  831. remotely.it(fixtures)('keeps prototype chain in derived class', (fixtures: string) => {
  832. const { derived } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  833. expect(derived.method()).to.equal('method');
  834. expect(derived.readonly).to.equal('readonly');
  835. expect(derived).to.not.have.ownProperty('method');
  836. const proto = Object.getPrototypeOf(derived);
  837. expect(proto).to.not.have.ownProperty('method');
  838. expect(Object.getPrototypeOf(proto)).to.have.ownProperty('method');
  839. });
  840. remotely.it(fixtures)('is referenced by methods in prototype chain', (fixtures: string) => {
  841. let { derived } = require('electron').remote.require(require('path').join(fixtures, 'module', 'class.js'));
  842. const method = derived.method;
  843. derived = null;
  844. global.gc();
  845. expect(method()).to.equal('method');
  846. });
  847. });
  848. describe('remote exception', () => {
  849. const remotely = makeRemotely(makeWindow());
  850. remotely.it(fixtures)('throws errors from the main process', (fixtures: string) => {
  851. const throwFunction = require('electron').remote.require(require('path').join(fixtures, 'module', 'exception.js'));
  852. expect(() => {
  853. throwFunction();
  854. }).to.throw(/undefined/);
  855. });
  856. remotely.it(fixtures)('tracks error cause', (fixtures: string) => {
  857. const throwFunction = require('electron').remote.require(require('path').join(fixtures, 'module', 'exception.js'));
  858. try {
  859. throwFunction(new Error('error from main'));
  860. expect.fail();
  861. } catch (e) {
  862. expect(e.message).to.match(/Could not call remote function/);
  863. expect(e.cause.message).to.equal('error from main');
  864. }
  865. });
  866. });
  867. describe('gc behavior', () => {
  868. const win = makeWindow();
  869. const remotely = makeRemotely(win);
  870. it('is resilient to gc happening between request and response', async () => {
  871. const obj = { x: 'y' };
  872. win().webContents.on('remote-get-global', (event) => {
  873. event.returnValue = obj;
  874. });
  875. await remotely(() => {
  876. const { ipc } = process._linkedBinding('electron_renderer_ipc');
  877. const originalSendSync = ipc.sendSync.bind(ipc) as any;
  878. ipc.sendSync = (...args: any[]): any => {
  879. const ret = originalSendSync(...args);
  880. (window as any).gc();
  881. return ret;
  882. };
  883. for (let i = 0; i < 100; i++) {
  884. // eslint-disable-next-line
  885. require('electron').remote.getGlobal('test').x;
  886. }
  887. });
  888. });
  889. });
  890. });