api-remote-spec.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. 'use strict';
  2. const chai = require('chai');
  3. const dirtyChai = require('dirty-chai');
  4. const path = require('path');
  5. const { closeWindow } = require('./window-helpers');
  6. const { resolveGetters } = require('./expect-helpers');
  7. const { ifdescribe } = require('./spec-helpers');
  8. const { remote, ipcRenderer } = require('electron');
  9. const { ipcMain, BrowserWindow } = remote;
  10. const { expect } = chai;
  11. const features = process.electronBinding('features');
  12. chai.use(dirtyChai);
  13. const comparePaths = (path1, path2) => {
  14. if (process.platform === 'win32') {
  15. path1 = path1.toLowerCase();
  16. path2 = path2.toLowerCase();
  17. }
  18. expect(path1).to.equal(path2);
  19. };
  20. ifdescribe(features.isRemoteModuleEnabled())('remote module', () => {
  21. const fixtures = path.join(__dirname, 'fixtures');
  22. describe('remote.require', () => {
  23. it('should returns same object for the same module', () => {
  24. const dialog1 = remote.require('electron');
  25. const dialog2 = remote.require('electron');
  26. expect(dialog1).to.equal(dialog2);
  27. });
  28. it('should work when object contains id property', () => {
  29. const a = remote.require(path.join(fixtures, 'module', 'id.js'));
  30. expect(a.id).to.equal(1127);
  31. });
  32. it('should work when object has no prototype', () => {
  33. const a = remote.require(path.join(fixtures, 'module', 'no-prototype.js'));
  34. expect(a.foo.constructor.name).to.equal('');
  35. expect(a.foo.bar).to.equal('baz');
  36. expect(a.foo.baz).to.equal(false);
  37. expect(a.bar).to.equal(1234);
  38. expect(a.anonymous.constructor.name).to.equal('');
  39. expect(a.getConstructorName(Object.create(null))).to.equal('');
  40. expect(a.getConstructorName(new (class {})())).to.equal('');
  41. });
  42. it('should search module from the user app', () => {
  43. comparePaths(path.normalize(remote.process.mainModule.filename), path.resolve(__dirname, 'static', 'main.js'));
  44. comparePaths(path.normalize(remote.process.mainModule.paths[0]), path.resolve(__dirname, 'static', 'node_modules'));
  45. });
  46. it('should work with function properties', () => {
  47. let a = remote.require(path.join(fixtures, 'module', 'export-function-with-properties.js'));
  48. expect(a).to.be.a('function');
  49. expect(a.bar).to.equal('baz');
  50. a = remote.require(path.join(fixtures, 'module', 'function-with-properties.js'));
  51. expect(a).to.be.an('object');
  52. expect(a.foo()).to.equal('hello');
  53. expect(a.foo.bar).to.equal('baz');
  54. expect(a.foo.nested.prop).to.equal('yes');
  55. expect(a.foo.method1()).to.equal('world');
  56. expect(a.foo.method1.prop1()).to.equal(123);
  57. expect(a.foo).to.have.a.property('bar');
  58. expect(a.foo).to.have.a.property('nested');
  59. expect(a.foo).to.have.a.property('method1');
  60. a = remote.require(path.join(fixtures, 'module', 'function-with-missing-properties.js')).setup();
  61. expect(a.bar()).to.equal(true);
  62. expect(a.bar.baz).to.be.undefined();
  63. });
  64. it('should work with static class members', () => {
  65. const a = remote.require(path.join(fixtures, 'module', 'remote-static.js'));
  66. expect(a.Foo).to.be.a('function');
  67. expect(a.Foo.foo()).to.equal(3);
  68. expect(a.Foo.bar).to.equal('baz');
  69. const foo = new a.Foo();
  70. expect(foo.baz()).to.equal(123);
  71. });
  72. it('includes the length of functions specified as arguments', () => {
  73. const a = remote.require(path.join(fixtures, 'module', 'function-with-args.js'));
  74. expect(a((a, b, c, d, f) => {})).to.equal(5);
  75. expect(a((a) => {})).to.equal(1);
  76. expect(a((...args) => {})).to.equal(0);
  77. });
  78. it('handles circular references in arrays and objects', () => {
  79. const a = remote.require(path.join(fixtures, 'module', 'circular.js'));
  80. let arrayA = ['foo'];
  81. const arrayB = [arrayA, 'bar'];
  82. arrayA.push(arrayB);
  83. expect(a.returnArgs(arrayA, arrayB)).to.deep.equal([
  84. ['foo', [null, 'bar']],
  85. [['foo', null], 'bar']
  86. ]);
  87. let objectA = { foo: 'bar' };
  88. const objectB = { baz: objectA };
  89. objectA.objectB = objectB;
  90. expect(a.returnArgs(objectA, objectB)).to.deep.equal([
  91. { foo: 'bar', objectB: { baz: null } },
  92. { baz: { foo: 'bar', objectB: null } }
  93. ]);
  94. arrayA = [1, 2, 3];
  95. expect(a.returnArgs({ foo: arrayA }, { bar: arrayA })).to.deep.equal([
  96. { foo: [1, 2, 3] },
  97. { bar: [1, 2, 3] }
  98. ]);
  99. objectA = { foo: 'bar' };
  100. expect(a.returnArgs({ foo: objectA }, { bar: objectA })).to.deep.equal([
  101. { foo: { foo: 'bar' } },
  102. { bar: { foo: 'bar' } }
  103. ]);
  104. arrayA = [];
  105. arrayA.push(arrayA);
  106. expect(a.returnArgs(arrayA)).to.deep.equal([
  107. [null]
  108. ]);
  109. objectA = {};
  110. objectA.foo = objectA;
  111. objectA.bar = 'baz';
  112. expect(a.returnArgs(objectA)).to.deep.equal([
  113. { foo: null, bar: 'baz' }
  114. ]);
  115. objectA = {};
  116. objectA.foo = { bar: objectA };
  117. objectA.bar = 'baz';
  118. expect(a.returnArgs(objectA)).to.deep.equal([
  119. { foo: { bar: null }, bar: 'baz' }
  120. ]);
  121. });
  122. });
  123. describe('remote.createFunctionWithReturnValue', () => {
  124. it('should be called in browser synchronously', () => {
  125. const buf = Buffer.from('test');
  126. const call = remote.require(path.join(fixtures, 'module', 'call.js'));
  127. const result = call.call(remote.createFunctionWithReturnValue(buf));
  128. expect(result).to.be.an.instanceOf(Buffer);
  129. });
  130. });
  131. describe('remote modules', () => {
  132. it('includes browser process modules as properties', async () => {
  133. const mainModules = await ipcRenderer.invoke('get-modules');
  134. const remoteModules = mainModules.filter(name => remote[name]);
  135. expect(remoteModules).to.be.deep.equal(mainModules);
  136. });
  137. it('returns toString() of original function via toString()', () => {
  138. const { readText } = remote.clipboard;
  139. expect(readText.toString().startsWith('function')).to.be.true();
  140. const { functionWithToStringProperty } = remote.require(path.join(fixtures, 'module', 'to-string-non-function.js'));
  141. expect(functionWithToStringProperty.toString).to.equal('hello');
  142. });
  143. });
  144. describe('remote object in renderer', () => {
  145. it('can change its properties', () => {
  146. const property = remote.require(path.join(fixtures, 'module', 'property.js'));
  147. expect(property).to.have.a.property('property').that.is.equal(1127);
  148. property.property = null;
  149. expect(property).to.have.a.property('property').that.is.null();
  150. property.property = undefined;
  151. expect(property).to.have.a.property('property').that.is.undefined();
  152. property.property = 1007;
  153. expect(property).to.have.a.property('property').that.is.equal(1007);
  154. expect(property.getFunctionProperty()).to.equal('foo-browser');
  155. property.func.property = 'bar';
  156. expect(property.getFunctionProperty()).to.equal('bar-browser');
  157. property.func.property = 'foo'; // revert back
  158. const property2 = remote.require(path.join(fixtures, 'module', 'property.js'));
  159. expect(property2.property).to.equal(1007);
  160. property.property = 1127;
  161. });
  162. it('rethrows errors getting/setting properties', () => {
  163. const foo = remote.require(path.join(fixtures, 'module', 'error-properties.js'));
  164. expect(() => {
  165. // eslint-disable-next-line
  166. foo.bar
  167. }).to.throw('getting error');
  168. expect(() => {
  169. foo.bar = 'test';
  170. }).to.throw('setting error');
  171. });
  172. it('can set a remote property with a remote object', () => {
  173. const foo = remote.require(path.join(fixtures, 'module', 'remote-object-set.js'));
  174. expect(() => {
  175. foo.bar = remote.getCurrentWindow();
  176. }).to.not.throw();
  177. });
  178. it('can construct an object from its member', () => {
  179. const call = remote.require(path.join(fixtures, 'module', 'call.js'));
  180. const obj = new call.constructor();
  181. expect(obj.test).to.equal('test');
  182. });
  183. it('can reassign and delete its member functions', () => {
  184. const remoteFunctions = remote.require(path.join(fixtures, 'module', 'function.js'));
  185. expect(remoteFunctions.aFunction()).to.equal(1127);
  186. remoteFunctions.aFunction = () => { return 1234; };
  187. expect(remoteFunctions.aFunction()).to.equal(1234);
  188. expect(delete remoteFunctions.aFunction).to.equal(true);
  189. });
  190. it('is referenced by its members', () => {
  191. const stringify = remote.getGlobal('JSON').stringify;
  192. global.gc();
  193. stringify({});
  194. });
  195. });
  196. describe('remote value in browser', () => {
  197. const print = path.join(fixtures, 'module', 'print_name.js');
  198. const printName = remote.require(print);
  199. it('preserves NaN', () => {
  200. expect(printName.getNaN()).to.be.NaN();
  201. expect(printName.echo(NaN)).to.be.NaN();
  202. });
  203. it('preserves Infinity', () => {
  204. expect(printName.getInfinity()).to.equal(Infinity);
  205. expect(printName.echo(Infinity)).to.equal(Infinity);
  206. });
  207. it('keeps its constructor name for objects', () => {
  208. const buf = Buffer.from('test');
  209. expect(printName.print(buf)).to.equal('Buffer');
  210. });
  211. it('supports instanceof Boolean', () => {
  212. const obj = Boolean(true);
  213. expect(printName.print(obj)).to.equal('Boolean');
  214. expect(printName.echo(obj)).to.deep.equal(obj);
  215. });
  216. it('supports instanceof Number', () => {
  217. const obj = Number(42);
  218. expect(printName.print(obj)).to.equal('Number');
  219. expect(printName.echo(obj)).to.deep.equal(obj);
  220. });
  221. it('supports instanceof String', () => {
  222. const obj = String('Hello World!');
  223. expect(printName.print(obj)).to.equal('String');
  224. expect(printName.echo(obj)).to.deep.equal(obj);
  225. });
  226. it('supports instanceof Date', () => {
  227. const now = new Date();
  228. expect(printName.print(now)).to.equal('Date');
  229. expect(printName.echo(now)).to.deep.equal(now);
  230. });
  231. it('supports instanceof RegExp', () => {
  232. const regexp = RegExp('.*');
  233. expect(printName.print(regexp)).to.equal('RegExp');
  234. expect(printName.echo(regexp)).to.deep.equal(regexp);
  235. });
  236. it('supports instanceof Buffer', () => {
  237. const buffer = Buffer.from('test');
  238. expect(buffer.equals(printName.echo(buffer))).to.be.true();
  239. const objectWithBuffer = { a: 'foo', b: Buffer.from('bar') };
  240. expect(objectWithBuffer.b.equals(printName.echo(objectWithBuffer).b)).to.be.true();
  241. const arrayWithBuffer = [1, 2, Buffer.from('baz')];
  242. expect(arrayWithBuffer[2].equals(printName.echo(arrayWithBuffer)[2])).to.be.true();
  243. });
  244. it('supports instanceof ArrayBuffer', () => {
  245. const buffer = new ArrayBuffer(8);
  246. const view = new DataView(buffer);
  247. view.setFloat64(0, Math.PI);
  248. expect(printName.echo(buffer)).to.deep.equal(buffer);
  249. expect(printName.print(buffer)).to.equal('ArrayBuffer');
  250. });
  251. it('supports instanceof Int8Array', () => {
  252. const values = [1, 2, 3, 4];
  253. expect([...printName.typedArray('Int8Array', values)]).to.deep.equal(values);
  254. const int8values = new Int8Array(values);
  255. expect(printName.typedArray('Int8Array', int8values)).to.deep.equal(int8values);
  256. expect(printName.print(int8values)).to.equal('Int8Array');
  257. });
  258. it('supports instanceof Uint8Array', () => {
  259. const values = [1, 2, 3, 4];
  260. expect([...printName.typedArray('Uint8Array', values)]).to.deep.equal(values);
  261. const uint8values = new Uint8Array(values);
  262. expect(printName.typedArray('Uint8Array', uint8values)).to.deep.equal(uint8values);
  263. expect(printName.print(uint8values)).to.equal('Uint8Array');
  264. });
  265. it('supports instanceof Uint8ClampedArray', () => {
  266. const values = [1, 2, 3, 4];
  267. expect([...printName.typedArray('Uint8ClampedArray', values)]).to.deep.equal(values);
  268. const uint8values = new Uint8ClampedArray(values);
  269. expect(printName.typedArray('Uint8ClampedArray', uint8values)).to.deep.equal(uint8values);
  270. expect(printName.print(uint8values)).to.equal('Uint8ClampedArray');
  271. });
  272. it('supports instanceof Int16Array', () => {
  273. const values = [0x1234, 0x2345, 0x3456, 0x4567];
  274. expect([...printName.typedArray('Int16Array', values)]).to.deep.equal(values);
  275. const int16values = new Int16Array(values);
  276. expect(printName.typedArray('Int16Array', int16values)).to.deep.equal(int16values);
  277. expect(printName.print(int16values)).to.equal('Int16Array');
  278. });
  279. it('supports instanceof Uint16Array', () => {
  280. const values = [0x1234, 0x2345, 0x3456, 0x4567];
  281. expect([...printName.typedArray('Uint16Array', values)]).to.deep.equal(values);
  282. const uint16values = new Uint16Array(values);
  283. expect(printName.typedArray('Uint16Array', uint16values)).to.deep.equal(uint16values);
  284. expect(printName.print(uint16values)).to.equal('Uint16Array');
  285. });
  286. it('supports instanceof Int32Array', () => {
  287. const values = [0x12345678, 0x23456789];
  288. expect([...printName.typedArray('Int32Array', values)]).to.deep.equal(values);
  289. const int32values = new Int32Array(values);
  290. expect(printName.typedArray('Int32Array', int32values)).to.deep.equal(int32values);
  291. expect(printName.print(int32values)).to.equal('Int32Array');
  292. });
  293. it('supports instanceof Uint32Array', () => {
  294. const values = [0x12345678, 0x23456789];
  295. expect([...printName.typedArray('Uint32Array', values)]).to.deep.equal(values);
  296. const uint32values = new Uint32Array(values);
  297. expect(printName.typedArray('Uint32Array', uint32values)).to.deep.equal(uint32values);
  298. expect(printName.print(uint32values)).to.equal('Uint32Array');
  299. });
  300. it('supports instanceof Float32Array', () => {
  301. const values = [0.5, 1.0, 1.5];
  302. expect([...printName.typedArray('Float32Array', values)]).to.deep.equal(values);
  303. const float32values = new Float32Array();
  304. expect(printName.typedArray('Float32Array', float32values)).to.deep.equal(float32values);
  305. expect(printName.print(float32values)).to.equal('Float32Array');
  306. });
  307. it('supports instanceof Float64Array', () => {
  308. const values = [0.5, 1.0, 1.5];
  309. expect([...printName.typedArray('Float64Array', values)]).to.deep.equal(values);
  310. const float64values = new Float64Array([0.5, 1.0, 1.5]);
  311. expect(printName.typedArray('Float64Array', float64values)).to.deep.equal(float64values);
  312. expect(printName.print(float64values)).to.equal('Float64Array');
  313. });
  314. });
  315. describe('remote promise', () => {
  316. it('can be used as promise in each side', (done) => {
  317. const promise = remote.require(path.join(fixtures, 'module', 'promise.js'));
  318. promise.twicePromise(Promise.resolve(1234)).then((value) => {
  319. expect(value).to.equal(2468);
  320. done();
  321. });
  322. });
  323. it('handles rejections via catch(onRejected)', (done) => {
  324. const promise = remote.require(path.join(fixtures, 'module', 'rejected-promise.js'));
  325. promise.reject(Promise.resolve(1234)).catch((error) => {
  326. expect(error.message).to.equal('rejected');
  327. done();
  328. });
  329. });
  330. it('handles rejections via then(onFulfilled, onRejected)', (done) => {
  331. const promise = remote.require(path.join(fixtures, 'module', 'rejected-promise.js'));
  332. promise.reject(Promise.resolve(1234)).then(() => {}, (error) => {
  333. expect(error.message).to.equal('rejected');
  334. done();
  335. });
  336. });
  337. it('does not emit unhandled rejection events in the main process', (done) => {
  338. remote.process.once('unhandledRejection', function (reason) {
  339. done(reason);
  340. });
  341. const promise = remote.require(path.join(fixtures, 'module', 'unhandled-rejection.js'));
  342. promise.reject().then(() => {
  343. done(new Error('Promise was not rejected'));
  344. }).catch((error) => {
  345. expect(error.message).to.equal('rejected');
  346. done();
  347. });
  348. });
  349. it('emits unhandled rejection events in the renderer process', (done) => {
  350. window.addEventListener('unhandledrejection', function handler (event) {
  351. event.preventDefault();
  352. expect(event.reason.message).to.equal('rejected');
  353. window.removeEventListener('unhandledrejection', handler);
  354. done();
  355. });
  356. const promise = remote.require(path.join(fixtures, 'module', 'unhandled-rejection.js'));
  357. promise.reject().then(() => {
  358. done(new Error('Promise was not rejected'));
  359. });
  360. });
  361. });
  362. describe('remote webContents', () => {
  363. it('can return same object with different getters', () => {
  364. const contents1 = remote.getCurrentWindow().webContents;
  365. const contents2 = remote.getCurrentWebContents();
  366. expect(contents1).to.equal(contents2);
  367. });
  368. });
  369. describe('remote class', () => {
  370. const cl = remote.require(path.join(fixtures, 'module', 'class.js'));
  371. const base = cl.base;
  372. let derived = cl.derived;
  373. it('can get methods', () => {
  374. expect(base.method()).to.equal('method');
  375. });
  376. it('can get properties', () => {
  377. expect(base.readonly).to.equal('readonly');
  378. });
  379. it('can change properties', () => {
  380. expect(base.value).to.equal('old');
  381. base.value = 'new';
  382. expect(base.value).to.equal('new');
  383. base.value = 'old';
  384. });
  385. it('has unenumerable methods', () => {
  386. expect(base).to.not.have.own.property('method');
  387. expect(Object.getPrototypeOf(base)).to.have.own.property('method');
  388. });
  389. it('keeps prototype chain in derived class', () => {
  390. expect(derived.method()).to.equal('method');
  391. expect(derived.readonly).to.equal('readonly');
  392. expect(derived).to.not.have.own.property('method');
  393. const proto = Object.getPrototypeOf(derived);
  394. expect(proto).to.not.have.own.property('method');
  395. expect(Object.getPrototypeOf(proto)).to.have.own.property('method');
  396. });
  397. it('is referenced by methods in prototype chain', () => {
  398. const method = derived.method;
  399. derived = null;
  400. global.gc();
  401. expect(method()).to.equal('method');
  402. });
  403. });
  404. describe('remote exception', () => {
  405. const throwFunction = remote.require(path.join(fixtures, 'module', 'exception.js'));
  406. it('throws errors from the main process', () => {
  407. expect(() => {
  408. throwFunction();
  409. }).to.throw(/undefined/);
  410. });
  411. it('tracks error cause', () => {
  412. try {
  413. throwFunction(new Error('error from main'));
  414. expect.fail();
  415. } catch (e) {
  416. expect(e.message).to.match(/Could not call remote function/);
  417. expect(e.cause.message).to.equal('error from main');
  418. }
  419. });
  420. });
  421. describe('remote function in renderer', () => {
  422. let w = null;
  423. afterEach(() => closeWindow(w).then(() => { w = null; }));
  424. afterEach(() => {
  425. ipcMain.removeAllListeners('done');
  426. });
  427. it('works when created in preload script', (done) => {
  428. ipcMain.once('done', () => w.close());
  429. const preload = path.join(fixtures, 'module', 'preload-remote-function.js');
  430. w = new BrowserWindow({
  431. show: false,
  432. webPreferences: {
  433. preload
  434. }
  435. });
  436. w.once('closed', () => done());
  437. w.loadURL('about:blank');
  438. });
  439. });
  440. describe('constructing a Uint8Array', () => {
  441. it('does not crash', () => {
  442. const RUint8Array = remote.getGlobal('Uint8Array');
  443. const arr = new RUint8Array();
  444. });
  445. });
  446. describe('remote listeners', () => {
  447. let w = null;
  448. afterEach(() => closeWindow(w).then(() => { w = null; }));
  449. it('detaches listeners subscribed to destroyed renderers, and shows a warning', (done) => {
  450. w = new BrowserWindow({
  451. show: false,
  452. webPreferences: {
  453. nodeIntegration: true
  454. }
  455. });
  456. w.webContents.once('did-finish-load', () => {
  457. w.webContents.once('did-finish-load', () => {
  458. const expectedMessage = [
  459. 'Attempting to call a function in a renderer window that has been closed or released.',
  460. 'Function provided here: remote-event-handler.html:11:33',
  461. 'Remote event names: remote-handler, other-remote-handler'
  462. ].join('\n');
  463. const results = ipcRenderer.sendSync('try-emit-web-contents-event', w.webContents.id, 'remote-handler');
  464. expect(results).to.deep.equal({
  465. warningMessage: expectedMessage,
  466. listenerCountBefore: 2,
  467. listenerCountAfter: 1
  468. });
  469. done();
  470. });
  471. w.webContents.reload();
  472. });
  473. w.loadFile(path.join(fixtures, 'api', 'remote-event-handler.html'));
  474. });
  475. });
  476. describe('with an overriden global Promise constrctor', () => {
  477. let original;
  478. before(() => {
  479. original = Promise;
  480. });
  481. it('using a promise based method resolves correctly', async () => {
  482. expect(await remote.getGlobal('returnAPromise')(123)).to.equal(123);
  483. global.Promise = { resolve: () => ({}) };
  484. expect(await remote.getGlobal('returnAPromise')(456)).to.equal(456);
  485. });
  486. after(() => {
  487. global.Promise = original;
  488. });
  489. });
  490. });