api-app-spec.ts 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  1. import { app, BrowserWindow, Menu, session, net as electronNet, WebContents, utilityProcess } from 'electron/main';
  2. import { assert, expect } from 'chai';
  3. import * as semver from 'semver';
  4. import split = require('split')
  5. import * as cp from 'node:child_process';
  6. import { once } from 'node:events';
  7. import * as fs from 'node:fs';
  8. import * as http from 'node:http';
  9. import * as https from 'node:https';
  10. import * as net from 'node:net';
  11. import * as path from 'node:path';
  12. import { promisify } from 'node:util';
  13. import { collectStreamBody, getResponse } from './lib/net-helpers';
  14. import { ifdescribe, ifit, listen, waitUntil } from './lib/spec-helpers';
  15. import { closeWindow, closeAllWindows } from './lib/window-helpers';
  16. const fixturesPath = path.resolve(__dirname, 'fixtures');
  17. describe('electron module', () => {
  18. it('does not expose internal modules to require', () => {
  19. expect(() => {
  20. require('clipboard');
  21. }).to.throw(/Cannot find module 'clipboard'/);
  22. });
  23. describe('require("electron")', () => {
  24. it('always returns the internal electron module', () => {
  25. require('electron');
  26. });
  27. });
  28. });
  29. describe('app module', () => {
  30. let server: https.Server;
  31. let secureUrl: string;
  32. const certPath = path.join(fixturesPath, 'certificates');
  33. before(async () => {
  34. const options = {
  35. key: fs.readFileSync(path.join(certPath, 'server.key')),
  36. cert: fs.readFileSync(path.join(certPath, 'server.pem')),
  37. ca: [
  38. fs.readFileSync(path.join(certPath, 'rootCA.pem')),
  39. fs.readFileSync(path.join(certPath, 'intermediateCA.pem'))
  40. ],
  41. requestCert: true,
  42. rejectUnauthorized: false
  43. };
  44. server = https.createServer(options, (req, res) => {
  45. if ((req as any).client.authorized) {
  46. res.writeHead(200);
  47. res.end('<title>authorized</title>');
  48. } else {
  49. res.writeHead(401);
  50. res.end('<title>denied</title>');
  51. }
  52. });
  53. secureUrl = (await listen(server)).url;
  54. });
  55. after(done => {
  56. server.close(() => done());
  57. });
  58. describe('app.getVersion()', () => {
  59. it('returns the version field of package.json', () => {
  60. expect(app.getVersion()).to.equal('0.1.0');
  61. });
  62. });
  63. describe('app.setVersion(version)', () => {
  64. it('overrides the version', () => {
  65. expect(app.getVersion()).to.equal('0.1.0');
  66. app.setVersion('test-version');
  67. expect(app.getVersion()).to.equal('test-version');
  68. app.setVersion('0.1.0');
  69. });
  70. });
  71. describe('app name APIs', () => {
  72. it('with properties', () => {
  73. it('returns the name field of package.json', () => {
  74. expect(app.name).to.equal('Electron Test Main');
  75. });
  76. it('overrides the name', () => {
  77. expect(app.name).to.equal('Electron Test Main');
  78. app.name = 'electron-test-name';
  79. expect(app.name).to.equal('electron-test-name');
  80. app.name = 'Electron Test Main';
  81. });
  82. });
  83. it('with functions', () => {
  84. it('returns the name field of package.json', () => {
  85. expect(app.getName()).to.equal('Electron Test Main');
  86. });
  87. it('overrides the name', () => {
  88. expect(app.getName()).to.equal('Electron Test Main');
  89. app.setName('electron-test-name');
  90. expect(app.getName()).to.equal('electron-test-name');
  91. app.setName('Electron Test Main');
  92. });
  93. });
  94. });
  95. describe('app.getLocale()', () => {
  96. it('should not be empty', () => {
  97. expect(app.getLocale()).to.not.equal('');
  98. });
  99. });
  100. describe('app.getSystemLocale()', () => {
  101. it('should not be empty', () => {
  102. expect(app.getSystemLocale()).to.not.equal('');
  103. });
  104. });
  105. describe('app.getPreferredSystemLanguages()', () => {
  106. ifit(process.platform !== 'linux')('should not be empty', () => {
  107. expect(app.getPreferredSystemLanguages().length).to.not.equal(0);
  108. });
  109. ifit(process.platform === 'linux')('should be empty or contain C entry', () => {
  110. const languages = app.getPreferredSystemLanguages();
  111. if (languages.length) {
  112. expect(languages).to.not.include('C');
  113. }
  114. });
  115. });
  116. describe('app.getLocaleCountryCode()', () => {
  117. it('should be empty or have length of two', () => {
  118. const localeCountryCode = app.getLocaleCountryCode();
  119. expect(localeCountryCode).to.be.a('string');
  120. expect(localeCountryCode.length).to.be.oneOf([0, 2]);
  121. });
  122. });
  123. describe('app.isPackaged', () => {
  124. it('should be false during tests', () => {
  125. expect(app.isPackaged).to.equal(false);
  126. });
  127. });
  128. ifdescribe(process.platform === 'darwin')('app.isInApplicationsFolder()', () => {
  129. it('should be false during tests', () => {
  130. expect(app.isInApplicationsFolder()).to.equal(false);
  131. });
  132. });
  133. describe('app.exit(exitCode)', () => {
  134. let appProcess: cp.ChildProcess | null = null;
  135. afterEach(() => {
  136. if (appProcess) appProcess.kill();
  137. });
  138. it('emits a process exit event with the code', async () => {
  139. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  140. const electronPath = process.execPath;
  141. let output = '';
  142. appProcess = cp.spawn(electronPath, [appPath]);
  143. if (appProcess && appProcess.stdout) {
  144. appProcess.stdout.on('data', data => { output += data; });
  145. }
  146. const [code] = await once(appProcess, 'exit');
  147. if (process.platform !== 'win32') {
  148. expect(output).to.include('Exit event with code: 123');
  149. }
  150. expect(code).to.equal(123);
  151. });
  152. it('closes all windows', async function () {
  153. const appPath = path.join(fixturesPath, 'api', 'exit-closes-all-windows-app');
  154. const electronPath = process.execPath;
  155. appProcess = cp.spawn(electronPath, [appPath]);
  156. const [code, signal] = await once(appProcess, 'exit');
  157. expect(signal).to.equal(null, 'exit signal should be null, if you see this please tag @MarshallOfSound');
  158. expect(code).to.equal(123, 'exit code should be 123, if you see this please tag @MarshallOfSound');
  159. });
  160. ifit(['darwin', 'linux'].includes(process.platform))('exits gracefully', async function () {
  161. const electronPath = process.execPath;
  162. const appPath = path.join(fixturesPath, 'api', 'singleton');
  163. appProcess = cp.spawn(electronPath, [appPath]);
  164. // Singleton will send us greeting data to let us know it's running.
  165. // After that, ask it to exit gracefully and confirm that it does.
  166. if (appProcess && appProcess.stdout) {
  167. appProcess.stdout.on('data', () => appProcess!.kill());
  168. }
  169. const [code, signal] = await once(appProcess, 'exit');
  170. const message = `code:\n${code}\nsignal:\n${signal}`;
  171. expect(code).to.equal(0, message);
  172. expect(signal).to.equal(null, message);
  173. });
  174. });
  175. ifdescribe(process.platform === 'darwin')('app.setActivationPolicy', () => {
  176. it('throws an error on invalid application policies', () => {
  177. expect(() => {
  178. app.setActivationPolicy('terrible' as any);
  179. }).to.throw(/Invalid activation policy: must be one of 'regular', 'accessory', or 'prohibited'/);
  180. });
  181. });
  182. describe('app.requestSingleInstanceLock', () => {
  183. interface SingleInstanceLockTestArgs {
  184. args: string[];
  185. expectedAdditionalData: unknown;
  186. }
  187. it('prevents the second launch of app', async function () {
  188. this.timeout(120000);
  189. const appPath = path.join(fixturesPath, 'api', 'singleton-data');
  190. const first = cp.spawn(process.execPath, [appPath]);
  191. await once(first.stdout, 'data');
  192. // Start second app when received output.
  193. const second = cp.spawn(process.execPath, [appPath]);
  194. const [code2] = await once(second, 'exit');
  195. expect(code2).to.equal(1);
  196. const [code1] = await once(first, 'exit');
  197. expect(code1).to.equal(0);
  198. });
  199. it('returns true when setting non-existent user data folder', async function () {
  200. const appPath = path.join(fixturesPath, 'api', 'singleton-userdata');
  201. const instance = cp.spawn(process.execPath, [appPath]);
  202. const [code] = await once(instance, 'exit');
  203. expect(code).to.equal(0);
  204. });
  205. async function testArgumentPassing (testArgs: SingleInstanceLockTestArgs) {
  206. const appPath = path.join(fixturesPath, 'api', 'singleton-data');
  207. const first = cp.spawn(process.execPath, [appPath, ...testArgs.args]);
  208. const firstExited = once(first, 'exit');
  209. // Wait for the first app to boot.
  210. const firstStdoutLines = first.stdout.pipe(split());
  211. while ((await once(firstStdoutLines, 'data')).toString() !== 'started') {
  212. // wait.
  213. }
  214. const additionalDataPromise = once(firstStdoutLines, 'data');
  215. const secondInstanceArgs = [process.execPath, appPath, ...testArgs.args, '--some-switch', 'some-arg'];
  216. const second = cp.spawn(secondInstanceArgs[0], secondInstanceArgs.slice(1));
  217. const secondExited = once(second, 'exit');
  218. const [code2] = await secondExited;
  219. expect(code2).to.equal(1);
  220. const [code1] = await firstExited;
  221. expect(code1).to.equal(0);
  222. const dataFromSecondInstance = await additionalDataPromise;
  223. const [args, additionalData] = dataFromSecondInstance[0].toString('ascii').split('||');
  224. const secondInstanceArgsReceived: string[] = JSON.parse(args.toString('ascii'));
  225. const secondInstanceDataReceived = JSON.parse(additionalData.toString('ascii'));
  226. // Ensure secondInstanceArgs is a subset of secondInstanceArgsReceived
  227. for (const arg of secondInstanceArgs) {
  228. expect(secondInstanceArgsReceived).to.include(arg,
  229. `argument ${arg} is missing from received second args`);
  230. }
  231. expect(secondInstanceDataReceived).to.be.deep.equal(testArgs.expectedAdditionalData,
  232. `received data ${JSON.stringify(secondInstanceDataReceived)} is not equal to expected data ${JSON.stringify(testArgs.expectedAdditionalData)}.`);
  233. }
  234. it('passes arguments to the second-instance event no additional data', async () => {
  235. await testArgumentPassing({
  236. args: [],
  237. expectedAdditionalData: null
  238. });
  239. });
  240. it('sends and receives JSON object data', async () => {
  241. const expectedAdditionalData = {
  242. level: 1,
  243. testkey: 'testvalue1',
  244. inner: {
  245. level: 2,
  246. testkey: 'testvalue2'
  247. }
  248. };
  249. await testArgumentPassing({
  250. args: ['--send-data'],
  251. expectedAdditionalData
  252. });
  253. });
  254. it('sends and receives numerical data', async () => {
  255. await testArgumentPassing({
  256. args: ['--send-data', '--data-content=2'],
  257. expectedAdditionalData: 2
  258. });
  259. });
  260. it('sends and receives string data', async () => {
  261. await testArgumentPassing({
  262. args: ['--send-data', '--data-content="data"'],
  263. expectedAdditionalData: 'data'
  264. });
  265. });
  266. it('sends and receives boolean data', async () => {
  267. await testArgumentPassing({
  268. args: ['--send-data', '--data-content=false'],
  269. expectedAdditionalData: false
  270. });
  271. });
  272. it('sends and receives array data', async () => {
  273. await testArgumentPassing({
  274. args: ['--send-data', '--data-content=[2, 3, 4]'],
  275. expectedAdditionalData: [2, 3, 4]
  276. });
  277. });
  278. it('sends and receives mixed array data', async () => {
  279. await testArgumentPassing({
  280. args: ['--send-data', '--data-content=["2", true, 4]'],
  281. expectedAdditionalData: ['2', true, 4]
  282. });
  283. });
  284. it('sends and receives null data', async () => {
  285. await testArgumentPassing({
  286. args: ['--send-data', '--data-content=null'],
  287. expectedAdditionalData: null
  288. });
  289. });
  290. it('cannot send or receive undefined data', async () => {
  291. try {
  292. await testArgumentPassing({
  293. args: ['--send-ack', '--ack-content="undefined"', '--prevent-default', '--send-data', '--data-content="undefined"'],
  294. expectedAdditionalData: undefined
  295. });
  296. assert(false);
  297. } catch {
  298. // This is expected.
  299. }
  300. });
  301. });
  302. describe('app.relaunch', () => {
  303. let server: net.Server | null = null;
  304. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-app-relaunch' : '/tmp/electron-app-relaunch';
  305. beforeEach(done => {
  306. fs.unlink(socketPath, () => {
  307. server = net.createServer();
  308. server.listen(socketPath);
  309. done();
  310. });
  311. });
  312. afterEach((done) => {
  313. server!.close(() => {
  314. if (process.platform === 'win32') {
  315. done();
  316. } else {
  317. fs.unlink(socketPath, () => done());
  318. }
  319. });
  320. });
  321. it('relaunches the app', function (done) {
  322. this.timeout(120000);
  323. let state = 'none';
  324. server!.once('error', error => done(error));
  325. server!.on('connection', client => {
  326. client.once('data', data => {
  327. if (String(data) === '--first' && state === 'none') {
  328. state = 'first-launch';
  329. } else if (String(data) === '--second' && state === 'first-launch') {
  330. state = 'second-launch';
  331. } else if (String(data) === '--third' && state === 'second-launch') {
  332. done();
  333. } else {
  334. done(`Unexpected state: "${state}", data: "${data}"`);
  335. }
  336. });
  337. });
  338. const appPath = path.join(fixturesPath, 'api', 'relaunch');
  339. const child = cp.spawn(process.execPath, [appPath, '--first']);
  340. child.stdout.on('data', (c) => console.log(c.toString()));
  341. child.stderr.on('data', (c) => console.log(c.toString()));
  342. child.on('exit', (code, signal) => {
  343. if (code !== 0) {
  344. console.log(`Process exited with code "${code}" signal "${signal}"`);
  345. }
  346. });
  347. });
  348. });
  349. ifdescribe(process.platform === 'darwin')('app.setUserActivity(type, userInfo)', () => {
  350. it('sets the current activity', () => {
  351. app.setUserActivity('com.electron.testActivity', { testData: '123' });
  352. expect(app.getCurrentActivityType()).to.equal('com.electron.testActivity');
  353. });
  354. });
  355. describe('certificate-error event', () => {
  356. afterEach(closeAllWindows);
  357. it('is emitted when visiting a server with a self-signed cert', async () => {
  358. const w = new BrowserWindow({ show: false });
  359. w.loadURL(secureUrl);
  360. await once(app, 'certificate-error');
  361. });
  362. describe('when denied', () => {
  363. before(() => {
  364. app.on('certificate-error', (event, webContents, url, error, certificate, callback) => {
  365. callback(false);
  366. });
  367. });
  368. after(() => {
  369. app.removeAllListeners('certificate-error');
  370. });
  371. it('causes did-fail-load', async () => {
  372. const w = new BrowserWindow({ show: false });
  373. w.loadURL(secureUrl);
  374. await once(w.webContents, 'did-fail-load');
  375. });
  376. });
  377. });
  378. // xdescribe('app.importCertificate', () => {
  379. // let w = null
  380. // before(function () {
  381. // if (process.platform !== 'linux') {
  382. // this.skip()
  383. // }
  384. // })
  385. // afterEach(() => closeWindow(w).then(() => { w = null }))
  386. // it('can import certificate into platform cert store', done => {
  387. // const options = {
  388. // certificate: path.join(certPath, 'client.p12'),
  389. // password: 'electron'
  390. // }
  391. // w = new BrowserWindow({
  392. // show: false,
  393. // webPreferences: {
  394. // nodeIntegration: true
  395. // }
  396. // })
  397. // w.webContents.on('did-finish-load', () => {
  398. // expect(w.webContents.getTitle()).to.equal('authorized')
  399. // done()
  400. // })
  401. // ipcRenderer.once('select-client-certificate', (event, webContentsId, list) => {
  402. // expect(webContentsId).to.equal(w.webContents.id)
  403. // expect(list).to.have.lengthOf(1)
  404. // expect(list[0]).to.deep.equal({
  405. // issuerName: 'Intermediate CA',
  406. // subjectName: 'Client Cert',
  407. // issuer: { commonName: 'Intermediate CA' },
  408. // subject: { commonName: 'Client Cert' }
  409. // })
  410. // event.sender.send('client-certificate-response', list[0])
  411. // })
  412. // app.importCertificate(options, result => {
  413. // expect(result).toNotExist()
  414. // ipcRenderer.sendSync('set-client-certificate-option', false)
  415. // w.loadURL(secureUrl)
  416. // })
  417. // })
  418. // })
  419. describe('BrowserWindow events', () => {
  420. let w: BrowserWindow = null as any;
  421. afterEach(() => {
  422. closeWindow(w).then(() => { w = null as any; });
  423. });
  424. it('should emit browser-window-focus event when window is focused', async () => {
  425. const emitted = once(app, 'browser-window-focus') as Promise<[any, BrowserWindow]>;
  426. w = new BrowserWindow({ show: false });
  427. w.emit('focus');
  428. const [, window] = await emitted;
  429. expect(window.id).to.equal(w.id);
  430. });
  431. it('should emit browser-window-blur event when window is blurred', async () => {
  432. const emitted = once(app, 'browser-window-blur') as Promise<[any, BrowserWindow]>;
  433. w = new BrowserWindow({ show: false });
  434. w.emit('blur');
  435. const [, window] = await emitted;
  436. expect(window.id).to.equal(w.id);
  437. });
  438. it('should emit browser-window-created event when window is created', async () => {
  439. const emitted = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
  440. w = new BrowserWindow({ show: false });
  441. const [, window] = await emitted;
  442. expect(window.id).to.equal(w.id);
  443. });
  444. it('should emit web-contents-created event when a webContents is created', async () => {
  445. const emitted = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
  446. w = new BrowserWindow({ show: false });
  447. const [, webContents] = await emitted;
  448. expect(webContents.id).to.equal(w.webContents.id);
  449. });
  450. // FIXME: re-enable this test on win32.
  451. ifit(process.platform !== 'win32')('should emit render-process-gone event when renderer crashes', async () => {
  452. w = new BrowserWindow({
  453. show: false,
  454. webPreferences: {
  455. nodeIntegration: true,
  456. contextIsolation: false
  457. }
  458. });
  459. await w.loadURL('about:blank');
  460. const emitted = once(app, 'render-process-gone') as Promise<[any, WebContents, Electron.RenderProcessGoneDetails]>;
  461. w.webContents.executeJavaScript('process.crash()');
  462. const [, webContents, details] = await emitted;
  463. expect(webContents).to.equal(w.webContents);
  464. expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
  465. });
  466. });
  467. describe('app.badgeCount', () => {
  468. const platformIsNotSupported =
  469. (process.platform === 'win32') ||
  470. (process.platform === 'linux' && !app.isUnityRunning());
  471. const expectedBadgeCount = 42;
  472. after(() => { app.badgeCount = 0; });
  473. ifdescribe(!platformIsNotSupported)('on supported platform', () => {
  474. describe('with properties', () => {
  475. it('sets a badge count', function () {
  476. app.badgeCount = expectedBadgeCount;
  477. expect(app.badgeCount).to.equal(expectedBadgeCount);
  478. });
  479. });
  480. describe('with functions', () => {
  481. it('sets a numerical badge count', function () {
  482. app.setBadgeCount(expectedBadgeCount);
  483. expect(app.getBadgeCount()).to.equal(expectedBadgeCount);
  484. });
  485. it('sets an non numeric (dot) badge count', function () {
  486. app.setBadgeCount();
  487. // Badge count should be zero when non numeric (dot) is requested
  488. expect(app.getBadgeCount()).to.equal(0);
  489. });
  490. });
  491. });
  492. ifdescribe(process.platform !== 'win32' && platformIsNotSupported)('on unsupported platform', () => {
  493. describe('with properties', () => {
  494. it('does not set a badge count', function () {
  495. app.badgeCount = 9999;
  496. expect(app.badgeCount).to.equal(0);
  497. });
  498. });
  499. describe('with functions', () => {
  500. it('does not set a badge count)', function () {
  501. app.setBadgeCount(9999);
  502. expect(app.getBadgeCount()).to.equal(0);
  503. });
  504. });
  505. });
  506. });
  507. ifdescribe(process.platform !== 'linux' && !process.mas && (process.platform !== 'darwin' || process.arch === 'arm64'))('app.get/setLoginItemSettings API', function () {
  508. const isMac = process.platform === 'darwin';
  509. const isWin = process.platform === 'win32';
  510. const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  511. const processStartArgs = [
  512. '--processStart', `"${path.basename(process.execPath)}"`,
  513. '--process-start-args', '"--hidden"'
  514. ];
  515. const regAddArgs = [
  516. 'ADD',
  517. 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run',
  518. '/v',
  519. 'additionalEntry',
  520. '/t',
  521. 'REG_BINARY',
  522. '/f',
  523. '/d'
  524. ];
  525. const productVersion = isMac ? cp.execSync('sw_vers -productVersion').toString().trim() : '';
  526. const isVenturaOrHigher = semver.gt(semver.coerce(productVersion) || '0.0.0', '13.0.0');
  527. beforeEach(() => {
  528. app.setLoginItemSettings({ openAtLogin: false });
  529. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
  530. app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
  531. });
  532. afterEach(() => {
  533. app.setLoginItemSettings({ openAtLogin: false });
  534. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs });
  535. app.setLoginItemSettings({ name: 'additionalEntry', openAtLogin: false });
  536. });
  537. ifit(!isWin)('sets and returns the app as a login item', () => {
  538. app.setLoginItemSettings({ openAtLogin: true });
  539. const settings = app.getLoginItemSettings();
  540. expect(settings.openAtLogin).to.equal(true);
  541. expect(settings.openAsHidden).to.equal(false);
  542. expect(settings.wasOpenedAtLogin).to.equal(false);
  543. expect(settings.wasOpenedAsHidden).to.equal(false);
  544. expect(settings.restoreState).to.equal(false);
  545. if (isVenturaOrHigher) expect(settings.status).to.equal('enabled');
  546. });
  547. ifit(isWin)('sets and returns the app as a login item (windows)', () => {
  548. app.setLoginItemSettings({ openAtLogin: true, enabled: true });
  549. expect(app.getLoginItemSettings()).to.deep.equal({
  550. openAtLogin: true,
  551. openAsHidden: false,
  552. wasOpenedAtLogin: false,
  553. wasOpenedAsHidden: false,
  554. restoreState: false,
  555. executableWillLaunchAtLogin: true,
  556. launchItems: [{
  557. name: 'electron.app.Electron',
  558. path: process.execPath,
  559. args: [],
  560. scope: 'user',
  561. enabled: true
  562. }]
  563. });
  564. app.setLoginItemSettings({ openAtLogin: false });
  565. app.setLoginItemSettings({ openAtLogin: true, enabled: false });
  566. expect(app.getLoginItemSettings()).to.deep.equal({
  567. openAtLogin: true,
  568. openAsHidden: false,
  569. wasOpenedAtLogin: false,
  570. wasOpenedAsHidden: false,
  571. restoreState: false,
  572. executableWillLaunchAtLogin: false,
  573. launchItems: [{
  574. name: 'electron.app.Electron',
  575. path: process.execPath,
  576. args: [],
  577. scope: 'user',
  578. enabled: false
  579. }]
  580. });
  581. });
  582. ifit(!isWin)('adds a login item that loads in hidden mode', () => {
  583. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  584. const settings = app.getLoginItemSettings();
  585. expect(settings.openAtLogin).to.equal(true);
  586. const hasOpenAsHidden = process.platform === 'darwin' && !isVenturaOrHigher;
  587. expect(settings.openAsHidden).to.equal(hasOpenAsHidden);
  588. expect(settings.wasOpenedAtLogin).to.equal(false);
  589. expect(settings.wasOpenedAsHidden).to.equal(false);
  590. expect(settings.restoreState).to.equal(false);
  591. if (isVenturaOrHigher) expect(settings.status).to.equal('enabled');
  592. });
  593. ifit(isWin)('adds a login item that loads in hidden mode (windows)', () => {
  594. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  595. expect(app.getLoginItemSettings()).to.deep.equal({
  596. openAtLogin: true,
  597. openAsHidden: false,
  598. wasOpenedAtLogin: false,
  599. wasOpenedAsHidden: false,
  600. restoreState: false,
  601. executableWillLaunchAtLogin: true,
  602. launchItems: [{
  603. name: 'electron.app.Electron',
  604. path: process.execPath,
  605. args: [],
  606. scope: 'user',
  607. enabled: true
  608. }]
  609. });
  610. });
  611. it('correctly sets and unsets the LoginItem', () => {
  612. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  613. app.setLoginItemSettings({ openAtLogin: true });
  614. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  615. app.setLoginItemSettings({ openAtLogin: false });
  616. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  617. });
  618. ifit(isMac)('correctly sets and unsets the LoginItem as hidden', () => {
  619. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  620. expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
  621. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: true });
  622. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  623. expect(app.getLoginItemSettings().openAsHidden).to.equal(!isVenturaOrHigher);
  624. app.setLoginItemSettings({ openAtLogin: true, openAsHidden: false });
  625. expect(app.getLoginItemSettings().openAtLogin).to.equal(true);
  626. expect(app.getLoginItemSettings().openAsHidden).to.equal(false);
  627. });
  628. ifdescribe(isMac)('using SMAppService', () => {
  629. ifit(isVenturaOrHigher)('can set a login item', () => {
  630. app.setLoginItemSettings({
  631. openAtLogin: true,
  632. type: 'mainAppService'
  633. });
  634. expect(app.getLoginItemSettings()).to.deep.equal({
  635. status: 'enabled',
  636. openAtLogin: true,
  637. openAsHidden: false,
  638. restoreState: false,
  639. wasOpenedAtLogin: false,
  640. wasOpenedAsHidden: false
  641. });
  642. });
  643. ifit(isVenturaOrHigher)('throws when setting non-default type with no name', () => {
  644. expect(() => {
  645. app.setLoginItemSettings({
  646. openAtLogin: true,
  647. type: 'daemonService'
  648. });
  649. }).to.throw(/'name' is required when type is not mainAppService/);
  650. });
  651. ifit(isVenturaOrHigher)('throws when getting non-default type with no name', () => {
  652. expect(() => {
  653. app.getLoginItemSettings({
  654. type: 'daemonService'
  655. });
  656. }).to.throw(/'name' is required when type is not mainAppService/);
  657. });
  658. ifit(isVenturaOrHigher)('can unset a login item', () => {
  659. app.setLoginItemSettings({
  660. openAtLogin: true,
  661. type: 'mainAppService'
  662. });
  663. app.setLoginItemSettings({
  664. openAtLogin: false,
  665. type: 'mainAppService'
  666. });
  667. expect(app.getLoginItemSettings()).to.deep.equal({
  668. status: 'not-registered',
  669. openAtLogin: false,
  670. openAsHidden: false,
  671. restoreState: false,
  672. wasOpenedAtLogin: false,
  673. wasOpenedAsHidden: false
  674. });
  675. });
  676. });
  677. ifit(isWin)('allows you to pass a custom executable and arguments', () => {
  678. app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: true });
  679. expect(app.getLoginItemSettings().openAtLogin).to.equal(false);
  680. const openAtLoginTrueEnabledTrue = app.getLoginItemSettings({
  681. path: updateExe,
  682. args: processStartArgs
  683. });
  684. expect(openAtLoginTrueEnabledTrue.openAtLogin).to.equal(true);
  685. expect(openAtLoginTrueEnabledTrue.executableWillLaunchAtLogin).to.equal(true);
  686. app.setLoginItemSettings({ openAtLogin: true, path: updateExe, args: processStartArgs, enabled: false });
  687. const openAtLoginTrueEnabledFalse = app.getLoginItemSettings({
  688. path: updateExe,
  689. args: processStartArgs
  690. });
  691. expect(openAtLoginTrueEnabledFalse.openAtLogin).to.equal(true);
  692. expect(openAtLoginTrueEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
  693. app.setLoginItemSettings({ openAtLogin: false, path: updateExe, args: processStartArgs, enabled: false });
  694. const openAtLoginFalseEnabledFalse = app.getLoginItemSettings({
  695. path: updateExe,
  696. args: processStartArgs
  697. });
  698. expect(openAtLoginFalseEnabledFalse.openAtLogin).to.equal(false);
  699. expect(openAtLoginFalseEnabledFalse.executableWillLaunchAtLogin).to.equal(false);
  700. });
  701. ifit(isWin)('allows you to pass a custom name', () => {
  702. app.setLoginItemSettings({ openAtLogin: true });
  703. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false });
  704. expect(app.getLoginItemSettings()).to.deep.equal({
  705. openAtLogin: true,
  706. openAsHidden: false,
  707. wasOpenedAtLogin: false,
  708. wasOpenedAsHidden: false,
  709. restoreState: false,
  710. executableWillLaunchAtLogin: true,
  711. launchItems: [{
  712. name: 'additionalEntry',
  713. path: process.execPath,
  714. args: [],
  715. scope: 'user',
  716. enabled: false
  717. }, {
  718. name: 'electron.app.Electron',
  719. path: process.execPath,
  720. args: [],
  721. scope: 'user',
  722. enabled: true
  723. }]
  724. });
  725. app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
  726. expect(app.getLoginItemSettings()).to.deep.equal({
  727. openAtLogin: true,
  728. openAsHidden: false,
  729. wasOpenedAtLogin: false,
  730. wasOpenedAsHidden: false,
  731. restoreState: false,
  732. executableWillLaunchAtLogin: true,
  733. launchItems: [{
  734. name: 'electron.app.Electron',
  735. path: process.execPath,
  736. args: [],
  737. scope: 'user',
  738. enabled: true
  739. }]
  740. });
  741. });
  742. ifit(isWin)('finds launch items independent of args', () => {
  743. app.setLoginItemSettings({ openAtLogin: true, args: ['arg1'] });
  744. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg2'] });
  745. expect(app.getLoginItemSettings()).to.deep.equal({
  746. openAtLogin: false,
  747. openAsHidden: false,
  748. wasOpenedAtLogin: false,
  749. wasOpenedAsHidden: false,
  750. restoreState: false,
  751. executableWillLaunchAtLogin: true,
  752. launchItems: [{
  753. name: 'additionalEntry',
  754. path: process.execPath,
  755. args: ['arg2'],
  756. scope: 'user',
  757. enabled: false
  758. }, {
  759. name: 'electron.app.Electron',
  760. path: process.execPath,
  761. args: ['arg1'],
  762. scope: 'user',
  763. enabled: true
  764. }]
  765. });
  766. });
  767. ifit(isWin)('finds launch items independent of path quotation or casing', () => {
  768. const expectation = {
  769. openAtLogin: false,
  770. openAsHidden: false,
  771. wasOpenedAtLogin: false,
  772. wasOpenedAsHidden: false,
  773. restoreState: false,
  774. executableWillLaunchAtLogin: true,
  775. launchItems: [{
  776. name: 'additionalEntry',
  777. path: 'C:\\electron\\myapp.exe',
  778. args: ['arg1'],
  779. scope: 'user',
  780. enabled: true
  781. }]
  782. };
  783. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: 'C:\\electron\\myapp.exe', args: ['arg1'] });
  784. expect(app.getLoginItemSettings({ path: '"C:\\electron\\MYAPP.exe"' })).to.deep.equal(expectation);
  785. app.setLoginItemSettings({ openAtLogin: false, name: 'additionalEntry' });
  786. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, path: '"C:\\electron\\MYAPP.exe"', args: ['arg1'] });
  787. expect(app.getLoginItemSettings({ path: 'C:\\electron\\myapp.exe' })).to.deep.equal({
  788. ...expectation,
  789. launchItems: [
  790. {
  791. name: 'additionalEntry',
  792. path: 'C:\\electron\\MYAPP.exe',
  793. args: ['arg1'],
  794. scope: 'user',
  795. enabled: true
  796. }
  797. ]
  798. });
  799. });
  800. ifit(isWin)('detects disabled by TaskManager', async () => {
  801. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: true, args: ['arg1'] });
  802. const appProcess = cp.spawn('reg', [...regAddArgs, '030000000000000000000000']);
  803. await once(appProcess, 'exit');
  804. expect(app.getLoginItemSettings()).to.deep.equal({
  805. openAtLogin: false,
  806. openAsHidden: false,
  807. wasOpenedAtLogin: false,
  808. wasOpenedAsHidden: false,
  809. restoreState: false,
  810. executableWillLaunchAtLogin: false,
  811. launchItems: [{
  812. name: 'additionalEntry',
  813. path: process.execPath,
  814. args: ['arg1'],
  815. scope: 'user',
  816. enabled: false
  817. }]
  818. });
  819. });
  820. ifit(isWin)('detects enabled by TaskManager', async () => {
  821. const expectation = {
  822. openAtLogin: false,
  823. openAsHidden: false,
  824. wasOpenedAtLogin: false,
  825. wasOpenedAsHidden: false,
  826. restoreState: false,
  827. executableWillLaunchAtLogin: true,
  828. launchItems: [{
  829. name: 'additionalEntry',
  830. path: process.execPath,
  831. args: ['arg1'],
  832. scope: 'user',
  833. enabled: true
  834. }]
  835. };
  836. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
  837. let appProcess = cp.spawn('reg', [...regAddArgs, '020000000000000000000000']);
  838. await once(appProcess, 'exit');
  839. expect(app.getLoginItemSettings()).to.deep.equal(expectation);
  840. app.setLoginItemSettings({ openAtLogin: true, name: 'additionalEntry', enabled: false, args: ['arg1'] });
  841. appProcess = cp.spawn('reg', [...regAddArgs, '000000000000000000000000']);
  842. await once(appProcess, 'exit');
  843. expect(app.getLoginItemSettings()).to.deep.equal(expectation);
  844. });
  845. });
  846. ifdescribe(process.platform !== 'linux')('accessibilitySupportEnabled property', () => {
  847. it('with properties', () => {
  848. it('can set accessibility support enabled', () => {
  849. expect(app.accessibilitySupportEnabled).to.eql(false);
  850. app.accessibilitySupportEnabled = true;
  851. expect(app.accessibilitySupportEnabled).to.eql(true);
  852. });
  853. });
  854. it('with functions', () => {
  855. it('can set accessibility support enabled', () => {
  856. expect(app.isAccessibilitySupportEnabled()).to.eql(false);
  857. app.setAccessibilitySupportEnabled(true);
  858. expect(app.isAccessibilitySupportEnabled()).to.eql(true);
  859. });
  860. });
  861. });
  862. describe('getAppPath', () => {
  863. it('works for directories with package.json', async () => {
  864. const { appPath } = await runTestApp('app-path');
  865. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path'));
  866. });
  867. it('works for directories with index.js', async () => {
  868. const { appPath } = await runTestApp('app-path/lib');
  869. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  870. });
  871. it('works for files without extension', async () => {
  872. const { appPath } = await runTestApp('app-path/lib/index');
  873. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  874. });
  875. it('works for files', async () => {
  876. const { appPath } = await runTestApp('app-path/lib/index.js');
  877. expect(appPath).to.equal(path.resolve(fixturesPath, 'api/app-path/lib'));
  878. });
  879. });
  880. describe('getPath(name)', () => {
  881. it('returns paths that exist', () => {
  882. const paths = [
  883. fs.existsSync(app.getPath('exe')),
  884. fs.existsSync(app.getPath('home')),
  885. fs.existsSync(app.getPath('temp'))
  886. ];
  887. expect(paths).to.deep.equal([true, true, true]);
  888. });
  889. it('throws an error when the name is invalid', () => {
  890. expect(() => {
  891. app.getPath('does-not-exist' as any);
  892. }).to.throw(/Failed to get 'does-not-exist' path/);
  893. });
  894. it('returns the overridden path', () => {
  895. app.setPath('music', __dirname);
  896. expect(app.getPath('music')).to.equal(__dirname);
  897. });
  898. if (process.platform === 'win32') {
  899. it('gets the folder for recent files', () => {
  900. const recent = app.getPath('recent');
  901. // We expect that one of our test machines have overridden this
  902. // to be something crazy, it'll always include the word "Recent"
  903. // unless people have been registry-hacking like crazy
  904. expect(recent).to.include('Recent');
  905. });
  906. it('can override the recent files path', () => {
  907. app.setPath('recent', 'C:\\fake-path');
  908. expect(app.getPath('recent')).to.equal('C:\\fake-path');
  909. });
  910. }
  911. it('uses the app name in getPath(userData)', () => {
  912. expect(app.getPath('userData')).to.include(app.name);
  913. });
  914. });
  915. describe('setPath(name, path)', () => {
  916. it('throws when a relative path is passed', () => {
  917. const badPath = 'hey/hi/hello';
  918. expect(() => {
  919. app.setPath('music', badPath);
  920. }).to.throw(/Path must be absolute/);
  921. });
  922. it('does not create a new directory by default', () => {
  923. const badPath = path.join(__dirname, 'music');
  924. expect(fs.existsSync(badPath)).to.be.false();
  925. app.setPath('music', badPath);
  926. expect(fs.existsSync(badPath)).to.be.false();
  927. expect(() => { app.getPath(badPath as any); }).to.throw();
  928. });
  929. describe('sessionData', () => {
  930. const appPath = path.join(__dirname, 'fixtures', 'apps', 'set-path');
  931. const appName = JSON.parse(fs.readFileSync(path.join(appPath, 'package.json'), 'utf8')).name;
  932. const userDataPath = path.join(app.getPath('appData'), appName);
  933. const tempBrowserDataPath = path.join(app.getPath('temp'), appName);
  934. const sessionFiles = [
  935. 'Preferences',
  936. 'Code Cache',
  937. 'Local Storage',
  938. 'IndexedDB',
  939. 'Service Worker'
  940. ];
  941. const hasSessionFiles = (dir: string) => {
  942. for (const file of sessionFiles) {
  943. if (!fs.existsSync(path.join(dir, file))) {
  944. return false;
  945. }
  946. }
  947. return true;
  948. };
  949. beforeEach(() => {
  950. fs.rmSync(userDataPath, { force: true, recursive: true });
  951. fs.rmSync(tempBrowserDataPath, { force: true, recursive: true });
  952. });
  953. it('writes to userData by default', () => {
  954. expect(hasSessionFiles(userDataPath)).to.equal(false);
  955. cp.spawnSync(process.execPath, [appPath]);
  956. expect(hasSessionFiles(userDataPath)).to.equal(true);
  957. });
  958. it('can be changed', () => {
  959. expect(hasSessionFiles(userDataPath)).to.equal(false);
  960. cp.spawnSync(process.execPath, [appPath, 'sessionData', tempBrowserDataPath]);
  961. expect(hasSessionFiles(userDataPath)).to.equal(false);
  962. expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
  963. });
  964. it('changing userData affects default sessionData', () => {
  965. expect(hasSessionFiles(userDataPath)).to.equal(false);
  966. cp.spawnSync(process.execPath, [appPath, 'userData', tempBrowserDataPath]);
  967. expect(hasSessionFiles(userDataPath)).to.equal(false);
  968. expect(hasSessionFiles(tempBrowserDataPath)).to.equal(true);
  969. });
  970. });
  971. });
  972. describe('setAppLogsPath(path)', () => {
  973. it('throws when a relative path is passed', () => {
  974. const badPath = 'hey/hi/hello';
  975. expect(() => {
  976. app.setAppLogsPath(badPath);
  977. }).to.throw(/Path must be absolute/);
  978. });
  979. });
  980. ifdescribe(process.platform !== 'linux')('select-client-certificate event', () => {
  981. let w: BrowserWindow;
  982. before(function () {
  983. session.fromPartition('empty-certificate').setCertificateVerifyProc((req, cb) => { cb(0); });
  984. });
  985. beforeEach(() => {
  986. w = new BrowserWindow({
  987. show: false,
  988. webPreferences: {
  989. nodeIntegration: true,
  990. partition: 'empty-certificate'
  991. }
  992. });
  993. });
  994. afterEach(() => closeWindow(w).then(() => { w = null as any; }));
  995. after(() => session.fromPartition('empty-certificate').setCertificateVerifyProc(null));
  996. it('can respond with empty certificate list', async () => {
  997. app.once('select-client-certificate', function (event, webContents, url, list, callback) {
  998. console.log('select-client-certificate emitted');
  999. event.preventDefault();
  1000. callback();
  1001. });
  1002. await w.webContents.loadURL(secureUrl);
  1003. expect(w.webContents.getTitle()).to.equal('denied');
  1004. });
  1005. });
  1006. ifdescribe(process.platform === 'win32')('setAsDefaultProtocolClient(protocol, path, args)', () => {
  1007. const protocol = 'electron-test';
  1008. const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  1009. const processStartArgs = [
  1010. '--processStart', `"${path.basename(process.execPath)}"`,
  1011. '--process-start-args', '"--hidden"'
  1012. ];
  1013. let Winreg: any;
  1014. let classesKey: any;
  1015. before(function () {
  1016. Winreg = require('winreg');
  1017. classesKey = new Winreg({
  1018. hive: Winreg.HKCU,
  1019. key: '\\Software\\Classes\\'
  1020. });
  1021. });
  1022. after(function (done) {
  1023. if (process.platform !== 'win32') {
  1024. done();
  1025. } else {
  1026. const protocolKey = new Winreg({
  1027. hive: Winreg.HKCU,
  1028. key: `\\Software\\Classes\\${protocol}`
  1029. });
  1030. // The last test leaves the registry dirty,
  1031. // delete the protocol key for those of us who test at home
  1032. protocolKey.destroy(() => done());
  1033. }
  1034. });
  1035. beforeEach(() => {
  1036. app.removeAsDefaultProtocolClient(protocol);
  1037. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1038. });
  1039. afterEach(() => {
  1040. app.removeAsDefaultProtocolClient(protocol);
  1041. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1042. app.removeAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1043. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  1044. });
  1045. it('sets the app as the default protocol client', () => {
  1046. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1047. app.setAsDefaultProtocolClient(protocol);
  1048. expect(app.isDefaultProtocolClient(protocol)).to.equal(true);
  1049. });
  1050. it('allows a custom path and args to be specified', () => {
  1051. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(false);
  1052. app.setAsDefaultProtocolClient(protocol, updateExe, processStartArgs);
  1053. expect(app.isDefaultProtocolClient(protocol, updateExe, processStartArgs)).to.equal(true);
  1054. expect(app.isDefaultProtocolClient(protocol)).to.equal(false);
  1055. });
  1056. it('creates a registry entry for the protocol class', async () => {
  1057. app.setAsDefaultProtocolClient(protocol);
  1058. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1059. const exists = keys.some(key => key.key.includes(protocol));
  1060. expect(exists).to.equal(true);
  1061. });
  1062. it('completely removes a registry entry for the protocol class', async () => {
  1063. app.setAsDefaultProtocolClient(protocol);
  1064. app.removeAsDefaultProtocolClient(protocol);
  1065. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1066. const exists = keys.some(key => key.key.includes(protocol));
  1067. expect(exists).to.equal(false);
  1068. });
  1069. it('only unsets a class registry key if it contains other data', async () => {
  1070. app.setAsDefaultProtocolClient(protocol);
  1071. const protocolKey = new Winreg({
  1072. hive: Winreg.HKCU,
  1073. key: `\\Software\\Classes\\${protocol}`
  1074. });
  1075. await promisify(protocolKey.set).call(protocolKey, 'test-value', 'REG_BINARY', '123');
  1076. app.removeAsDefaultProtocolClient(protocol);
  1077. const keys = await promisify(classesKey.keys).call(classesKey) as any[];
  1078. const exists = keys.some(key => key.key.includes(protocol));
  1079. expect(exists).to.equal(true);
  1080. });
  1081. it('sets the default client such that getApplicationNameForProtocol returns Electron', () => {
  1082. app.setAsDefaultProtocolClient(protocol);
  1083. expect(app.getApplicationNameForProtocol(`${protocol}://`)).to.equal('Electron');
  1084. });
  1085. });
  1086. describe('getApplicationNameForProtocol()', () => {
  1087. // TODO: Linux CI doesn't have registered http & https handlers
  1088. ifit(!(process.env.CI && process.platform === 'linux'))('returns application names for common protocols', function () {
  1089. // We can't expect particular app names here, but these protocols should
  1090. // at least have _something_ registered. Except on our Linux CI
  1091. // environment apparently.
  1092. const protocols = [
  1093. 'http://',
  1094. 'https://'
  1095. ];
  1096. for (const protocol of protocols) {
  1097. expect(app.getApplicationNameForProtocol(protocol)).to.not.equal('');
  1098. }
  1099. });
  1100. it('returns an empty string for a bogus protocol', () => {
  1101. expect(app.getApplicationNameForProtocol('bogus-protocol://')).to.equal('');
  1102. });
  1103. });
  1104. ifdescribe(process.platform !== 'linux')('getApplicationInfoForProtocol()', () => {
  1105. it('returns promise rejection for a bogus protocol', async function () {
  1106. await expect(
  1107. app.getApplicationInfoForProtocol('bogus-protocol://')
  1108. ).to.eventually.be.rejectedWith(
  1109. 'Unable to retrieve installation path to app'
  1110. );
  1111. });
  1112. it('returns resolved promise with appPath, displayName and icon', async function () {
  1113. const appInfo = await app.getApplicationInfoForProtocol('https://');
  1114. expect(appInfo.path).not.to.be.undefined();
  1115. expect(appInfo.name).not.to.be.undefined();
  1116. expect(appInfo.icon).not.to.be.undefined();
  1117. });
  1118. });
  1119. describe('isDefaultProtocolClient()', () => {
  1120. it('returns false for a bogus protocol', () => {
  1121. expect(app.isDefaultProtocolClient('bogus-protocol://')).to.equal(false);
  1122. });
  1123. });
  1124. ifdescribe(process.platform === 'win32')('app launch through uri', () => {
  1125. it('does not launch for argument following a URL', async () => {
  1126. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1127. // App should exit with non 123 code.
  1128. const first = cp.spawn(process.execPath, [appPath, 'electron-test:?', 'abc']);
  1129. const [code] = await once(first, 'exit');
  1130. expect(code).to.not.equal(123);
  1131. });
  1132. it('launches successfully for argument following a file path', async () => {
  1133. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1134. // App should exit with code 123.
  1135. const first = cp.spawn(process.execPath, [appPath, 'e:\\abc', 'abc']);
  1136. const [code] = await once(first, 'exit');
  1137. expect(code).to.equal(123);
  1138. });
  1139. it('launches successfully for multiple URIs following --', async () => {
  1140. const appPath = path.join(fixturesPath, 'api', 'quit-app');
  1141. // App should exit with code 123.
  1142. const first = cp.spawn(process.execPath, [appPath, '--', 'http://electronjs.org', 'electron-test://testdata']);
  1143. const [code] = await once(first, 'exit');
  1144. expect(code).to.equal(123);
  1145. });
  1146. });
  1147. // FIXME Get these specs running on Linux CI
  1148. ifdescribe(process.platform !== 'linux')('getFileIcon() API', () => {
  1149. const iconPath = path.join(__dirname, 'fixtures/assets/icon.ico');
  1150. const sizes = {
  1151. small: 16,
  1152. normal: 32,
  1153. large: process.platform === 'win32' ? 32 : 48
  1154. };
  1155. it('fetches a non-empty icon', async () => {
  1156. const icon = await app.getFileIcon(iconPath);
  1157. expect(icon.isEmpty()).to.equal(false);
  1158. });
  1159. it('fetches normal icon size by default', async () => {
  1160. const icon = await app.getFileIcon(iconPath);
  1161. const size = icon.getSize();
  1162. expect(size.height).to.equal(sizes.normal);
  1163. expect(size.width).to.equal(sizes.normal);
  1164. });
  1165. describe('size option', () => {
  1166. it('fetches a small icon', async () => {
  1167. const icon = await app.getFileIcon(iconPath, { size: 'small' });
  1168. const size = icon.getSize();
  1169. expect(size.height).to.equal(sizes.small);
  1170. expect(size.width).to.equal(sizes.small);
  1171. });
  1172. it('fetches a normal icon', async () => {
  1173. const icon = await app.getFileIcon(iconPath, { size: 'normal' });
  1174. const size = icon.getSize();
  1175. expect(size.height).to.equal(sizes.normal);
  1176. expect(size.width).to.equal(sizes.normal);
  1177. });
  1178. it('fetches a large icon', async () => {
  1179. // macOS does not support large icons
  1180. if (process.platform === 'darwin') return;
  1181. const icon = await app.getFileIcon(iconPath, { size: 'large' });
  1182. const size = icon.getSize();
  1183. expect(size.height).to.equal(sizes.large);
  1184. expect(size.width).to.equal(sizes.large);
  1185. });
  1186. });
  1187. });
  1188. describe('getAppMetrics() API', () => {
  1189. it('returns memory and cpu stats of all running electron processes', () => {
  1190. const appMetrics = app.getAppMetrics();
  1191. expect(appMetrics).to.be.an('array').and.have.lengthOf.at.least(1, 'App memory info object is not > 0');
  1192. const types = [];
  1193. for (const entry of appMetrics) {
  1194. expect(entry.pid).to.be.above(0, 'pid is not > 0');
  1195. expect(entry.type).to.be.a('string').that.does.not.equal('');
  1196. expect(entry.creationTime).to.be.a('number').that.is.greaterThan(0);
  1197. types.push(entry.type);
  1198. expect(entry.cpu).to.have.ownProperty('percentCPUUsage').that.is.a('number');
  1199. expect(entry.cpu).to.have.ownProperty('idleWakeupsPerSecond').that.is.a('number');
  1200. expect(entry.memory).to.have.property('workingSetSize').that.is.greaterThan(0);
  1201. expect(entry.memory).to.have.property('peakWorkingSetSize').that.is.greaterThan(0);
  1202. if (entry.type === 'Utility' || entry.type === 'GPU') {
  1203. expect(entry.serviceName).to.be.a('string').that.does.not.equal('');
  1204. }
  1205. if (entry.type === 'Utility') {
  1206. expect(entry).to.have.property('name').that.is.a('string');
  1207. }
  1208. if (process.platform === 'win32') {
  1209. expect(entry.memory).to.have.property('privateBytes').that.is.greaterThan(0);
  1210. }
  1211. if (process.platform !== 'linux') {
  1212. expect(entry.sandboxed).to.be.a('boolean');
  1213. }
  1214. if (process.platform === 'win32') {
  1215. expect(entry.integrityLevel).to.be.a('string');
  1216. }
  1217. }
  1218. if (process.platform === 'darwin') {
  1219. expect(types).to.include('GPU');
  1220. }
  1221. expect(types).to.include('Browser');
  1222. });
  1223. });
  1224. describe('getGPUFeatureStatus() API', () => {
  1225. it('returns the graphic features statuses', () => {
  1226. const features = app.getGPUFeatureStatus();
  1227. expect(features).to.have.ownProperty('webgl').that.is.a('string');
  1228. expect(features).to.have.ownProperty('gpu_compositing').that.is.a('string');
  1229. });
  1230. });
  1231. // FIXME https://github.com/electron/electron/issues/24224
  1232. ifdescribe(process.platform !== 'linux')('getGPUInfo() API', () => {
  1233. const appPath = path.join(fixturesPath, 'api', 'gpu-info.js');
  1234. const getGPUInfo = async (type: string) => {
  1235. const appProcess = cp.spawn(process.execPath, [appPath, type]);
  1236. let gpuInfoData = '';
  1237. let errorData = '';
  1238. appProcess.stdout.on('data', (data) => {
  1239. gpuInfoData += data;
  1240. });
  1241. appProcess.stderr.on('data', (data) => {
  1242. errorData += data;
  1243. });
  1244. const [exitCode] = await once(appProcess, 'exit');
  1245. if (exitCode === 0) {
  1246. try {
  1247. const [, json] = /HERE COMES THE JSON: (.+) AND THERE IT WAS/.exec(gpuInfoData)!;
  1248. // return info data on successful exit
  1249. return JSON.parse(json);
  1250. } catch (e) {
  1251. console.error('Failed to interpret the following as JSON:');
  1252. console.error(gpuInfoData);
  1253. throw e;
  1254. }
  1255. } else {
  1256. // return error if not clean exit
  1257. throw new Error(errorData);
  1258. }
  1259. };
  1260. const verifyBasicGPUInfo = async (gpuInfo: any) => {
  1261. // Devices information is always present in the available info.
  1262. expect(gpuInfo).to.have.ownProperty('gpuDevice')
  1263. .that.is.an('array')
  1264. .and.does.not.equal([]);
  1265. const device = gpuInfo.gpuDevice[0];
  1266. expect(device).to.be.an('object')
  1267. .and.to.have.property('deviceId')
  1268. .that.is.a('number')
  1269. .not.lessThan(0);
  1270. };
  1271. it('succeeds with basic GPUInfo', async () => {
  1272. const gpuInfo = await getGPUInfo('basic');
  1273. await verifyBasicGPUInfo(gpuInfo);
  1274. });
  1275. it('succeeds with complete GPUInfo', async () => {
  1276. const completeInfo = await getGPUInfo('complete');
  1277. if (process.platform === 'linux') {
  1278. // For linux and macOS complete info is same as basic info
  1279. await verifyBasicGPUInfo(completeInfo);
  1280. const basicInfo = await getGPUInfo('basic');
  1281. expect(completeInfo).to.deep.equal(basicInfo);
  1282. } else {
  1283. // Gl version is present in the complete info.
  1284. expect(completeInfo).to.have.ownProperty('auxAttributes')
  1285. .that.is.an('object');
  1286. if (completeInfo.gpuDevice.active) {
  1287. expect(completeInfo.auxAttributes).to.have.ownProperty('glVersion')
  1288. .that.is.a('string')
  1289. .and.does.not.equal([]);
  1290. }
  1291. }
  1292. });
  1293. it('fails for invalid info_type', () => {
  1294. const invalidType = 'invalid';
  1295. const expectedErrorMessage = "Invalid info type. Use 'basic' or 'complete'";
  1296. return expect(app.getGPUInfo(invalidType as any)).to.eventually.be.rejectedWith(expectedErrorMessage);
  1297. });
  1298. });
  1299. ifdescribe(!(process.platform === 'linux' && (process.arch === 'arm64' || process.arch === 'arm')))('sandbox options', () => {
  1300. let appProcess: cp.ChildProcess = null as any;
  1301. let server: net.Server = null as any;
  1302. const socketPath = process.platform === 'win32' ? '\\\\.\\pipe\\electron-mixed-sandbox' : '/tmp/electron-mixed-sandbox';
  1303. beforeEach(function (done) {
  1304. fs.unlink(socketPath, () => {
  1305. server = net.createServer();
  1306. server.listen(socketPath);
  1307. done();
  1308. });
  1309. });
  1310. afterEach(done => {
  1311. if (appProcess != null) appProcess.kill();
  1312. if (server) {
  1313. server.close(() => {
  1314. if (process.platform === 'win32') {
  1315. done();
  1316. } else {
  1317. fs.unlink(socketPath, () => done());
  1318. }
  1319. });
  1320. } else {
  1321. done();
  1322. }
  1323. });
  1324. describe('when app.enableSandbox() is called', () => {
  1325. it('adds --enable-sandbox to all renderer processes', done => {
  1326. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1327. appProcess = cp.spawn(process.execPath, [appPath, '--app-enable-sandbox'], { stdio: 'inherit' });
  1328. server.once('error', error => { done(error); });
  1329. server.on('connection', client => {
  1330. client.once('data', (data) => {
  1331. const argv = JSON.parse(data.toString());
  1332. expect(argv.sandbox).to.include('--enable-sandbox');
  1333. expect(argv.sandbox).to.not.include('--no-sandbox');
  1334. expect(argv.noSandbox).to.include('--enable-sandbox');
  1335. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1336. expect(argv.noSandboxDevtools).to.equal(true);
  1337. expect(argv.sandboxDevtools).to.equal(true);
  1338. done();
  1339. });
  1340. });
  1341. });
  1342. });
  1343. describe('when the app is launched with --enable-sandbox', () => {
  1344. it('adds --enable-sandbox to all renderer processes', done => {
  1345. const appPath = path.join(fixturesPath, 'api', 'mixed-sandbox-app');
  1346. appProcess = cp.spawn(process.execPath, [appPath, '--enable-sandbox'], { stdio: 'inherit' });
  1347. server.once('error', error => { done(error); });
  1348. server.on('connection', client => {
  1349. client.once('data', data => {
  1350. const argv = JSON.parse(data.toString());
  1351. expect(argv.sandbox).to.include('--enable-sandbox');
  1352. expect(argv.sandbox).to.not.include('--no-sandbox');
  1353. expect(argv.noSandbox).to.include('--enable-sandbox');
  1354. expect(argv.noSandbox).to.not.include('--no-sandbox');
  1355. expect(argv.noSandboxDevtools).to.equal(true);
  1356. expect(argv.sandboxDevtools).to.equal(true);
  1357. done();
  1358. });
  1359. });
  1360. });
  1361. });
  1362. });
  1363. describe('disableDomainBlockingFor3DAPIs() API', () => {
  1364. it('throws when called after app is ready', () => {
  1365. expect(() => {
  1366. app.disableDomainBlockingFor3DAPIs();
  1367. }).to.throw(/before app is ready/);
  1368. });
  1369. });
  1370. ifdescribe(process.platform === 'darwin')('app hide and show API', () => {
  1371. describe('app.isHidden', () => {
  1372. it('returns true when the app is hidden', async () => {
  1373. app.hide();
  1374. await expect(
  1375. waitUntil(() => app.isHidden())
  1376. ).to.eventually.be.fulfilled();
  1377. });
  1378. it('returns false when the app is shown', async () => {
  1379. app.show();
  1380. await expect(
  1381. waitUntil(() => !app.isHidden())
  1382. ).to.eventually.be.fulfilled();
  1383. });
  1384. });
  1385. });
  1386. ifdescribe(process.platform === 'darwin')('dock APIs', () => {
  1387. after(async () => {
  1388. await app.dock.show();
  1389. });
  1390. describe('dock.setMenu', () => {
  1391. it('can be retrieved via dock.getMenu', () => {
  1392. expect(app.dock.getMenu()).to.equal(null);
  1393. const menu = new Menu();
  1394. app.dock.setMenu(menu);
  1395. expect(app.dock.getMenu()).to.equal(menu);
  1396. });
  1397. it('keeps references to the menu', () => {
  1398. app.dock.setMenu(new Menu());
  1399. const v8Util = process._linkedBinding('electron_common_v8_util');
  1400. v8Util.requestGarbageCollectionForTesting();
  1401. });
  1402. });
  1403. describe('dock.setIcon', () => {
  1404. it('throws a descriptive error for a bad icon path', () => {
  1405. const badPath = path.resolve('I', 'Do', 'Not', 'Exist');
  1406. expect(() => {
  1407. app.dock.setIcon(badPath);
  1408. }).to.throw(/Failed to load image from path (.+)/);
  1409. });
  1410. });
  1411. describe('dock.bounce', () => {
  1412. it('should return -1 for unknown bounce type', () => {
  1413. expect(app.dock.bounce('bad type' as any)).to.equal(-1);
  1414. });
  1415. it('should return a positive number for informational type', () => {
  1416. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1417. if (!appHasFocus) {
  1418. expect(app.dock.bounce('informational')).to.be.at.least(0);
  1419. }
  1420. });
  1421. it('should return a positive number for critical type', () => {
  1422. const appHasFocus = !!BrowserWindow.getFocusedWindow();
  1423. if (!appHasFocus) {
  1424. expect(app.dock.bounce('critical')).to.be.at.least(0);
  1425. }
  1426. });
  1427. });
  1428. describe('dock.cancelBounce', () => {
  1429. it('should not throw', () => {
  1430. app.dock.cancelBounce(app.dock.bounce('critical'));
  1431. });
  1432. });
  1433. describe('dock.setBadge', () => {
  1434. after(() => {
  1435. app.dock.setBadge('');
  1436. });
  1437. it('should not throw', () => {
  1438. app.dock.setBadge('1');
  1439. });
  1440. it('should be retrievable via getBadge', () => {
  1441. app.dock.setBadge('test');
  1442. expect(app.dock.getBadge()).to.equal('test');
  1443. });
  1444. });
  1445. describe('dock.hide', () => {
  1446. it('should not throw', () => {
  1447. app.dock.hide();
  1448. expect(app.dock.isVisible()).to.equal(false);
  1449. });
  1450. });
  1451. // Note that dock.show tests should run after dock.hide tests, to work
  1452. // around a bug of macOS.
  1453. // See https://github.com/electron/electron/pull/25269 for more.
  1454. describe('dock.show', () => {
  1455. it('should not throw', () => {
  1456. return app.dock.show().then(() => {
  1457. expect(app.dock.isVisible()).to.equal(true);
  1458. });
  1459. });
  1460. it('returns a Promise', () => {
  1461. expect(app.dock.show()).to.be.a('promise');
  1462. });
  1463. it('eventually fulfills', async () => {
  1464. await expect(app.dock.show()).to.eventually.be.fulfilled.equal(undefined);
  1465. });
  1466. });
  1467. });
  1468. describe('whenReady', () => {
  1469. it('returns a Promise', () => {
  1470. expect(app.whenReady()).to.be.a('promise');
  1471. });
  1472. it('becomes fulfilled if the app is already ready', async () => {
  1473. expect(app.isReady()).to.equal(true);
  1474. await expect(app.whenReady()).to.be.eventually.fulfilled.equal(undefined);
  1475. });
  1476. });
  1477. describe('app.applicationMenu', () => {
  1478. it('has the applicationMenu property', () => {
  1479. expect(app).to.have.property('applicationMenu');
  1480. });
  1481. });
  1482. describe('commandLine.hasSwitch', () => {
  1483. it('returns true when present', () => {
  1484. app.commandLine.appendSwitch('foobar1');
  1485. expect(app.commandLine.hasSwitch('foobar1')).to.equal(true);
  1486. });
  1487. it('returns false when not present', () => {
  1488. expect(app.commandLine.hasSwitch('foobar2')).to.equal(false);
  1489. });
  1490. });
  1491. describe('commandLine.hasSwitch (existing argv)', () => {
  1492. it('returns true when present', async () => {
  1493. const { hasSwitch } = await runTestApp('command-line', '--foobar');
  1494. expect(hasSwitch).to.equal(true);
  1495. });
  1496. it('returns false when not present', async () => {
  1497. const { hasSwitch } = await runTestApp('command-line');
  1498. expect(hasSwitch).to.equal(false);
  1499. });
  1500. });
  1501. describe('commandLine.getSwitchValue', () => {
  1502. it('returns the value when present', () => {
  1503. app.commandLine.appendSwitch('foobar', 'æøåü');
  1504. expect(app.commandLine.getSwitchValue('foobar')).to.equal('æøåü');
  1505. });
  1506. it('returns an empty string when present without value', () => {
  1507. app.commandLine.appendSwitch('foobar1');
  1508. expect(app.commandLine.getSwitchValue('foobar1')).to.equal('');
  1509. });
  1510. it('returns an empty string when not present', () => {
  1511. expect(app.commandLine.getSwitchValue('foobar2')).to.equal('');
  1512. });
  1513. });
  1514. describe('commandLine.getSwitchValue (existing argv)', () => {
  1515. it('returns the value when present', async () => {
  1516. const { getSwitchValue } = await runTestApp('command-line', '--foobar=test');
  1517. expect(getSwitchValue).to.equal('test');
  1518. });
  1519. it('returns an empty string when present without value', async () => {
  1520. const { getSwitchValue } = await runTestApp('command-line', '--foobar');
  1521. expect(getSwitchValue).to.equal('');
  1522. });
  1523. it('returns an empty string when not present', async () => {
  1524. const { getSwitchValue } = await runTestApp('command-line');
  1525. expect(getSwitchValue).to.equal('');
  1526. });
  1527. });
  1528. describe('commandLine.removeSwitch', () => {
  1529. it('no-ops a non-existent switch', async () => {
  1530. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1531. app.commandLine.removeSwitch('foobar3');
  1532. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1533. });
  1534. it('removes an existing switch', async () => {
  1535. app.commandLine.appendSwitch('foobar3', 'test');
  1536. expect(app.commandLine.hasSwitch('foobar3')).to.equal(true);
  1537. app.commandLine.removeSwitch('foobar3');
  1538. expect(app.commandLine.hasSwitch('foobar3')).to.equal(false);
  1539. });
  1540. });
  1541. ifdescribe(process.platform === 'darwin')('app.setSecureKeyboardEntryEnabled', () => {
  1542. it('changes Secure Keyboard Entry is enabled', () => {
  1543. app.setSecureKeyboardEntryEnabled(true);
  1544. expect(app.isSecureKeyboardEntryEnabled()).to.equal(true);
  1545. app.setSecureKeyboardEntryEnabled(false);
  1546. expect(app.isSecureKeyboardEntryEnabled()).to.equal(false);
  1547. });
  1548. });
  1549. describe('configureHostResolver', () => {
  1550. after(() => {
  1551. // Returns to the default configuration.
  1552. app.configureHostResolver({});
  1553. });
  1554. it('fails on bad arguments', () => {
  1555. expect(() => {
  1556. (app.configureHostResolver as any)();
  1557. }).to.throw();
  1558. expect(() => {
  1559. app.configureHostResolver({
  1560. secureDnsMode: 'notAValidValue' as any
  1561. });
  1562. }).to.throw();
  1563. expect(() => {
  1564. app.configureHostResolver({
  1565. secureDnsServers: [123 as any]
  1566. });
  1567. }).to.throw();
  1568. });
  1569. it('affects dns lookup behavior', async () => {
  1570. // 1. resolve a domain name to check that things are working
  1571. await expect(new Promise((resolve, reject) => {
  1572. electronNet.request({
  1573. method: 'HEAD',
  1574. url: 'https://www.electronjs.org'
  1575. }).on('response', resolve)
  1576. .on('error', reject)
  1577. .end();
  1578. })).to.eventually.be.fulfilled();
  1579. // 2. change the host resolver configuration to something that will
  1580. // always fail
  1581. app.configureHostResolver({
  1582. secureDnsMode: 'secure',
  1583. secureDnsServers: ['https://127.0.0.1:1234']
  1584. });
  1585. // 3. check that resolving domain names now fails
  1586. await expect(new Promise((resolve, reject) => {
  1587. electronNet.request({
  1588. method: 'HEAD',
  1589. // Needs to be a slightly different domain to above, otherwise the
  1590. // response will come from the cache.
  1591. url: 'https://electronjs.org'
  1592. }).on('response', resolve)
  1593. .on('error', reject)
  1594. .end();
  1595. })).to.eventually.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
  1596. });
  1597. });
  1598. describe('about panel', () => {
  1599. it('app.setAboutPanelOptions() does not crash', () => {
  1600. app.setAboutPanelOptions({
  1601. applicationName: 'electron!!',
  1602. version: '1.2.3'
  1603. });
  1604. });
  1605. it('app.showAboutPanel() does not crash & runs asynchronously', () => {
  1606. app.showAboutPanel();
  1607. });
  1608. });
  1609. describe('app.setProxy(options)', () => {
  1610. let server: http.Server;
  1611. afterEach(async () => {
  1612. if (server) {
  1613. server.close();
  1614. }
  1615. await app.setProxy({ mode: 'direct' as const });
  1616. });
  1617. it('allows configuring proxy settings', async () => {
  1618. const config = { proxyRules: 'http=myproxy:80' };
  1619. await app.setProxy(config);
  1620. const proxy = await app.resolveProxy('http://example.com/');
  1621. expect(proxy).to.equal('PROXY myproxy:80');
  1622. });
  1623. it('allows removing the implicit bypass rules for localhost', async () => {
  1624. const config = {
  1625. proxyRules: 'http=myproxy:80',
  1626. proxyBypassRules: '<-loopback>'
  1627. };
  1628. await app.setProxy(config);
  1629. const proxy = await app.resolveProxy('http://localhost');
  1630. expect(proxy).to.equal('PROXY myproxy:80');
  1631. });
  1632. it('allows configuring proxy settings with pacScript', async () => {
  1633. server = http.createServer((req, res) => {
  1634. const pac = `
  1635. function FindProxyForURL(url, host) {
  1636. return "PROXY myproxy:8132";
  1637. }
  1638. `;
  1639. res.writeHead(200, {
  1640. 'Content-Type': 'application/x-ns-proxy-autoconfig'
  1641. });
  1642. res.end(pac);
  1643. });
  1644. const { url } = await listen(server);
  1645. {
  1646. const config = { pacScript: url };
  1647. await app.setProxy(config);
  1648. const proxy = await app.resolveProxy('https://google.com');
  1649. expect(proxy).to.equal('PROXY myproxy:8132');
  1650. }
  1651. {
  1652. const config = { mode: 'pac_script' as any, pacScript: url };
  1653. await app.setProxy(config);
  1654. const proxy = await app.resolveProxy('https://google.com');
  1655. expect(proxy).to.equal('PROXY myproxy:8132');
  1656. }
  1657. });
  1658. it('allows bypassing proxy settings', async () => {
  1659. const config = {
  1660. proxyRules: 'http=myproxy:80',
  1661. proxyBypassRules: '<local>'
  1662. };
  1663. await app.setProxy(config);
  1664. const proxy = await app.resolveProxy('http://example/');
  1665. expect(proxy).to.equal('DIRECT');
  1666. });
  1667. it('allows configuring proxy settings with mode `direct`', async () => {
  1668. const config = { mode: 'direct' as const, proxyRules: 'http=myproxy:80' };
  1669. await app.setProxy(config);
  1670. const proxy = await app.resolveProxy('http://example.com/');
  1671. expect(proxy).to.equal('DIRECT');
  1672. });
  1673. it('allows configuring proxy settings with mode `auto_detect`', async () => {
  1674. const config = { mode: 'auto_detect' as const };
  1675. await app.setProxy(config);
  1676. });
  1677. it('allows configuring proxy settings with mode `pac_script`', async () => {
  1678. const config = { mode: 'pac_script' as const };
  1679. await app.setProxy(config);
  1680. const proxy = await app.resolveProxy('http://example.com/');
  1681. expect(proxy).to.equal('DIRECT');
  1682. });
  1683. it('allows configuring proxy settings with mode `fixed_servers`', async () => {
  1684. const config = { mode: 'fixed_servers' as const, proxyRules: 'http=myproxy:80' };
  1685. await app.setProxy(config);
  1686. const proxy = await app.resolveProxy('http://example.com/');
  1687. expect(proxy).to.equal('PROXY myproxy:80');
  1688. });
  1689. it('allows configuring proxy settings with mode `system`', async () => {
  1690. const config = { mode: 'system' as const };
  1691. await app.setProxy(config);
  1692. });
  1693. it('disallows configuring proxy settings with mode `invalid`', async () => {
  1694. const config = { mode: 'invalid' as any };
  1695. await expect(app.setProxy(config)).to.eventually.be.rejectedWith(/Invalid mode/);
  1696. });
  1697. it('impacts proxy for requests made from utility process', async () => {
  1698. const utilityFixturePath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process', 'api-net-spec.js');
  1699. const fn = async () => {
  1700. const urlRequest = electronNet.request('http://example.com/');
  1701. const response = await getResponse(urlRequest);
  1702. expect(response.statusCode).to.equal(200);
  1703. const message = await collectStreamBody(response);
  1704. expect(message).to.equal('ok from proxy\n');
  1705. };
  1706. server = http.createServer((req, res) => {
  1707. res.writeHead(200);
  1708. res.end('ok from proxy\n');
  1709. });
  1710. const { port, hostname } = await listen(server);
  1711. const config = { mode: 'fixed_servers' as const, proxyRules: `http=${hostname}:${port}` };
  1712. await app.setProxy(config);
  1713. const proxy = await app.resolveProxy('http://example.com/');
  1714. expect(proxy).to.equal(`PROXY ${hostname}:${port}`);
  1715. const child = utilityProcess.fork(utilityFixturePath, [], {
  1716. execArgv: ['--expose-gc']
  1717. });
  1718. child.postMessage({ fn: `(${fn})()` });
  1719. const [data] = await once(child, 'message');
  1720. expect(data.ok).to.be.true(data.message);
  1721. // Cleanup.
  1722. const [code] = await once(child, 'exit');
  1723. expect(code).to.equal(0);
  1724. });
  1725. it('does not impact proxy for requests made from main process', async () => {
  1726. server = http.createServer((req, res) => {
  1727. res.writeHead(200);
  1728. res.end('ok from server\n');
  1729. });
  1730. const { url } = await listen(server);
  1731. const config = { mode: 'fixed_servers' as const, proxyRules: 'http=myproxy:80' };
  1732. await app.setProxy(config);
  1733. const proxy = await app.resolveProxy('http://example.com/');
  1734. expect(proxy).to.equal('PROXY myproxy:80');
  1735. const urlRequest = electronNet.request(url);
  1736. const response = await getResponse(urlRequest);
  1737. expect(response.statusCode).to.equal(200);
  1738. const message = await collectStreamBody(response);
  1739. expect(message).to.equal('ok from server\n');
  1740. });
  1741. });
  1742. });
  1743. describe('default behavior', () => {
  1744. describe('application menu', () => {
  1745. it('creates the default menu if the app does not set it', async () => {
  1746. const result = await runTestApp('default-menu');
  1747. expect(result).to.equal(false);
  1748. });
  1749. it('does not create the default menu if the app sets a custom menu', async () => {
  1750. const result = await runTestApp('default-menu', '--custom-menu');
  1751. expect(result).to.equal(true);
  1752. });
  1753. it('does not create the default menu if the app sets a null menu', async () => {
  1754. const result = await runTestApp('default-menu', '--null-menu');
  1755. expect(result).to.equal(true);
  1756. });
  1757. });
  1758. describe('window-all-closed', () => {
  1759. afterEach(closeAllWindows);
  1760. it('quits when the app does not handle the event', async () => {
  1761. const result = await runTestApp('window-all-closed');
  1762. expect(result).to.equal(false);
  1763. });
  1764. it('does not quit when the app handles the event', async () => {
  1765. const result = await runTestApp('window-all-closed', '--handle-event');
  1766. expect(result).to.equal(true);
  1767. });
  1768. it('should omit closed windows from getAllWindows', async () => {
  1769. const w = new BrowserWindow({ show: false });
  1770. const len = new Promise(resolve => {
  1771. app.on('window-all-closed', () => {
  1772. resolve(BrowserWindow.getAllWindows().length);
  1773. });
  1774. });
  1775. w.close();
  1776. expect(await len).to.equal(0);
  1777. });
  1778. });
  1779. describe('user agent fallback', () => {
  1780. let initialValue: string;
  1781. before(() => {
  1782. initialValue = app.userAgentFallback!;
  1783. });
  1784. it('should have a reasonable default', () => {
  1785. expect(initialValue).to.include(`Electron/${process.versions.electron}`);
  1786. expect(initialValue).to.include(`Chrome/${process.versions.chrome}`);
  1787. });
  1788. it('should be overridable', () => {
  1789. app.userAgentFallback = 'test-agent/123';
  1790. expect(app.userAgentFallback).to.equal('test-agent/123');
  1791. });
  1792. it('should be restorable', () => {
  1793. app.userAgentFallback = 'test-agent/123';
  1794. app.userAgentFallback = '';
  1795. expect(app.userAgentFallback).to.equal(initialValue);
  1796. });
  1797. });
  1798. describe('login event', () => {
  1799. afterEach(closeAllWindows);
  1800. let server: http.Server;
  1801. let serverUrl: string;
  1802. before(async () => {
  1803. server = http.createServer((request, response) => {
  1804. if (request.headers.authorization) {
  1805. return response.end('ok');
  1806. }
  1807. response
  1808. .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' })
  1809. .end();
  1810. });
  1811. serverUrl = (await listen(server)).url;
  1812. });
  1813. it('should emit a login event on app when a WebContents hits a 401', async () => {
  1814. const w = new BrowserWindow({ show: false });
  1815. w.loadURL(serverUrl);
  1816. const [, webContents] = await once(app, 'login') as [any, WebContents];
  1817. expect(webContents).to.equal(w.webContents);
  1818. });
  1819. });
  1820. describe('running under ARM64 translation', () => {
  1821. it('does not throw an error', () => {
  1822. if (process.platform === 'darwin' || process.platform === 'win32') {
  1823. expect(app.runningUnderARM64Translation).not.to.be.undefined();
  1824. expect(() => {
  1825. return app.runningUnderARM64Translation;
  1826. }).not.to.throw();
  1827. } else {
  1828. expect(app.runningUnderARM64Translation).to.be.undefined();
  1829. }
  1830. });
  1831. });
  1832. });
  1833. async function runTestApp (name: string, ...args: any[]) {
  1834. const appPath = path.join(fixturesPath, 'api', name);
  1835. const electronPath = process.execPath;
  1836. const appProcess = cp.spawn(electronPath, [appPath, ...args]);
  1837. let output = '';
  1838. appProcess.stdout.on('data', (data) => { output += data; });
  1839. await once(appProcess.stdout, 'end');
  1840. return JSON.parse(output);
  1841. }