api-remote-spec.ts 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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, contextIsolation: false } });
  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, contextIsolation: false } });
  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', 'remote');
  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, '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, 'preload-remote-function.js');
  283. const w = new BrowserWindow({
  284. show: false,
  285. webPreferences: {
  286. preload,
  287. enableRemoteModule: true,
  288. contextIsolation: false
  289. }
  290. });
  291. w.loadURL('about:blank');
  292. await emittedOnce(ipcMain, 'done');
  293. });
  294. });
  295. describe('remote objects registry', () => {
  296. it('does not dereference until the render view is deleted (regression)', async () => {
  297. const w = new BrowserWindow({
  298. show: false,
  299. webPreferences: {
  300. nodeIntegration: true,
  301. enableRemoteModule: true,
  302. contextIsolation: false
  303. }
  304. });
  305. const message = emittedOnce(ipcMain, 'error-message');
  306. w.loadFile(path.join(fixtures, 'render-view-deleted.html'));
  307. const [, msg] = await message;
  308. expect(msg).to.match(/^Cannot call method 'getURL' on missing remote object/);
  309. });
  310. });
  311. describe('nativeImage serialization', () => {
  312. const w = makeWindow();
  313. const remotely = makeRemotely(w);
  314. it('can serialize an empty nativeImage from renderer to main', async () => {
  315. const getImageEmpty = (img: NativeImage) => img.isEmpty();
  316. w().webContents.once('remote-get-global', (event) => {
  317. event.returnValue = getImageEmpty;
  318. });
  319. await expect(remotely(() => {
  320. const emptyImage = require('electron').nativeImage.createEmpty();
  321. return require('electron').remote.getGlobal('someFunction')(emptyImage);
  322. })).to.eventually.be.true();
  323. });
  324. it('can serialize an empty nativeImage from main to renderer', async () => {
  325. w().webContents.once('remote-get-global', (event) => {
  326. const emptyImage = require('electron').nativeImage.createEmpty();
  327. event.returnValue = emptyImage;
  328. });
  329. await expect(remotely(() => {
  330. const image = require('electron').remote.getGlobal('someFunction');
  331. return image.isEmpty();
  332. })).to.eventually.be.true();
  333. });
  334. it('can serialize a non-empty nativeImage from renderer to main', async () => {
  335. const getImageSize = (img: NativeImage) => img.getSize();
  336. w().webContents.once('remote-get-global', (event) => {
  337. event.returnValue = getImageSize;
  338. });
  339. await expect(remotely(() => {
  340. const { nativeImage } = require('electron');
  341. const nonEmptyImage = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==');
  342. return require('electron').remote.getGlobal('someFunction')(nonEmptyImage);
  343. })).to.eventually.deep.equal({ width: 2, height: 2 });
  344. });
  345. it('can serialize a non-empty nativeImage from main to renderer', async () => {
  346. w().webContents.once('remote-get-global', (event) => {
  347. const nonEmptyImage = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQYlWP8//8/AwMDEwMDAwMDAwAkBgMBBMzldwAAAABJRU5ErkJggg==');
  348. event.returnValue = nonEmptyImage;
  349. });
  350. await expect(remotely(() => {
  351. const image = require('electron').remote.getGlobal('someFunction');
  352. return image.getSize();
  353. })).to.eventually.deep.equal({ width: 2, height: 2 });
  354. });
  355. it('can properly create a menu with an nativeImage icon in the renderer', async () => {
  356. await expect(remotely(() => {
  357. const { remote, nativeImage } = require('electron');
  358. remote.Menu.buildFromTemplate([
  359. {
  360. label: 'hello',
  361. icon: nativeImage.createEmpty()
  362. }
  363. ]);
  364. })).to.be.fulfilled();
  365. });
  366. });
  367. describe('remote listeners', () => {
  368. afterEach(closeAllWindows);
  369. it('detaches listeners subscribed to destroyed renderers, and shows a warning', async () => {
  370. const w = new BrowserWindow({
  371. show: false,
  372. webPreferences: {
  373. nodeIntegration: true,
  374. enableRemoteModule: true,
  375. contextIsolation: false
  376. }
  377. });
  378. await w.loadFile(path.join(fixtures, 'remote-event-handler.html'));
  379. w.webContents.reload();
  380. await emittedOnce(w.webContents, 'did-finish-load');
  381. const expectedMessage = [
  382. 'Attempting to call a function in a renderer window that has been closed or released.',
  383. 'Function provided here: remote-event-handler.html:11:33',
  384. 'Remote event names: remote-handler, other-remote-handler'
  385. ].join('\n');
  386. expect(w.webContents.listenerCount('remote-handler')).to.equal(2);
  387. let warnMessage: string | null = null;
  388. const originalWarn = console.warn;
  389. let warned: Function;
  390. const warnPromise = new Promise(resolve => {
  391. warned = resolve;
  392. });
  393. try {
  394. console.warn = (message: string) => {
  395. warnMessage = message;
  396. warned();
  397. };
  398. w.webContents.emit('remote-handler', { sender: w.webContents });
  399. await warnPromise;
  400. } finally {
  401. console.warn = originalWarn;
  402. }
  403. expect(w.webContents.listenerCount('remote-handler')).to.equal(1);
  404. expect(warnMessage).to.equal(expectedMessage);
  405. });
  406. });
  407. describe('remote.require', () => {
  408. const w = makeWindow();
  409. const remotely = makeRemotely(w);
  410. remotely.it()('should returns same object for the same module', () => {
  411. const { remote } = require('electron');
  412. const a = remote.require('electron');
  413. const b = remote.require('electron');
  414. expect(a).to.equal(b);
  415. });
  416. remotely.it(path.join(fixtures, 'id.js'))('should work when object contains id property', (module: string) => {
  417. const { id } = require('electron').remote.require(module);
  418. expect(id).to.equal(1127);
  419. });
  420. remotely.it(path.join(fixtures, 'no-prototype.js'))('should work when object has no prototype', (module: string) => {
  421. const a = require('electron').remote.require(module);
  422. expect(a.foo.bar).to.equal('baz');
  423. expect(a.foo.baz).to.equal(false);
  424. expect(a.bar).to.equal(1234);
  425. expect(a.getConstructorName(Object.create(null))).to.equal('');
  426. expect(a.getConstructorName(new (class {})())).to.equal('');
  427. });
  428. it('should search module from the user app', async () => {
  429. expectPathsEqual(
  430. path.normalize(await remotely(() => {
  431. const { remote } = require('electron');
  432. return (remote as any).process.mainModule.filename;
  433. })),
  434. path.resolve(__dirname, 'index.js')
  435. );
  436. expectPathsEqual(
  437. path.normalize(await remotely(() => {
  438. const { remote } = require('electron');
  439. return (remote as any).process.mainModule.paths[0];
  440. })),
  441. path.resolve(__dirname, 'node_modules')
  442. );
  443. });
  444. remotely.it(fixtures)('should work with function properties', (fixtures: string) => {
  445. const path = require('path');
  446. {
  447. const a = require('electron').remote.require(path.join(fixtures, 'export-function-with-properties.js'));
  448. expect(typeof a).to.equal('function');
  449. expect(a.bar).to.equal('baz');
  450. }
  451. {
  452. const a = require('electron').remote.require(path.join(fixtures, 'function-with-properties.js'));
  453. expect(typeof a).to.equal('object');
  454. expect(a.foo()).to.equal('hello');
  455. expect(a.foo.bar).to.equal('baz');
  456. expect(a.foo.nested.prop).to.equal('yes');
  457. expect(a.foo.method1()).to.equal('world');
  458. expect(a.foo.method1.prop1()).to.equal(123);
  459. }
  460. {
  461. const a = require('electron').remote.require(path.join(fixtures, 'function-with-missing-properties.js')).setup();
  462. expect(a.bar()).to.equal(true);
  463. expect(a.bar.baz).to.be.undefined();
  464. }
  465. });
  466. remotely.it(fixtures)('should work with static class members', (fixtures: string) => {
  467. const path = require('path');
  468. const a = require('electron').remote.require(path.join(fixtures, 'remote-static.js'));
  469. expect(typeof a.Foo).to.equal('function');
  470. expect(a.Foo.foo()).to.equal(3);
  471. expect(a.Foo.bar).to.equal('baz');
  472. expect(new a.Foo().baz()).to.equal(123);
  473. });
  474. remotely.it(fixtures)('includes the length of functions specified as arguments', (fixtures: string) => {
  475. const path = require('path');
  476. const a = require('electron').remote.require(path.join(fixtures, 'function-with-args.js'));
  477. /* eslint-disable @typescript-eslint/no-unused-vars */
  478. expect(a((a: any, b: any, c: any) => {})).to.equal(3);
  479. expect(a((a: any) => {})).to.equal(1);
  480. expect(a((...args: any[]) => {})).to.equal(0);
  481. /* eslint-enable @typescript-eslint/no-unused-vars */
  482. });
  483. remotely.it(fixtures)('handles circular references in arrays and objects', (fixtures: string) => {
  484. const path = require('path');
  485. const a = require('electron').remote.require(path.join(fixtures, 'circular.js'));
  486. let arrayA: any[] = ['foo'];
  487. const arrayB = [arrayA, 'bar'];
  488. arrayA.push(arrayB);
  489. expect(a.returnArgs(arrayA, arrayB)).to.deep.equal([
  490. ['foo', [null, 'bar']],
  491. [['foo', null], 'bar']
  492. ]);
  493. let objectA: any = { foo: 'bar' };
  494. const objectB = { baz: objectA };
  495. objectA.objectB = objectB;
  496. expect(a.returnArgs(objectA, objectB)).to.deep.equal([
  497. { foo: 'bar', objectB: { baz: null } },
  498. { baz: { foo: 'bar', objectB: null } }
  499. ]);
  500. arrayA = [1, 2, 3];
  501. expect(a.returnArgs({ foo: arrayA }, { bar: arrayA })).to.deep.equal([
  502. { foo: [1, 2, 3] },
  503. { bar: [1, 2, 3] }
  504. ]);
  505. objectA = { foo: 'bar' };
  506. expect(a.returnArgs({ foo: objectA }, { bar: objectA })).to.deep.equal([
  507. { foo: { foo: 'bar' } },
  508. { bar: { foo: 'bar' } }
  509. ]);
  510. arrayA = [];
  511. arrayA.push(arrayA);
  512. expect(a.returnArgs(arrayA)).to.deep.equal([
  513. [null]
  514. ]);
  515. objectA = {};
  516. objectA.foo = objectA;
  517. objectA.bar = 'baz';
  518. expect(a.returnArgs(objectA)).to.deep.equal([
  519. { foo: null, bar: 'baz' }
  520. ]);
  521. objectA = {};
  522. objectA.foo = { bar: objectA };
  523. objectA.bar = 'baz';
  524. expect(a.returnArgs(objectA)).to.deep.equal([
  525. { foo: { bar: null }, bar: 'baz' }
  526. ]);
  527. });
  528. });
  529. describe('remote.createFunctionWithReturnValue', () => {
  530. const remotely = makeRemotely(makeWindow());
  531. remotely.it(fixtures)('should be called in browser synchronously', async (fixtures: string) => {
  532. const { remote } = require('electron');
  533. const path = require('path');
  534. const buf = Buffer.from('test');
  535. const call = remote.require(path.join(fixtures, 'call.js'));
  536. const result = call.call((remote as any).createFunctionWithReturnValue(buf));
  537. expect(result).to.be.an.instanceOf(Uint8Array);
  538. });
  539. });
  540. describe('remote modules', () => {
  541. const remotely = makeRemotely(makeWindow());
  542. const mainModules = Object.keys(require('electron'));
  543. remotely.it(mainModules)('includes browser process modules as properties', (mainModules: string[]) => {
  544. const { remote } = require('electron');
  545. const remoteModules = mainModules.filter(name => (remote as any)[name]);
  546. expect(remoteModules).to.be.deep.equal(mainModules);
  547. });
  548. remotely.it(fixtures)('returns toString() of original function via toString()', (fixtures: string) => {
  549. const path = require('path');
  550. const { readText } = require('electron').remote.clipboard;
  551. expect(readText.toString().startsWith('function')).to.be.true();
  552. const { functionWithToStringProperty } = require('electron').remote.require(path.join(fixtures, 'to-string-non-function.js'));
  553. expect(functionWithToStringProperty.toString).to.equal('hello');
  554. });
  555. const protocolKeys = Object.getOwnPropertyNames(protocol);
  556. remotely.it(protocolKeys)('remote.protocol returns all keys', (protocolKeys: [string]) => {
  557. const protocol = require('electron').remote.protocol;
  558. const remoteKeys = Object.getOwnPropertyNames(protocol);
  559. expect(remoteKeys).to.deep.equal(protocolKeys);
  560. for (const key of remoteKeys) {
  561. expect(typeof (protocol as any)[key]).to.equal('function');
  562. }
  563. });
  564. });
  565. describe('remote object in renderer', () => {
  566. const win = makeWindow();
  567. const remotely = makeRemotely(win);
  568. remotely.it(fixtures)('can change its properties', (fixtures: string) => {
  569. const module = require('path').join(fixtures, 'property.js');
  570. const property = require('electron').remote.require(module);
  571. expect(property.property).to.equal(1127);
  572. property.property = null;
  573. expect(property.property).to.equal(null);
  574. property.property = undefined;
  575. expect(property.property).to.equal(undefined);
  576. property.property = 1007;
  577. expect(property.property).to.equal(1007);
  578. expect(property.getFunctionProperty()).to.equal('foo-browser');
  579. property.func.property = 'bar';
  580. expect(property.getFunctionProperty()).to.equal('bar-browser');
  581. property.func.property = 'foo'; // revert back
  582. const property2 = require('electron').remote.require(module);
  583. expect(property2.property).to.equal(1007);
  584. property.property = 1127; // revert back
  585. });
  586. remotely.it(fixtures)('rethrows errors getting/setting properties', (fixtures: string) => {
  587. const foo = require('electron').remote.require(require('path').join(fixtures, 'error-properties.js'));
  588. expect(() => {
  589. // eslint-disable-next-line
  590. foo.bar
  591. }).to.throw('getting error');
  592. expect(() => {
  593. foo.bar = 'test';
  594. }).to.throw('setting error');
  595. });
  596. remotely.it(fixtures)('can set a remote property with a remote object', (fixtures: string) => {
  597. const { remote } = require('electron');
  598. const foo = remote.require(require('path').join(fixtures, 'remote-object-set.js'));
  599. foo.bar = remote.getCurrentWindow();
  600. });
  601. remotely.it(fixtures)('can construct an object from its member', (fixtures: string) => {
  602. const call = require('electron').remote.require(require('path').join(fixtures, 'call.js'));
  603. const obj = new call.constructor();
  604. expect(obj.test).to.equal('test');
  605. });
  606. remotely.it(fixtures)('can reassign and delete its member functions', (fixtures: string) => {
  607. const remoteFunctions = require('electron').remote.require(require('path').join(fixtures, 'function.js'));
  608. expect(remoteFunctions.aFunction()).to.equal(1127);
  609. remoteFunctions.aFunction = () => { return 1234; };
  610. expect(remoteFunctions.aFunction()).to.equal(1234);
  611. expect(delete remoteFunctions.aFunction).to.equal(true);
  612. });
  613. remotely.it('is referenced by its members', () => {
  614. const stringify = require('electron').remote.getGlobal('JSON').stringify;
  615. global.gc();
  616. stringify({});
  617. });
  618. it('can handle objects without constructors', async () => {
  619. win().webContents.once('remote-get-global', (event) => {
  620. class Foo { bar () { return 'bar'; } }
  621. Foo.prototype.constructor = undefined as any;
  622. event.returnValue = new Foo();
  623. });
  624. expect(await remotely(() => require('electron').remote.getGlobal('test').bar())).to.equal('bar');
  625. });
  626. });
  627. describe('remote value in browser', () => {
  628. const remotely = makeRemotely(makeWindow());
  629. const print = path.join(fixtures, 'print_name.js');
  630. remotely.it(print)('preserves NaN', (print: string) => {
  631. const printName = require('electron').remote.require(print);
  632. expect(printName.getNaN()).to.be.NaN();
  633. expect(printName.echo(NaN)).to.be.NaN();
  634. });
  635. remotely.it(print)('preserves Infinity', (print: string) => {
  636. const printName = require('electron').remote.require(print);
  637. expect(printName.getInfinity()).to.equal(Infinity);
  638. expect(printName.echo(Infinity)).to.equal(Infinity);
  639. });
  640. remotely.it(print)('keeps its constructor name for objects', (print: string) => {
  641. const printName = require('electron').remote.require(print);
  642. const buf = Buffer.from('test');
  643. expect(printName.print(buf)).to.equal('Buffer');
  644. });
  645. remotely.it(print)('supports instanceof Boolean', (print: string) => {
  646. const printName = require('electron').remote.require(print);
  647. const obj = Boolean(true);
  648. expect(printName.print(obj)).to.equal('Boolean');
  649. expect(printName.echo(obj)).to.deep.equal(obj);
  650. });
  651. remotely.it(print)('supports instanceof Number', (print: string) => {
  652. const printName = require('electron').remote.require(print);
  653. const obj = Number(42);
  654. expect(printName.print(obj)).to.equal('Number');
  655. expect(printName.echo(obj)).to.deep.equal(obj);
  656. });
  657. remotely.it(print)('supports instanceof String', (print: string) => {
  658. const printName = require('electron').remote.require(print);
  659. const obj = String('Hello World!');
  660. expect(printName.print(obj)).to.equal('String');
  661. expect(printName.echo(obj)).to.deep.equal(obj);
  662. });
  663. remotely.it(print)('supports instanceof Date', (print: string) => {
  664. const printName = require('electron').remote.require(print);
  665. const now = new Date();
  666. expect(printName.print(now)).to.equal('Date');
  667. expect(printName.echo(now)).to.deep.equal(now);
  668. });
  669. remotely.it(print)('supports instanceof RegExp', (print: string) => {
  670. const printName = require('electron').remote.require(print);
  671. const regexp = RegExp('.*');
  672. expect(printName.print(regexp)).to.equal('RegExp');
  673. expect(printName.echo(regexp)).to.deep.equal(regexp);
  674. });
  675. remotely.it(print)('supports instanceof Buffer', (print: string) => {
  676. const printName = require('electron').remote.require(print);
  677. const buffer = Buffer.from('test');
  678. expect(buffer.equals(printName.echo(buffer))).to.be.true();
  679. const objectWithBuffer = { a: 'foo', b: Buffer.from('bar') };
  680. expect(objectWithBuffer.b.equals(printName.echo(objectWithBuffer).b)).to.be.true();
  681. const arrayWithBuffer = [1, 2, Buffer.from('baz')];
  682. expect((arrayWithBuffer[2] as Buffer).equals(printName.echo(arrayWithBuffer)[2])).to.be.true();
  683. });
  684. remotely.it(print)('supports instanceof ArrayBuffer', (print: string) => {
  685. const printName = require('electron').remote.require(print);
  686. const buffer = new ArrayBuffer(8);
  687. const view = new DataView(buffer);
  688. view.setFloat64(0, Math.PI);
  689. expect(printName.echo(buffer)).to.deep.equal(buffer);
  690. expect(printName.print(buffer)).to.equal('ArrayBuffer');
  691. });
  692. const arrayTests: [string, number[]][] = [
  693. ['Int8Array', [1, 2, 3, 4]],
  694. ['Uint8Array', [1, 2, 3, 4]],
  695. ['Uint8ClampedArray', [1, 2, 3, 4]],
  696. ['Int16Array', [0x1234, 0x2345, 0x3456, 0x4567]],
  697. ['Uint16Array', [0x1234, 0x2345, 0x3456, 0x4567]],
  698. ['Int32Array', [0x12345678, 0x23456789]],
  699. ['Uint32Array', [0x12345678, 0x23456789]],
  700. ['Float32Array', [0.5, 1.0, 1.5]],
  701. ['Float64Array', [0.5, 1.0, 1.5]]
  702. ];
  703. arrayTests.forEach(([arrayType, values]) => {
  704. remotely.it(print, arrayType, values)(`supports instanceof ${arrayType}`, (print: string, arrayType: string, values: number[]) => {
  705. const printName = require('electron').remote.require(print);
  706. expect([...printName.typedArray(arrayType, values)]).to.deep.equal(values);
  707. const int8values = new ((window as any)[arrayType])(values);
  708. expect(printName.typedArray(arrayType, int8values)).to.deep.equal(int8values);
  709. expect(printName.print(int8values)).to.equal(arrayType);
  710. });
  711. });
  712. describe('constructing a Uint8Array', () => {
  713. remotely.it()('does not crash', () => {
  714. const RUint8Array = require('electron').remote.getGlobal('Uint8Array');
  715. new RUint8Array() // eslint-disable-line
  716. });
  717. });
  718. });
  719. describe('remote promise', () => {
  720. const remotely = makeRemotely(makeWindow());
  721. remotely.it(fixtures)('can be used as promise in each side', async (fixtures: string) => {
  722. const promise = require('electron').remote.require(require('path').join(fixtures, 'promise.js'));
  723. const value = await promise.twicePromise(Promise.resolve(1234));
  724. expect(value).to.equal(2468);
  725. });
  726. remotely.it(fixtures)('handles rejections via catch(onRejected)', async (fixtures: string) => {
  727. const promise = require('electron').remote.require(require('path').join(fixtures, 'rejected-promise.js'));
  728. const error = await new Promise<Error>(resolve => {
  729. promise.reject(Promise.resolve(1234)).catch(resolve);
  730. });
  731. expect(error.message).to.equal('rejected');
  732. });
  733. remotely.it(fixtures)('handles rejections via then(onFulfilled, onRejected)', async (fixtures: string) => {
  734. const promise = require('electron').remote.require(require('path').join(fixtures, 'rejected-promise.js'));
  735. const error = await new Promise<Error>(resolve => {
  736. promise.reject(Promise.resolve(1234)).then(() => {}, resolve);
  737. });
  738. expect(error.message).to.equal('rejected');
  739. });
  740. it('does not emit unhandled rejection events in the main process', (done) => {
  741. function onUnhandledRejection () {
  742. done(new Error('Unexpected unhandledRejection event'));
  743. }
  744. process.once('unhandledRejection', onUnhandledRejection);
  745. remotely(async (fixtures: string) => {
  746. const promise = require('electron').remote.require(require('path').join(fixtures, 'unhandled-rejection.js'));
  747. return new Promise((resolve, reject) => {
  748. promise.reject().then(() => {
  749. reject(new Error('Promise was not rejected'));
  750. }).catch((error: Error) => {
  751. resolve(error);
  752. });
  753. });
  754. }, fixtures).then(error => {
  755. try {
  756. expect(error.message).to.equal('rejected');
  757. done();
  758. } catch (e) {
  759. done(e);
  760. } finally {
  761. process.off('unhandledRejection', onUnhandledRejection);
  762. }
  763. });
  764. });
  765. it('emits unhandled rejection events in the renderer process', (done) => {
  766. remotely((module: string) => new Promise((resolve, reject) => {
  767. const promise = require('electron').remote.require(module);
  768. window.addEventListener('unhandledrejection', function handler (event) {
  769. event.preventDefault();
  770. window.removeEventListener('unhandledrejection', handler);
  771. resolve(event.reason.message);
  772. });
  773. promise.reject().then(() => {
  774. reject(new Error('Promise was not rejected'));
  775. });
  776. }), path.join(fixtures, 'unhandled-rejection.js')).then(
  777. (message) => {
  778. try {
  779. expect(message).to.equal('rejected');
  780. done();
  781. } catch (e) {
  782. done(e);
  783. }
  784. },
  785. done
  786. );
  787. });
  788. before(() => {
  789. (global as any).returnAPromise = (value: any) => new Promise((resolve) => setTimeout(() => resolve(value), 100));
  790. });
  791. after(() => {
  792. delete (global as any).returnAPromise;
  793. });
  794. remotely.it()('using a promise based method resolves correctly when global Promise is overridden', async () => {
  795. const { remote } = require('electron');
  796. const original = global.Promise;
  797. try {
  798. expect(await remote.getGlobal('returnAPromise')(123)).to.equal(123);
  799. global.Promise = { resolve: () => ({}) } as any;
  800. expect(await remote.getGlobal('returnAPromise')(456)).to.equal(456);
  801. } finally {
  802. global.Promise = original;
  803. }
  804. });
  805. });
  806. describe('remote webContents', () => {
  807. const remotely = makeRemotely(makeWindow());
  808. it('can return same object with different getters', async () => {
  809. const equal = await remotely(() => {
  810. const { remote } = require('electron');
  811. const contents1 = remote.getCurrentWindow().webContents;
  812. const contents2 = remote.getCurrentWebContents();
  813. return contents1 === contents2;
  814. });
  815. expect(equal).to.be.true();
  816. });
  817. });
  818. describe('remote class', () => {
  819. const remotely = makeRemotely(makeWindow());
  820. remotely.it(fixtures)('can get methods', (fixtures: string) => {
  821. const { base } = require('electron').remote.require(require('path').join(fixtures, 'class.js'));
  822. expect(base.method()).to.equal('method');
  823. });
  824. remotely.it(fixtures)('can get properties', (fixtures: string) => {
  825. const { base } = require('electron').remote.require(require('path').join(fixtures, 'class.js'));
  826. expect(base.readonly).to.equal('readonly');
  827. });
  828. remotely.it(fixtures)('can change properties', (fixtures: string) => {
  829. const { base } = require('electron').remote.require(require('path').join(fixtures, 'class.js'));
  830. expect(base.value).to.equal('old');
  831. base.value = 'new';
  832. expect(base.value).to.equal('new');
  833. base.value = 'old';
  834. });
  835. remotely.it(fixtures)('has unenumerable methods', (fixtures: string) => {
  836. const { base } = require('electron').remote.require(require('path').join(fixtures, 'class.js'));
  837. expect(base).to.not.have.ownProperty('method');
  838. expect(Object.getPrototypeOf(base)).to.have.ownProperty('method');
  839. });
  840. remotely.it(fixtures)('keeps prototype chain in derived class', (fixtures: string) => {
  841. const { derived } = require('electron').remote.require(require('path').join(fixtures, 'class.js'));
  842. expect(derived.method()).to.equal('method');
  843. expect(derived.readonly).to.equal('readonly');
  844. expect(derived).to.not.have.ownProperty('method');
  845. const proto = Object.getPrototypeOf(derived);
  846. expect(proto).to.not.have.ownProperty('method');
  847. expect(Object.getPrototypeOf(proto)).to.have.ownProperty('method');
  848. });
  849. remotely.it(fixtures)('is referenced by methods in prototype chain', (fixtures: string) => {
  850. let { derived } = require('electron').remote.require(require('path').join(fixtures, 'class.js'));
  851. const method = derived.method;
  852. derived = null;
  853. global.gc();
  854. expect(method()).to.equal('method');
  855. });
  856. });
  857. describe('remote exception', () => {
  858. const remotely = makeRemotely(makeWindow());
  859. remotely.it(fixtures)('throws errors from the main process', (fixtures: string) => {
  860. const throwFunction = require('electron').remote.require(require('path').join(fixtures, 'exception.js'));
  861. expect(() => {
  862. throwFunction();
  863. }).to.throw(/undefined/);
  864. });
  865. remotely.it(fixtures)('tracks error cause', (fixtures: string) => {
  866. const throwFunction = require('electron').remote.require(require('path').join(fixtures, 'exception.js'));
  867. try {
  868. throwFunction(new Error('error from main'));
  869. expect.fail();
  870. } catch (e) {
  871. expect(e.message).to.match(/Could not call remote function/);
  872. expect(e.cause.message).to.equal('error from main');
  873. }
  874. });
  875. });
  876. describe('gc behavior', () => {
  877. const win = makeWindow();
  878. const remotely = makeRemotely(win);
  879. it('is resilient to gc happening between request and response', async () => {
  880. const obj = { x: 'y' };
  881. win().webContents.on('remote-get-global', (event) => {
  882. event.returnValue = obj;
  883. });
  884. await remotely(() => {
  885. const { ipc } = process._linkedBinding('electron_renderer_ipc');
  886. const originalSendSync = ipc.sendSync.bind(ipc) as any;
  887. ipc.sendSync = (...args: any[]): any => {
  888. const ret = originalSendSync(...args);
  889. (window as any).gc();
  890. return ret;
  891. };
  892. for (let i = 0; i < 100; i++) {
  893. // eslint-disable-next-line
  894. require('electron').remote.getGlobal('test').x;
  895. }
  896. });
  897. });
  898. });
  899. });