api-browser-window-spec.ts 162 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575
  1. import { expect } from 'chai';
  2. import * as childProcess from 'child_process';
  3. import * as path from 'path';
  4. import * as fs from 'fs';
  5. import * as os from 'os';
  6. import * as qs from 'querystring';
  7. import * as http from 'http';
  8. import { AddressInfo } from 'net';
  9. import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main';
  10. import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers';
  11. import { ifit, ifdescribe, defer, delay } from './spec-helpers';
  12. import { closeWindow, closeAllWindows } from './window-helpers';
  13. const features = process._linkedBinding('electron_common_features');
  14. const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures');
  15. // Is the display's scale factor possibly causing rounding of pixel coordinate
  16. // values?
  17. const isScaleFactorRounding = () => {
  18. const { scaleFactor } = screen.getPrimaryDisplay();
  19. // Return true if scale factor is non-integer value
  20. if (Math.round(scaleFactor) !== scaleFactor) return true;
  21. // Return true if scale factor is odd number above 2
  22. return scaleFactor > 2 && scaleFactor % 2 === 1;
  23. };
  24. const expectBoundsEqual = (actual: any, expected: any) => {
  25. if (!isScaleFactorRounding()) {
  26. expect(expected).to.deep.equal(actual);
  27. } else if (Array.isArray(actual)) {
  28. expect(actual[0]).to.be.closeTo(expected[0], 1);
  29. expect(actual[1]).to.be.closeTo(expected[1], 1);
  30. } else {
  31. expect(actual.x).to.be.closeTo(expected.x, 1);
  32. expect(actual.y).to.be.closeTo(expected.y, 1);
  33. expect(actual.width).to.be.closeTo(expected.width, 1);
  34. expect(actual.height).to.be.closeTo(expected.height, 1);
  35. }
  36. };
  37. const isBeforeUnload = (event: Event, level: number, message: string) => {
  38. return (message === 'beforeunload');
  39. };
  40. describe('BrowserWindow module', () => {
  41. describe('BrowserWindow constructor', () => {
  42. it('allows passing void 0 as the webContents', async () => {
  43. expect(() => {
  44. const w = new BrowserWindow({
  45. show: false,
  46. // apparently void 0 had different behaviour from undefined in the
  47. // issue that this test is supposed to catch.
  48. webContents: void 0 // eslint-disable-line no-void
  49. } as any);
  50. w.destroy();
  51. }).not.to.throw();
  52. });
  53. ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
  54. const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon');
  55. const appProcess = childProcess.spawn(process.execPath, [appPath]);
  56. await new Promise((resolve) => { appProcess.once('exit', resolve); });
  57. });
  58. it('does not crash or throw when passed an invalid icon', async () => {
  59. expect(() => {
  60. const w = new BrowserWindow({
  61. icon: undefined
  62. } as any);
  63. w.destroy();
  64. }).not.to.throw();
  65. });
  66. });
  67. describe('garbage collection', () => {
  68. const v8Util = process._linkedBinding('electron_common_v8_util');
  69. afterEach(closeAllWindows);
  70. it('window does not get garbage collected when opened', async () => {
  71. const w = new BrowserWindow({ show: false });
  72. // Keep a weak reference to the window.
  73. // eslint-disable-next-line no-undef
  74. const wr = new WeakRef(w);
  75. await delay();
  76. // Do garbage collection, since |w| is not referenced in this closure
  77. // it would be gone after next call if there is no other reference.
  78. v8Util.requestGarbageCollectionForTesting();
  79. await delay();
  80. expect(wr.deref()).to.not.be.undefined();
  81. });
  82. });
  83. describe('BrowserWindow.close()', () => {
  84. let w = null as unknown as BrowserWindow;
  85. beforeEach(() => {
  86. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  87. });
  88. afterEach(async () => {
  89. await closeWindow(w);
  90. w = null as unknown as BrowserWindow;
  91. });
  92. it('should work if called when a messageBox is showing', async () => {
  93. const closed = emittedOnce(w, 'closed');
  94. dialog.showMessageBox(w, { message: 'Hello Error' });
  95. w.close();
  96. await closed;
  97. });
  98. it('should emit unload handler', async () => {
  99. await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
  100. const closed = emittedOnce(w, 'closed');
  101. w.close();
  102. await closed;
  103. const test = path.join(fixtures, 'api', 'unload');
  104. const content = fs.readFileSync(test);
  105. fs.unlinkSync(test);
  106. expect(String(content)).to.equal('unload');
  107. });
  108. it('should emit beforeunload handler', async () => {
  109. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  110. w.close();
  111. await emittedOnce(w.webContents, 'before-unload-fired');
  112. });
  113. it('should not crash when keyboard event is sent before closing', async () => {
  114. await w.loadURL('data:text/html,pls no crash');
  115. const closed = emittedOnce(w, 'closed');
  116. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
  117. w.close();
  118. await closed;
  119. });
  120. describe('when invoked synchronously inside navigation observer', () => {
  121. let server: http.Server = null as unknown as http.Server;
  122. let url: string = null as unknown as string;
  123. before((done) => {
  124. server = http.createServer((request, response) => {
  125. switch (request.url) {
  126. case '/net-error':
  127. response.destroy();
  128. break;
  129. case '/301':
  130. response.statusCode = 301;
  131. response.setHeader('Location', '/200');
  132. response.end();
  133. break;
  134. case '/200':
  135. response.statusCode = 200;
  136. response.end('hello');
  137. break;
  138. case '/title':
  139. response.statusCode = 200;
  140. response.end('<title>Hello</title>');
  141. break;
  142. default:
  143. throw new Error(`unsupported endpoint: ${request.url}`);
  144. }
  145. }).listen(0, '127.0.0.1', () => {
  146. url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  147. done();
  148. });
  149. });
  150. after(() => {
  151. server.close();
  152. });
  153. const events = [
  154. { name: 'did-start-loading', path: '/200' },
  155. { name: 'dom-ready', path: '/200' },
  156. { name: 'page-title-updated', path: '/title' },
  157. { name: 'did-stop-loading', path: '/200' },
  158. { name: 'did-finish-load', path: '/200' },
  159. { name: 'did-frame-finish-load', path: '/200' },
  160. { name: 'did-fail-load', path: '/net-error' }
  161. ];
  162. for (const { name, path } of events) {
  163. it(`should not crash when closed during ${name}`, async () => {
  164. const w = new BrowserWindow({ show: false });
  165. w.webContents.once((name as any), () => {
  166. w.close();
  167. });
  168. const destroyed = emittedOnce(w.webContents, 'destroyed');
  169. w.webContents.loadURL(url + path);
  170. await destroyed;
  171. });
  172. }
  173. });
  174. });
  175. describe('window.close()', () => {
  176. let w = null as unknown as BrowserWindow;
  177. beforeEach(() => {
  178. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  179. });
  180. afterEach(async () => {
  181. await closeWindow(w);
  182. w = null as unknown as BrowserWindow;
  183. });
  184. it('should emit unload event', async () => {
  185. w.loadFile(path.join(fixtures, 'api', 'close.html'));
  186. await emittedOnce(w, 'closed');
  187. const test = path.join(fixtures, 'api', 'close');
  188. const content = fs.readFileSync(test).toString();
  189. fs.unlinkSync(test);
  190. expect(content).to.equal('close');
  191. });
  192. it('should emit beforeunload event', async function () {
  193. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  194. w.webContents.executeJavaScript('window.close()', true);
  195. await emittedOnce(w.webContents, 'before-unload-fired');
  196. });
  197. });
  198. describe('BrowserWindow.destroy()', () => {
  199. let w = null as unknown as BrowserWindow;
  200. beforeEach(() => {
  201. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  202. });
  203. afterEach(async () => {
  204. await closeWindow(w);
  205. w = null as unknown as BrowserWindow;
  206. });
  207. it('prevents users to access methods of webContents', async () => {
  208. const contents = w.webContents;
  209. w.destroy();
  210. await new Promise(setImmediate);
  211. expect(() => {
  212. contents.getProcessId();
  213. }).to.throw('Object has been destroyed');
  214. });
  215. it('should not crash when destroying windows with pending events', () => {
  216. const focusListener = () => { };
  217. app.on('browser-window-focus', focusListener);
  218. const windowCount = 3;
  219. const windowOptions = {
  220. show: false,
  221. width: 400,
  222. height: 400,
  223. webPreferences: {
  224. backgroundThrottling: false
  225. }
  226. };
  227. const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
  228. windows.forEach(win => win.show());
  229. windows.forEach(win => win.focus());
  230. windows.forEach(win => win.destroy());
  231. app.removeListener('browser-window-focus', focusListener);
  232. });
  233. });
  234. describe('BrowserWindow.loadURL(url)', () => {
  235. let w = null as unknown as BrowserWindow;
  236. const scheme = 'other';
  237. const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
  238. before(() => {
  239. protocol.registerFileProtocol(scheme, (request, callback) => {
  240. callback(srcPath);
  241. });
  242. });
  243. after(() => {
  244. protocol.unregisterProtocol(scheme);
  245. });
  246. beforeEach(() => {
  247. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  248. });
  249. afterEach(async () => {
  250. await closeWindow(w);
  251. w = null as unknown as BrowserWindow;
  252. });
  253. let server = null as unknown as http.Server;
  254. let url = null as unknown as string;
  255. let postData = null as any;
  256. before((done) => {
  257. const filePath = path.join(fixtures, 'pages', 'a.html');
  258. const fileStats = fs.statSync(filePath);
  259. postData = [
  260. {
  261. type: 'rawData',
  262. bytes: Buffer.from('username=test&file=')
  263. },
  264. {
  265. type: 'file',
  266. filePath: filePath,
  267. offset: 0,
  268. length: fileStats.size,
  269. modificationTime: fileStats.mtime.getTime() / 1000
  270. }
  271. ];
  272. server = http.createServer((req, res) => {
  273. function respond () {
  274. if (req.method === 'POST') {
  275. let body = '';
  276. req.on('data', (data) => {
  277. if (data) body += data;
  278. });
  279. req.on('end', () => {
  280. const parsedData = qs.parse(body);
  281. fs.readFile(filePath, (err, data) => {
  282. if (err) return;
  283. if (parsedData.username === 'test' &&
  284. parsedData.file === data.toString()) {
  285. res.end();
  286. }
  287. });
  288. });
  289. } else if (req.url === '/302') {
  290. res.setHeader('Location', '/200');
  291. res.statusCode = 302;
  292. res.end();
  293. } else {
  294. res.end();
  295. }
  296. }
  297. setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0);
  298. });
  299. server.listen(0, '127.0.0.1', () => {
  300. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  301. done();
  302. });
  303. });
  304. after(() => {
  305. server.close();
  306. });
  307. it('should emit did-start-loading event', async () => {
  308. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  309. w.loadURL('about:blank');
  310. await didStartLoading;
  311. });
  312. it('should emit ready-to-show event', async () => {
  313. const readyToShow = emittedOnce(w, 'ready-to-show');
  314. w.loadURL('about:blank');
  315. await readyToShow;
  316. });
  317. // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
  318. // changed and adjust the test.
  319. it.skip('should emit did-fail-load event for files that do not exist', async () => {
  320. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  321. w.loadURL('file://a.txt');
  322. const [, code, desc,, isMainFrame] = await didFailLoad;
  323. expect(code).to.equal(-6);
  324. expect(desc).to.equal('ERR_FILE_NOT_FOUND');
  325. expect(isMainFrame).to.equal(true);
  326. });
  327. it('should emit did-fail-load event for invalid URL', async () => {
  328. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  329. w.loadURL('http://example:port');
  330. const [, code, desc,, isMainFrame] = await didFailLoad;
  331. expect(desc).to.equal('ERR_INVALID_URL');
  332. expect(code).to.equal(-300);
  333. expect(isMainFrame).to.equal(true);
  334. });
  335. it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
  336. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  337. w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
  338. const [,,,, isMainFrame] = await didFailLoad;
  339. expect(isMainFrame).to.equal(false);
  340. });
  341. it('does not crash in did-fail-provisional-load handler', (done) => {
  342. w.webContents.once('did-fail-provisional-load', () => {
  343. w.loadURL('http://127.0.0.1:11111');
  344. done();
  345. });
  346. w.loadURL('http://127.0.0.1:11111');
  347. });
  348. it('should emit did-fail-load event for URL exceeding character limit', async () => {
  349. const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
  350. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  351. w.loadURL(`data:image/png;base64,${data}`);
  352. const [, code, desc,, isMainFrame] = await didFailLoad;
  353. expect(desc).to.equal('ERR_INVALID_URL');
  354. expect(code).to.equal(-300);
  355. expect(isMainFrame).to.equal(true);
  356. });
  357. it('should return a promise', () => {
  358. const p = w.loadURL('about:blank');
  359. expect(p).to.have.property('then');
  360. });
  361. it('should return a promise that resolves', async () => {
  362. await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
  363. });
  364. it('should return a promise that rejects on a load failure', async () => {
  365. const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
  366. const p = w.loadURL(`data:image/png;base64,${data}`);
  367. await expect(p).to.eventually.be.rejected;
  368. });
  369. it('should return a promise that resolves even if pushState occurs during navigation', async () => {
  370. const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
  371. await expect(p).to.eventually.be.fulfilled;
  372. });
  373. // FIXME(robo/nornagon): re-enable these once service workers work
  374. describe.skip('POST navigations', () => {
  375. afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
  376. it('supports specifying POST data', async () => {
  377. await w.loadURL(url, { postData });
  378. });
  379. it('sets the content type header on URL encoded forms', async () => {
  380. await w.loadURL(url);
  381. const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
  382. w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
  383. resolve(details);
  384. });
  385. });
  386. w.webContents.executeJavaScript(`
  387. form = document.createElement('form')
  388. document.body.appendChild(form)
  389. form.method = 'POST'
  390. form.submit()
  391. `);
  392. const details = await requestDetails;
  393. expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
  394. });
  395. it('sets the content type header on multi part forms', async () => {
  396. await w.loadURL(url);
  397. const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
  398. w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
  399. resolve(details);
  400. });
  401. });
  402. w.webContents.executeJavaScript(`
  403. form = document.createElement('form')
  404. document.body.appendChild(form)
  405. form.method = 'POST'
  406. form.enctype = 'multipart/form-data'
  407. file = document.createElement('input')
  408. file.type = 'file'
  409. file.name = 'file'
  410. form.appendChild(file)
  411. form.submit()
  412. `);
  413. const details = await requestDetails;
  414. expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
  415. });
  416. });
  417. it('should support base url for data urls', async () => {
  418. await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
  419. expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
  420. });
  421. });
  422. for (const sandbox of [false, true]) {
  423. describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
  424. let w = null as unknown as BrowserWindow;
  425. beforeEach(() => {
  426. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
  427. });
  428. afterEach(async () => {
  429. await closeWindow(w);
  430. w = null as unknown as BrowserWindow;
  431. });
  432. describe('will-navigate event', () => {
  433. let server = null as unknown as http.Server;
  434. let url = null as unknown as string;
  435. before((done) => {
  436. server = http.createServer((req, res) => {
  437. if (req.url === '/navigate-top') {
  438. res.end('<a target=_top href="/">navigate _top</a>');
  439. } else {
  440. res.end('');
  441. }
  442. });
  443. server.listen(0, '127.0.0.1', () => {
  444. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
  445. done();
  446. });
  447. });
  448. after(() => {
  449. server.close();
  450. });
  451. it('allows the window to be closed from the event listener', (done) => {
  452. w.webContents.once('will-navigate', () => {
  453. w.close();
  454. done();
  455. });
  456. w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
  457. });
  458. it('can be prevented', (done) => {
  459. let willNavigate = false;
  460. w.webContents.once('will-navigate', (e) => {
  461. willNavigate = true;
  462. e.preventDefault();
  463. });
  464. w.webContents.on('did-stop-loading', () => {
  465. if (willNavigate) {
  466. // i.e. it shouldn't have had '?navigated' appended to it.
  467. try {
  468. expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
  469. done();
  470. } catch (e) {
  471. done(e);
  472. }
  473. }
  474. });
  475. w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
  476. });
  477. it('is triggered when navigating from file: to http:', async () => {
  478. await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  479. w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
  480. const navigatedTo = await new Promise(resolve => {
  481. w.webContents.once('will-navigate', (e, url) => {
  482. e.preventDefault();
  483. resolve(url);
  484. });
  485. });
  486. expect(navigatedTo).to.equal(url);
  487. expect(w.webContents.getURL()).to.match(/^file:/);
  488. });
  489. it('is triggered when navigating from about:blank to http:', async () => {
  490. await w.loadURL('about:blank');
  491. w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
  492. const navigatedTo = await new Promise(resolve => {
  493. w.webContents.once('will-navigate', (e, url) => {
  494. e.preventDefault();
  495. resolve(url);
  496. });
  497. });
  498. expect(navigatedTo).to.equal(url);
  499. expect(w.webContents.getURL()).to.equal('about:blank');
  500. });
  501. it('is triggered when a cross-origin iframe navigates _top', async () => {
  502. await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
  503. await delay(1000);
  504. w.webContents.debugger.attach('1.1');
  505. const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
  506. const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
  507. const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
  508. targetId: iframeTarget.targetId,
  509. flatten: true
  510. });
  511. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  512. type: 'mousePressed',
  513. x: 10,
  514. y: 10,
  515. clickCount: 1,
  516. button: 'left'
  517. }, sessionId);
  518. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  519. type: 'mouseReleased',
  520. x: 10,
  521. y: 10,
  522. clickCount: 1,
  523. button: 'left'
  524. }, sessionId);
  525. let willNavigateEmitted = false;
  526. w.webContents.on('will-navigate', () => {
  527. willNavigateEmitted = true;
  528. });
  529. await emittedOnce(w.webContents, 'did-navigate');
  530. expect(willNavigateEmitted).to.be.true();
  531. });
  532. });
  533. describe('will-redirect event', () => {
  534. let server = null as unknown as http.Server;
  535. let url = null as unknown as string;
  536. before((done) => {
  537. server = http.createServer((req, res) => {
  538. if (req.url === '/302') {
  539. res.setHeader('Location', '/200');
  540. res.statusCode = 302;
  541. res.end();
  542. } else if (req.url === '/navigate-302') {
  543. res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
  544. } else {
  545. res.end();
  546. }
  547. });
  548. server.listen(0, '127.0.0.1', () => {
  549. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  550. done();
  551. });
  552. });
  553. after(() => {
  554. server.close();
  555. });
  556. it('is emitted on redirects', async () => {
  557. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  558. w.loadURL(`${url}/302`);
  559. await willRedirect;
  560. });
  561. it('is emitted after will-navigate on redirects', async () => {
  562. let navigateCalled = false;
  563. w.webContents.on('will-navigate', () => {
  564. navigateCalled = true;
  565. });
  566. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  567. w.loadURL(`${url}/navigate-302`);
  568. await willRedirect;
  569. expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
  570. });
  571. it('is emitted before did-stop-loading on redirects', async () => {
  572. let stopCalled = false;
  573. w.webContents.on('did-stop-loading', () => {
  574. stopCalled = true;
  575. });
  576. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  577. w.loadURL(`${url}/302`);
  578. await willRedirect;
  579. expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
  580. });
  581. it('allows the window to be closed from the event listener', (done) => {
  582. w.webContents.once('will-redirect', () => {
  583. w.close();
  584. done();
  585. });
  586. w.loadURL(`${url}/302`);
  587. });
  588. it('can be prevented', (done) => {
  589. w.webContents.once('will-redirect', (event) => {
  590. event.preventDefault();
  591. });
  592. w.webContents.on('will-navigate', (e, u) => {
  593. expect(u).to.equal(`${url}/302`);
  594. });
  595. w.webContents.on('did-stop-loading', () => {
  596. try {
  597. expect(w.webContents.getURL()).to.equal(
  598. `${url}/navigate-302`,
  599. 'url should not have changed after navigation event'
  600. );
  601. done();
  602. } catch (e) {
  603. done(e);
  604. }
  605. });
  606. w.webContents.on('will-redirect', (e, u) => {
  607. try {
  608. expect(u).to.equal(`${url}/200`);
  609. } catch (e) {
  610. done(e);
  611. }
  612. });
  613. w.loadURL(`${url}/navigate-302`);
  614. });
  615. });
  616. });
  617. }
  618. describe('focus and visibility', () => {
  619. let w = null as unknown as BrowserWindow;
  620. beforeEach(() => {
  621. w = new BrowserWindow({ show: false });
  622. });
  623. afterEach(async () => {
  624. await closeWindow(w);
  625. w = null as unknown as BrowserWindow;
  626. });
  627. describe('BrowserWindow.show()', () => {
  628. it('should focus on window', () => {
  629. w.show();
  630. expect(w.isFocused()).to.equal(true);
  631. });
  632. it('should make the window visible', () => {
  633. w.show();
  634. expect(w.isVisible()).to.equal(true);
  635. });
  636. it('emits when window is shown', async () => {
  637. const show = emittedOnce(w, 'show');
  638. w.show();
  639. await show;
  640. expect(w.isVisible()).to.equal(true);
  641. });
  642. });
  643. describe('BrowserWindow.hide()', () => {
  644. it('should defocus on window', () => {
  645. w.hide();
  646. expect(w.isFocused()).to.equal(false);
  647. });
  648. it('should make the window not visible', () => {
  649. w.show();
  650. w.hide();
  651. expect(w.isVisible()).to.equal(false);
  652. });
  653. it('emits when window is hidden', async () => {
  654. const shown = emittedOnce(w, 'show');
  655. w.show();
  656. await shown;
  657. const hidden = emittedOnce(w, 'hide');
  658. w.hide();
  659. await hidden;
  660. expect(w.isVisible()).to.equal(false);
  661. });
  662. });
  663. describe('BrowserWindow.showInactive()', () => {
  664. it('should not focus on window', () => {
  665. w.showInactive();
  666. expect(w.isFocused()).to.equal(false);
  667. });
  668. });
  669. describe('BrowserWindow.focus()', () => {
  670. it('does not make the window become visible', () => {
  671. expect(w.isVisible()).to.equal(false);
  672. w.focus();
  673. expect(w.isVisible()).to.equal(false);
  674. });
  675. });
  676. describe('BrowserWindow.blur()', () => {
  677. it('removes focus from window', () => {
  678. w.blur();
  679. expect(w.isFocused()).to.equal(false);
  680. });
  681. });
  682. describe('BrowserWindow.getFocusedWindow()', () => {
  683. it('returns the opener window when dev tools window is focused', async () => {
  684. w.show();
  685. w.webContents.openDevTools({ mode: 'undocked' });
  686. await emittedOnce(w.webContents, 'devtools-focused');
  687. expect(BrowserWindow.getFocusedWindow()).to.equal(w);
  688. });
  689. });
  690. describe('BrowserWindow.moveTop()', () => {
  691. it('should not steal focus', async () => {
  692. const posDelta = 50;
  693. const wShownInactive = emittedOnce(w, 'show');
  694. w.showInactive();
  695. await wShownInactive;
  696. expect(w.isFocused()).to.equal(false);
  697. const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
  698. const otherWindowShown = emittedOnce(otherWindow, 'show');
  699. const otherWindowFocused = emittedOnce(otherWindow, 'focus');
  700. otherWindow.show();
  701. await otherWindowShown;
  702. await otherWindowFocused;
  703. expect(otherWindow.isFocused()).to.equal(true);
  704. w.moveTop();
  705. const wPos = w.getPosition();
  706. const wMoving = emittedOnce(w, 'move');
  707. w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
  708. await wMoving;
  709. expect(w.isFocused()).to.equal(false);
  710. expect(otherWindow.isFocused()).to.equal(true);
  711. const wFocused = emittedOnce(w, 'focus');
  712. const otherWindowBlurred = emittedOnce(otherWindow, 'blur');
  713. w.focus();
  714. await wFocused;
  715. await otherWindowBlurred;
  716. expect(w.isFocused()).to.equal(true);
  717. otherWindow.moveTop();
  718. const otherWindowPos = otherWindow.getPosition();
  719. const otherWindowMoving = emittedOnce(otherWindow, 'move');
  720. otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
  721. await otherWindowMoving;
  722. expect(otherWindow.isFocused()).to.equal(false);
  723. expect(w.isFocused()).to.equal(true);
  724. await closeWindow(otherWindow, { assertNotWindows: false });
  725. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
  726. });
  727. });
  728. ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => {
  729. it('should throw an exception if wrong formatting', async () => {
  730. const fakeSourceIds = [
  731. 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
  732. ];
  733. fakeSourceIds.forEach((sourceId) => {
  734. expect(() => {
  735. w.moveAbove(sourceId);
  736. }).to.throw(/Invalid media source id/);
  737. });
  738. });
  739. it('should throw an exception if wrong type', async () => {
  740. const fakeSourceIds = [null as any, 123 as any];
  741. fakeSourceIds.forEach((sourceId) => {
  742. expect(() => {
  743. w.moveAbove(sourceId);
  744. }).to.throw(/Error processing argument at index 0 */);
  745. });
  746. });
  747. it('should throw an exception if invalid window', async () => {
  748. // It is very unlikely that these window id exist.
  749. const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
  750. 'window:123456:9'];
  751. fakeSourceIds.forEach((sourceId) => {
  752. expect(() => {
  753. w.moveAbove(sourceId);
  754. }).to.throw(/Invalid media source id/);
  755. });
  756. });
  757. it('should not throw an exception', async () => {
  758. const w2 = new BrowserWindow({ show: false, title: 'window2' });
  759. const w2Shown = emittedOnce(w2, 'show');
  760. w2.show();
  761. await w2Shown;
  762. expect(() => {
  763. w.moveAbove(w2.getMediaSourceId());
  764. }).to.not.throw();
  765. await closeWindow(w2, { assertNotWindows: false });
  766. });
  767. });
  768. describe('BrowserWindow.setFocusable()', () => {
  769. it('can set unfocusable window to focusable', async () => {
  770. const w2 = new BrowserWindow({ focusable: false });
  771. const w2Focused = emittedOnce(w2, 'focus');
  772. w2.setFocusable(true);
  773. w2.focus();
  774. await w2Focused;
  775. await closeWindow(w2, { assertNotWindows: false });
  776. });
  777. });
  778. describe('BrowserWindow.isFocusable()', () => {
  779. it('correctly returns whether a window is focusable', async () => {
  780. const w2 = new BrowserWindow({ focusable: false });
  781. expect(w2.isFocusable()).to.be.false();
  782. w2.setFocusable(true);
  783. expect(w2.isFocusable()).to.be.true();
  784. await closeWindow(w2, { assertNotWindows: false });
  785. });
  786. });
  787. });
  788. describe('sizing', () => {
  789. let w = null as unknown as BrowserWindow;
  790. beforeEach(() => {
  791. w = new BrowserWindow({ show: false, width: 400, height: 400 });
  792. });
  793. afterEach(async () => {
  794. await closeWindow(w);
  795. w = null as unknown as BrowserWindow;
  796. });
  797. describe('BrowserWindow.setBounds(bounds[, animate])', () => {
  798. it('sets the window bounds with full bounds', () => {
  799. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  800. w.setBounds(fullBounds);
  801. expectBoundsEqual(w.getBounds(), fullBounds);
  802. });
  803. it('sets the window bounds with partial bounds', () => {
  804. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  805. w.setBounds(fullBounds);
  806. const boundsUpdate = { width: 200 };
  807. w.setBounds(boundsUpdate as any);
  808. const expectedBounds = Object.assign(fullBounds, boundsUpdate);
  809. expectBoundsEqual(w.getBounds(), expectedBounds);
  810. });
  811. ifit(process.platform === 'darwin')('on macOS', () => {
  812. it('emits \'resized\' event after animating', async () => {
  813. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  814. w.setBounds(fullBounds, true);
  815. await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled();
  816. });
  817. });
  818. });
  819. describe('BrowserWindow.setSize(width, height)', () => {
  820. it('sets the window size', async () => {
  821. const size = [300, 400];
  822. const resized = emittedOnce(w, 'resize');
  823. w.setSize(size[0], size[1]);
  824. await resized;
  825. expectBoundsEqual(w.getSize(), size);
  826. });
  827. ifit(process.platform === 'darwin')('on macOS', () => {
  828. it('emits \'resized\' event after animating', async () => {
  829. const size = [300, 400];
  830. w.setSize(size[0], size[1], true);
  831. await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled();
  832. });
  833. });
  834. });
  835. describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
  836. it('sets the maximum and minimum size of the window', () => {
  837. expect(w.getMinimumSize()).to.deep.equal([0, 0]);
  838. expect(w.getMaximumSize()).to.deep.equal([0, 0]);
  839. w.setMinimumSize(100, 100);
  840. expectBoundsEqual(w.getMinimumSize(), [100, 100]);
  841. expectBoundsEqual(w.getMaximumSize(), [0, 0]);
  842. w.setMaximumSize(900, 600);
  843. expectBoundsEqual(w.getMinimumSize(), [100, 100]);
  844. expectBoundsEqual(w.getMaximumSize(), [900, 600]);
  845. });
  846. });
  847. describe('BrowserWindow.setAspectRatio(ratio)', () => {
  848. it('resets the behaviour when passing in 0', async () => {
  849. const size = [300, 400];
  850. w.setAspectRatio(1 / 2);
  851. w.setAspectRatio(0);
  852. const resize = emittedOnce(w, 'resize');
  853. w.setSize(size[0], size[1]);
  854. await resize;
  855. expectBoundsEqual(w.getSize(), size);
  856. });
  857. });
  858. describe('BrowserWindow.setPosition(x, y)', () => {
  859. it('sets the window position', async () => {
  860. const pos = [10, 10];
  861. const move = emittedOnce(w, 'move');
  862. w.setPosition(pos[0], pos[1]);
  863. await move;
  864. expect(w.getPosition()).to.deep.equal(pos);
  865. });
  866. });
  867. describe('BrowserWindow.setContentSize(width, height)', () => {
  868. it('sets the content size', async () => {
  869. // NB. The CI server has a very small screen. Attempting to size the window
  870. // larger than the screen will limit the window's size to the screen and
  871. // cause the test to fail.
  872. const size = [456, 567];
  873. w.setContentSize(size[0], size[1]);
  874. await new Promise(setImmediate);
  875. const after = w.getContentSize();
  876. expect(after).to.deep.equal(size);
  877. });
  878. it('works for a frameless window', async () => {
  879. w.destroy();
  880. w = new BrowserWindow({
  881. show: false,
  882. frame: false,
  883. width: 400,
  884. height: 400
  885. });
  886. const size = [456, 567];
  887. w.setContentSize(size[0], size[1]);
  888. await new Promise(setImmediate);
  889. const after = w.getContentSize();
  890. expect(after).to.deep.equal(size);
  891. });
  892. });
  893. describe('BrowserWindow.setContentBounds(bounds)', () => {
  894. it('sets the content size and position', async () => {
  895. const bounds = { x: 10, y: 10, width: 250, height: 250 };
  896. const resize = emittedOnce(w, 'resize');
  897. w.setContentBounds(bounds);
  898. await resize;
  899. await delay();
  900. expectBoundsEqual(w.getContentBounds(), bounds);
  901. });
  902. it('works for a frameless window', async () => {
  903. w.destroy();
  904. w = new BrowserWindow({
  905. show: false,
  906. frame: false,
  907. width: 300,
  908. height: 300
  909. });
  910. const bounds = { x: 10, y: 10, width: 250, height: 250 };
  911. const resize = emittedOnce(w, 'resize');
  912. w.setContentBounds(bounds);
  913. await resize;
  914. await delay();
  915. expectBoundsEqual(w.getContentBounds(), bounds);
  916. });
  917. });
  918. describe('BrowserWindow.getBackgroundColor()', () => {
  919. it('returns default value if no backgroundColor is set', () => {
  920. w.destroy();
  921. w = new BrowserWindow({});
  922. expect(w.getBackgroundColor()).to.equal('#FFFFFF');
  923. });
  924. it('returns correct value if backgroundColor is set', () => {
  925. const backgroundColor = '#BBAAFF';
  926. w.destroy();
  927. w = new BrowserWindow({
  928. backgroundColor: backgroundColor
  929. });
  930. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  931. });
  932. it('returns correct value from setBackgroundColor()', () => {
  933. const backgroundColor = '#AABBFF';
  934. w.destroy();
  935. w = new BrowserWindow({});
  936. w.setBackgroundColor(backgroundColor);
  937. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  938. });
  939. });
  940. describe('BrowserWindow.getNormalBounds()', () => {
  941. describe('Normal state', () => {
  942. it('checks normal bounds after resize', async () => {
  943. const size = [300, 400];
  944. const resize = emittedOnce(w, 'resize');
  945. w.setSize(size[0], size[1]);
  946. await resize;
  947. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  948. });
  949. it('checks normal bounds after move', async () => {
  950. const pos = [10, 10];
  951. const move = emittedOnce(w, 'move');
  952. w.setPosition(pos[0], pos[1]);
  953. await move;
  954. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  955. });
  956. });
  957. ifdescribe(process.platform !== 'linux')('Maximized state', () => {
  958. it('checks normal bounds when maximized', async () => {
  959. const bounds = w.getBounds();
  960. const maximize = emittedOnce(w, 'maximize');
  961. w.show();
  962. w.maximize();
  963. await maximize;
  964. expectBoundsEqual(w.getNormalBounds(), bounds);
  965. });
  966. it('checks normal bounds when unmaximized', async () => {
  967. const bounds = w.getBounds();
  968. w.once('maximize', () => {
  969. w.unmaximize();
  970. });
  971. const unmaximize = emittedOnce(w, 'unmaximize');
  972. w.show();
  973. w.maximize();
  974. await unmaximize;
  975. expectBoundsEqual(w.getNormalBounds(), bounds);
  976. });
  977. it('does not change size for a frameless window with min size', async () => {
  978. w.destroy();
  979. w = new BrowserWindow({
  980. show: false,
  981. frame: false,
  982. width: 300,
  983. height: 300,
  984. minWidth: 300,
  985. minHeight: 300
  986. });
  987. const bounds = w.getBounds();
  988. w.once('maximize', () => {
  989. w.unmaximize();
  990. });
  991. const unmaximize = emittedOnce(w, 'unmaximize');
  992. w.show();
  993. w.maximize();
  994. await unmaximize;
  995. expectBoundsEqual(w.getNormalBounds(), bounds);
  996. });
  997. it('can check transparent window maximization', async () => {
  998. w.destroy();
  999. w = new BrowserWindow({
  1000. show: false,
  1001. width: 300,
  1002. height: 300,
  1003. transparent: true
  1004. });
  1005. const maximize = emittedOnce(w, 'resize');
  1006. w.show();
  1007. w.maximize();
  1008. await maximize;
  1009. expect(w.isMaximized()).to.equal(true);
  1010. const unmaximize = emittedOnce(w, 'resize');
  1011. w.unmaximize();
  1012. await unmaximize;
  1013. expect(w.isMaximized()).to.equal(false);
  1014. });
  1015. });
  1016. ifdescribe(process.platform !== 'linux')('Minimized state', () => {
  1017. it('checks normal bounds when minimized', async () => {
  1018. const bounds = w.getBounds();
  1019. const minimize = emittedOnce(w, 'minimize');
  1020. w.show();
  1021. w.minimize();
  1022. await minimize;
  1023. expectBoundsEqual(w.getNormalBounds(), bounds);
  1024. });
  1025. it('checks normal bounds when restored', async () => {
  1026. const bounds = w.getBounds();
  1027. w.once('minimize', () => {
  1028. w.restore();
  1029. });
  1030. const restore = emittedOnce(w, 'restore');
  1031. w.show();
  1032. w.minimize();
  1033. await restore;
  1034. expectBoundsEqual(w.getNormalBounds(), bounds);
  1035. });
  1036. it('does not change size for a frameless window with min size', async () => {
  1037. w.destroy();
  1038. w = new BrowserWindow({
  1039. show: false,
  1040. frame: false,
  1041. width: 300,
  1042. height: 300,
  1043. minWidth: 300,
  1044. minHeight: 300
  1045. });
  1046. const bounds = w.getBounds();
  1047. w.once('minimize', () => {
  1048. w.restore();
  1049. });
  1050. const restore = emittedOnce(w, 'restore');
  1051. w.show();
  1052. w.minimize();
  1053. await restore;
  1054. expectBoundsEqual(w.getNormalBounds(), bounds);
  1055. });
  1056. });
  1057. ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
  1058. it('with properties', () => {
  1059. it('can be set with the fullscreen constructor option', () => {
  1060. w = new BrowserWindow({ fullscreen: true });
  1061. expect(w.fullScreen).to.be.true();
  1062. });
  1063. it('can be changed', () => {
  1064. w.fullScreen = false;
  1065. expect(w.fullScreen).to.be.false();
  1066. w.fullScreen = true;
  1067. expect(w.fullScreen).to.be.true();
  1068. });
  1069. it('checks normal bounds when fullscreen\'ed', async () => {
  1070. const bounds = w.getBounds();
  1071. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1072. w.show();
  1073. w.fullScreen = true;
  1074. await enterFullScreen;
  1075. expectBoundsEqual(w.getNormalBounds(), bounds);
  1076. });
  1077. it('checks normal bounds when unfullscreen\'ed', async () => {
  1078. const bounds = w.getBounds();
  1079. w.once('enter-full-screen', () => {
  1080. w.fullScreen = false;
  1081. });
  1082. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1083. w.show();
  1084. w.fullScreen = true;
  1085. await leaveFullScreen;
  1086. expectBoundsEqual(w.getNormalBounds(), bounds);
  1087. });
  1088. });
  1089. it('with functions', () => {
  1090. it('can be set with the fullscreen constructor option', () => {
  1091. w = new BrowserWindow({ fullscreen: true });
  1092. expect(w.isFullScreen()).to.be.true();
  1093. });
  1094. it('can be changed', () => {
  1095. w.setFullScreen(false);
  1096. expect(w.isFullScreen()).to.be.false();
  1097. w.setFullScreen(true);
  1098. expect(w.isFullScreen()).to.be.true();
  1099. });
  1100. it('checks normal bounds when fullscreen\'ed', async () => {
  1101. const bounds = w.getBounds();
  1102. w.show();
  1103. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1104. w.setFullScreen(true);
  1105. await enterFullScreen;
  1106. expectBoundsEqual(w.getNormalBounds(), bounds);
  1107. });
  1108. it('checks normal bounds when unfullscreen\'ed', async () => {
  1109. const bounds = w.getBounds();
  1110. w.show();
  1111. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1112. w.setFullScreen(true);
  1113. await enterFullScreen;
  1114. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1115. w.setFullScreen(false);
  1116. await leaveFullScreen;
  1117. expectBoundsEqual(w.getNormalBounds(), bounds);
  1118. });
  1119. });
  1120. });
  1121. });
  1122. });
  1123. ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
  1124. let w = null as unknown as BrowserWindow;
  1125. beforeEach(() => {
  1126. w = new BrowserWindow({ show: false });
  1127. });
  1128. afterEach(async () => {
  1129. await closeWindow(w);
  1130. w = null as unknown as BrowserWindow;
  1131. });
  1132. describe('BrowserWindow.selectPreviousTab()', () => {
  1133. it('does not throw', () => {
  1134. expect(() => {
  1135. w.selectPreviousTab();
  1136. }).to.not.throw();
  1137. });
  1138. });
  1139. describe('BrowserWindow.selectNextTab()', () => {
  1140. it('does not throw', () => {
  1141. expect(() => {
  1142. w.selectNextTab();
  1143. }).to.not.throw();
  1144. });
  1145. });
  1146. describe('BrowserWindow.mergeAllWindows()', () => {
  1147. it('does not throw', () => {
  1148. expect(() => {
  1149. w.mergeAllWindows();
  1150. }).to.not.throw();
  1151. });
  1152. });
  1153. describe('BrowserWindow.moveTabToNewWindow()', () => {
  1154. it('does not throw', () => {
  1155. expect(() => {
  1156. w.moveTabToNewWindow();
  1157. }).to.not.throw();
  1158. });
  1159. });
  1160. describe('BrowserWindow.toggleTabBar()', () => {
  1161. it('does not throw', () => {
  1162. expect(() => {
  1163. w.toggleTabBar();
  1164. }).to.not.throw();
  1165. });
  1166. });
  1167. describe('BrowserWindow.addTabbedWindow()', () => {
  1168. it('does not throw', async () => {
  1169. const tabbedWindow = new BrowserWindow({});
  1170. expect(() => {
  1171. w.addTabbedWindow(tabbedWindow);
  1172. }).to.not.throw();
  1173. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
  1174. await closeWindow(tabbedWindow, { assertNotWindows: false });
  1175. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
  1176. });
  1177. it('throws when called on itself', () => {
  1178. expect(() => {
  1179. w.addTabbedWindow(w);
  1180. }).to.throw('AddTabbedWindow cannot be called by a window on itself.');
  1181. });
  1182. });
  1183. });
  1184. describe('autoHideMenuBar state', () => {
  1185. afterEach(closeAllWindows);
  1186. it('for properties', () => {
  1187. it('can be set with autoHideMenuBar constructor option', () => {
  1188. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1189. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1190. });
  1191. it('can be changed', () => {
  1192. const w = new BrowserWindow({ show: false });
  1193. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1194. w.autoHideMenuBar = true;
  1195. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1196. w.autoHideMenuBar = false;
  1197. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1198. });
  1199. });
  1200. it('for functions', () => {
  1201. it('can be set with autoHideMenuBar constructor option', () => {
  1202. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1203. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1204. });
  1205. it('can be changed', () => {
  1206. const w = new BrowserWindow({ show: false });
  1207. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1208. w.setAutoHideMenuBar(true);
  1209. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1210. w.setAutoHideMenuBar(false);
  1211. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1212. });
  1213. });
  1214. });
  1215. describe('BrowserWindow.capturePage(rect)', () => {
  1216. afterEach(closeAllWindows);
  1217. it('returns a Promise with a Buffer', async () => {
  1218. const w = new BrowserWindow({ show: false });
  1219. const image = await w.capturePage({
  1220. x: 0,
  1221. y: 0,
  1222. width: 100,
  1223. height: 100
  1224. });
  1225. expect(image.isEmpty()).to.equal(true);
  1226. });
  1227. it('resolves after the window is hidden', async () => {
  1228. const w = new BrowserWindow({ show: false });
  1229. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  1230. await emittedOnce(w, 'ready-to-show');
  1231. w.show();
  1232. const visibleImage = await w.capturePage();
  1233. expect(visibleImage.isEmpty()).to.equal(false);
  1234. w.hide();
  1235. const hiddenImage = await w.capturePage();
  1236. const isEmpty = process.platform !== 'darwin';
  1237. expect(hiddenImage.isEmpty()).to.equal(isEmpty);
  1238. });
  1239. it('preserves transparency', async () => {
  1240. const w = new BrowserWindow({ show: false, transparent: true });
  1241. w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
  1242. await emittedOnce(w, 'ready-to-show');
  1243. w.show();
  1244. const image = await w.capturePage();
  1245. const imgBuffer = image.toPNG();
  1246. // Check the 25th byte in the PNG.
  1247. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  1248. expect(imgBuffer[25]).to.equal(6);
  1249. });
  1250. });
  1251. describe('BrowserWindow.setProgressBar(progress)', () => {
  1252. let w = null as unknown as BrowserWindow;
  1253. before(() => {
  1254. w = new BrowserWindow({ show: false });
  1255. });
  1256. after(async () => {
  1257. await closeWindow(w);
  1258. w = null as unknown as BrowserWindow;
  1259. });
  1260. it('sets the progress', () => {
  1261. expect(() => {
  1262. if (process.platform === 'darwin') {
  1263. app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
  1264. }
  1265. w.setProgressBar(0.5);
  1266. if (process.platform === 'darwin') {
  1267. app.dock.setIcon(null as any);
  1268. }
  1269. w.setProgressBar(-1);
  1270. }).to.not.throw();
  1271. });
  1272. it('sets the progress using "paused" mode', () => {
  1273. expect(() => {
  1274. w.setProgressBar(0.5, { mode: 'paused' });
  1275. }).to.not.throw();
  1276. });
  1277. it('sets the progress using "error" mode', () => {
  1278. expect(() => {
  1279. w.setProgressBar(0.5, { mode: 'error' });
  1280. }).to.not.throw();
  1281. });
  1282. it('sets the progress using "normal" mode', () => {
  1283. expect(() => {
  1284. w.setProgressBar(0.5, { mode: 'normal' });
  1285. }).to.not.throw();
  1286. });
  1287. });
  1288. describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
  1289. let w = null as unknown as BrowserWindow;
  1290. beforeEach(() => {
  1291. w = new BrowserWindow({ show: true });
  1292. });
  1293. afterEach(async () => {
  1294. await closeWindow(w);
  1295. w = null as unknown as BrowserWindow;
  1296. });
  1297. it('sets the window as always on top', () => {
  1298. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1299. w.setAlwaysOnTop(true, 'screen-saver');
  1300. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1301. w.setAlwaysOnTop(false);
  1302. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1303. w.setAlwaysOnTop(true);
  1304. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1305. });
  1306. ifit(process.platform === 'darwin')('resets the windows level on minimize', () => {
  1307. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1308. w.setAlwaysOnTop(true, 'screen-saver');
  1309. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1310. w.minimize();
  1311. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1312. w.restore();
  1313. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1314. });
  1315. it('causes the right value to be emitted on `always-on-top-changed`', async () => {
  1316. const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed');
  1317. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1318. w.setAlwaysOnTop(true);
  1319. const [, alwaysOnTop] = await alwaysOnTopChanged;
  1320. expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
  1321. });
  1322. });
  1323. describe('preconnect feature', () => {
  1324. let w = null as unknown as BrowserWindow;
  1325. let server = null as unknown as http.Server;
  1326. let url = null as unknown as string;
  1327. let connections = 0;
  1328. beforeEach(async () => {
  1329. connections = 0;
  1330. server = http.createServer((req, res) => {
  1331. if (req.url === '/link') {
  1332. res.setHeader('Content-type', 'text/html');
  1333. res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
  1334. return;
  1335. }
  1336. res.end();
  1337. });
  1338. server.on('connection', () => { connections++; });
  1339. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()));
  1340. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1341. });
  1342. afterEach(async () => {
  1343. server.close();
  1344. await closeWindow(w);
  1345. w = null as unknown as BrowserWindow;
  1346. server = null as unknown as http.Server;
  1347. });
  1348. it('calling preconnect() connects to the server', async () => {
  1349. w = new BrowserWindow({ show: false });
  1350. w.webContents.on('did-start-navigation', (event, url) => {
  1351. w.webContents.session.preconnect({ url, numSockets: 4 });
  1352. });
  1353. await w.loadURL(url);
  1354. expect(connections).to.equal(4);
  1355. });
  1356. it('does not preconnect unless requested', async () => {
  1357. w = new BrowserWindow({ show: false });
  1358. await w.loadURL(url);
  1359. expect(connections).to.equal(1);
  1360. });
  1361. it('parses <link rel=preconnect>', async () => {
  1362. w = new BrowserWindow({ show: true });
  1363. const p = emittedOnce(w.webContents.session, 'preconnect');
  1364. w.loadURL(url + '/link');
  1365. const [, preconnectUrl, allowCredentials] = await p;
  1366. expect(preconnectUrl).to.equal('http://example.com/');
  1367. expect(allowCredentials).to.be.true('allowCredentials');
  1368. });
  1369. });
  1370. describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
  1371. let w = null as unknown as BrowserWindow;
  1372. beforeEach(() => {
  1373. w = new BrowserWindow({ show: false });
  1374. });
  1375. afterEach(async () => {
  1376. await closeWindow(w);
  1377. w = null as unknown as BrowserWindow;
  1378. });
  1379. ifit(process.platform === 'darwin')('on macOS', () => {
  1380. it('allows changing cursor auto-hiding', () => {
  1381. expect(() => {
  1382. w.setAutoHideCursor(false);
  1383. w.setAutoHideCursor(true);
  1384. }).to.not.throw();
  1385. });
  1386. });
  1387. ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
  1388. it('is not available', () => {
  1389. expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
  1390. });
  1391. });
  1392. });
  1393. ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
  1394. afterEach(closeAllWindows);
  1395. it('does not throw', () => {
  1396. const w = new BrowserWindow({ show: false });
  1397. expect(() => {
  1398. w.setWindowButtonVisibility(true);
  1399. w.setWindowButtonVisibility(false);
  1400. }).to.not.throw();
  1401. });
  1402. it('changes window button visibility for normal window', () => {
  1403. const w = new BrowserWindow({ show: false });
  1404. expect(w._getWindowButtonVisibility()).to.equal(true);
  1405. w.setWindowButtonVisibility(false);
  1406. expect(w._getWindowButtonVisibility()).to.equal(false);
  1407. w.setWindowButtonVisibility(true);
  1408. expect(w._getWindowButtonVisibility()).to.equal(true);
  1409. });
  1410. it('changes window button visibility for frameless window', () => {
  1411. const w = new BrowserWindow({ show: false, frame: false });
  1412. expect(w._getWindowButtonVisibility()).to.equal(false);
  1413. w.setWindowButtonVisibility(true);
  1414. expect(w._getWindowButtonVisibility()).to.equal(true);
  1415. w.setWindowButtonVisibility(false);
  1416. expect(w._getWindowButtonVisibility()).to.equal(false);
  1417. });
  1418. it('changes window button visibility for hiddenInset window', () => {
  1419. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  1420. expect(w._getWindowButtonVisibility()).to.equal(true);
  1421. w.setWindowButtonVisibility(false);
  1422. expect(w._getWindowButtonVisibility()).to.equal(false);
  1423. w.setWindowButtonVisibility(true);
  1424. expect(w._getWindowButtonVisibility()).to.equal(true);
  1425. });
  1426. it('changes window button visibility for customButtonsOnHover window', () => {
  1427. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
  1428. expect(w._getWindowButtonVisibility()).to.equal(true);
  1429. w.setWindowButtonVisibility(false);
  1430. expect(w._getWindowButtonVisibility()).to.equal(false);
  1431. w.setWindowButtonVisibility(true);
  1432. expect(w._getWindowButtonVisibility()).to.equal(true);
  1433. });
  1434. });
  1435. ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
  1436. afterEach(closeAllWindows);
  1437. it('allows setting, changing, and removing the vibrancy', () => {
  1438. const w = new BrowserWindow({ show: false });
  1439. expect(() => {
  1440. w.setVibrancy('light');
  1441. w.setVibrancy('dark');
  1442. w.setVibrancy(null);
  1443. w.setVibrancy('ultra-dark');
  1444. w.setVibrancy('' as any);
  1445. }).to.not.throw();
  1446. });
  1447. });
  1448. ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
  1449. const pos = { x: 10, y: 10 };
  1450. afterEach(closeAllWindows);
  1451. describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
  1452. it('gets position property for "hidden" titleBarStyle', () => {
  1453. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1454. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1455. });
  1456. it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
  1457. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1458. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1459. });
  1460. });
  1461. describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
  1462. it('sets position property for "hidden" titleBarStyle', () => {
  1463. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1464. const newPos = { x: 20, y: 20 };
  1465. w.setTrafficLightPosition(newPos);
  1466. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1467. });
  1468. it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
  1469. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1470. const newPos = { x: 20, y: 20 };
  1471. w.setTrafficLightPosition(newPos);
  1472. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1473. });
  1474. });
  1475. });
  1476. ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
  1477. afterEach(closeAllWindows);
  1478. it('supports setting the app details', () => {
  1479. const w = new BrowserWindow({ show: false });
  1480. const iconPath = path.join(fixtures, 'assets', 'icon.ico');
  1481. expect(() => {
  1482. w.setAppDetails({ appId: 'my.app.id' });
  1483. w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
  1484. w.setAppDetails({ appIconPath: iconPath });
  1485. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
  1486. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
  1487. w.setAppDetails({ relaunchDisplayName: 'My app name' });
  1488. w.setAppDetails({
  1489. appId: 'my.app.id',
  1490. appIconPath: iconPath,
  1491. appIconIndex: 0,
  1492. relaunchCommand: 'my-app.exe arg1 arg2',
  1493. relaunchDisplayName: 'My app name'
  1494. });
  1495. w.setAppDetails({});
  1496. }).to.not.throw();
  1497. expect(() => {
  1498. (w.setAppDetails as any)();
  1499. }).to.throw('Insufficient number of arguments.');
  1500. });
  1501. });
  1502. describe('BrowserWindow.fromId(id)', () => {
  1503. afterEach(closeAllWindows);
  1504. it('returns the window with id', () => {
  1505. const w = new BrowserWindow({ show: false });
  1506. expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
  1507. });
  1508. });
  1509. describe('BrowserWindow.fromWebContents(webContents)', () => {
  1510. afterEach(closeAllWindows);
  1511. it('returns the window with the webContents', () => {
  1512. const w = new BrowserWindow({ show: false });
  1513. const found = BrowserWindow.fromWebContents(w.webContents);
  1514. expect(found!.id).to.equal(w.id);
  1515. });
  1516. it('returns null for webContents without a BrowserWindow', () => {
  1517. const contents = (webContents as any).create({});
  1518. try {
  1519. expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
  1520. } finally {
  1521. contents.destroy();
  1522. }
  1523. });
  1524. it('returns the correct window for a BrowserView webcontents', async () => {
  1525. const w = new BrowserWindow({ show: false });
  1526. const bv = new BrowserView();
  1527. w.setBrowserView(bv);
  1528. defer(() => {
  1529. w.removeBrowserView(bv);
  1530. (bv.webContents as any).destroy();
  1531. });
  1532. await bv.webContents.loadURL('about:blank');
  1533. expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
  1534. });
  1535. it('returns the correct window for a WebView webcontents', async () => {
  1536. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  1537. w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
  1538. // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
  1539. // https://github.com/electron/electron/issues/25413, and is not integral
  1540. // to the test.
  1541. const p = emittedOnce(w.webContents, 'did-attach-webview');
  1542. const [, webviewContents] = await emittedOnce(app, 'web-contents-created');
  1543. expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
  1544. await p;
  1545. });
  1546. });
  1547. describe('BrowserWindow.openDevTools()', () => {
  1548. afterEach(closeAllWindows);
  1549. it('does not crash for frameless window', () => {
  1550. const w = new BrowserWindow({ show: false, frame: false });
  1551. w.webContents.openDevTools();
  1552. });
  1553. });
  1554. describe('BrowserWindow.fromBrowserView(browserView)', () => {
  1555. afterEach(closeAllWindows);
  1556. it('returns the window with the BrowserView', () => {
  1557. const w = new BrowserWindow({ show: false });
  1558. const bv = new BrowserView();
  1559. w.setBrowserView(bv);
  1560. defer(() => {
  1561. w.removeBrowserView(bv);
  1562. (bv.webContents as any).destroy();
  1563. });
  1564. expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
  1565. });
  1566. it('returns the window when there are multiple BrowserViews', () => {
  1567. const w = new BrowserWindow({ show: false });
  1568. const bv1 = new BrowserView();
  1569. w.addBrowserView(bv1);
  1570. const bv2 = new BrowserView();
  1571. w.addBrowserView(bv2);
  1572. defer(() => {
  1573. w.removeBrowserView(bv1);
  1574. w.removeBrowserView(bv2);
  1575. (bv1.webContents as any).destroy();
  1576. (bv2.webContents as any).destroy();
  1577. });
  1578. expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
  1579. expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
  1580. });
  1581. it('returns undefined if not attached', () => {
  1582. const bv = new BrowserView();
  1583. defer(() => {
  1584. (bv.webContents as any).destroy();
  1585. });
  1586. expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
  1587. });
  1588. });
  1589. describe('BrowserWindow.setOpacity(opacity)', () => {
  1590. afterEach(closeAllWindows);
  1591. ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
  1592. it('make window with initial opacity', () => {
  1593. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  1594. expect(w.getOpacity()).to.equal(0.5);
  1595. });
  1596. it('allows setting the opacity', () => {
  1597. const w = new BrowserWindow({ show: false });
  1598. expect(() => {
  1599. w.setOpacity(0.0);
  1600. expect(w.getOpacity()).to.equal(0.0);
  1601. w.setOpacity(0.5);
  1602. expect(w.getOpacity()).to.equal(0.5);
  1603. w.setOpacity(1.0);
  1604. expect(w.getOpacity()).to.equal(1.0);
  1605. }).to.not.throw();
  1606. });
  1607. it('clamps opacity to [0.0...1.0]', () => {
  1608. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  1609. w.setOpacity(100);
  1610. expect(w.getOpacity()).to.equal(1.0);
  1611. w.setOpacity(-100);
  1612. expect(w.getOpacity()).to.equal(0.0);
  1613. });
  1614. });
  1615. ifdescribe(process.platform === 'linux')(('Linux'), () => {
  1616. it('sets 1 regardless of parameter', () => {
  1617. const w = new BrowserWindow({ show: false });
  1618. w.setOpacity(0);
  1619. expect(w.getOpacity()).to.equal(1.0);
  1620. w.setOpacity(0.5);
  1621. expect(w.getOpacity()).to.equal(1.0);
  1622. });
  1623. });
  1624. });
  1625. describe('BrowserWindow.setShape(rects)', () => {
  1626. afterEach(closeAllWindows);
  1627. it('allows setting shape', () => {
  1628. const w = new BrowserWindow({ show: false });
  1629. expect(() => {
  1630. w.setShape([]);
  1631. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
  1632. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
  1633. w.setShape([]);
  1634. }).to.not.throw();
  1635. });
  1636. });
  1637. describe('"useContentSize" option', () => {
  1638. afterEach(closeAllWindows);
  1639. it('make window created with content size when used', () => {
  1640. const w = new BrowserWindow({
  1641. show: false,
  1642. width: 400,
  1643. height: 400,
  1644. useContentSize: true
  1645. });
  1646. const contentSize = w.getContentSize();
  1647. expect(contentSize).to.deep.equal([400, 400]);
  1648. });
  1649. it('make window created with window size when not used', () => {
  1650. const w = new BrowserWindow({
  1651. show: false,
  1652. width: 400,
  1653. height: 400
  1654. });
  1655. const size = w.getSize();
  1656. expect(size).to.deep.equal([400, 400]);
  1657. });
  1658. it('works for a frameless window', () => {
  1659. const w = new BrowserWindow({
  1660. show: false,
  1661. frame: false,
  1662. width: 400,
  1663. height: 400,
  1664. useContentSize: true
  1665. });
  1666. const contentSize = w.getContentSize();
  1667. expect(contentSize).to.deep.equal([400, 400]);
  1668. const size = w.getSize();
  1669. expect(size).to.deep.equal([400, 400]);
  1670. });
  1671. });
  1672. ifdescribe(process.platform === 'darwin' && parseInt(os.release().split('.')[0]) >= 14)('"titleBarStyle" option', () => {
  1673. afterEach(closeAllWindows);
  1674. it('creates browser window with hidden title bar', () => {
  1675. const w = new BrowserWindow({
  1676. show: false,
  1677. width: 400,
  1678. height: 400,
  1679. titleBarStyle: 'hidden'
  1680. });
  1681. const contentSize = w.getContentSize();
  1682. expect(contentSize).to.deep.equal([400, 400]);
  1683. });
  1684. it('creates browser window with hidden inset title bar', () => {
  1685. const w = new BrowserWindow({
  1686. show: false,
  1687. width: 400,
  1688. height: 400,
  1689. titleBarStyle: 'hiddenInset'
  1690. });
  1691. const contentSize = w.getContentSize();
  1692. expect(contentSize).to.deep.equal([400, 400]);
  1693. });
  1694. });
  1695. ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
  1696. afterEach(closeAllWindows);
  1697. it('can move the window out of screen', () => {
  1698. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  1699. w.setPosition(-10, 50);
  1700. const after = w.getPosition();
  1701. expect(after).to.deep.equal([-10, 50]);
  1702. });
  1703. it('cannot move the window behind menu bar', () => {
  1704. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  1705. w.setPosition(-10, -10);
  1706. const after = w.getPosition();
  1707. expect(after[1]).to.be.at.least(0);
  1708. });
  1709. it('can move the window behind menu bar if it has no frame', () => {
  1710. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
  1711. w.setPosition(-10, -10);
  1712. const after = w.getPosition();
  1713. expect(after[0]).to.be.equal(-10);
  1714. expect(after[1]).to.be.equal(-10);
  1715. });
  1716. it('without it, cannot move the window out of screen', () => {
  1717. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  1718. w.setPosition(-10, -10);
  1719. const after = w.getPosition();
  1720. expect(after[1]).to.be.at.least(0);
  1721. });
  1722. it('can set the window larger than screen', () => {
  1723. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  1724. const size = screen.getPrimaryDisplay().size;
  1725. size.width += 100;
  1726. size.height += 100;
  1727. w.setSize(size.width, size.height);
  1728. expectBoundsEqual(w.getSize(), [size.width, size.height]);
  1729. });
  1730. it('without it, cannot set the window larger than screen', () => {
  1731. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  1732. const size = screen.getPrimaryDisplay().size;
  1733. size.width += 100;
  1734. size.height += 100;
  1735. w.setSize(size.width, size.height);
  1736. expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
  1737. });
  1738. });
  1739. ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
  1740. afterEach(closeAllWindows);
  1741. it('sets the window width to the page width when used', () => {
  1742. const w = new BrowserWindow({
  1743. show: false,
  1744. width: 500,
  1745. height: 400,
  1746. zoomToPageWidth: true
  1747. });
  1748. w.maximize();
  1749. expect(w.getSize()[0]).to.equal(500);
  1750. });
  1751. });
  1752. describe('"tabbingIdentifier" option', () => {
  1753. afterEach(closeAllWindows);
  1754. it('can be set on a window', () => {
  1755. expect(() => {
  1756. /* eslint-disable no-new */
  1757. new BrowserWindow({
  1758. tabbingIdentifier: 'group1'
  1759. });
  1760. new BrowserWindow({
  1761. tabbingIdentifier: 'group2',
  1762. frame: false
  1763. });
  1764. /* eslint-enable no-new */
  1765. }).not.to.throw();
  1766. });
  1767. });
  1768. describe('"webPreferences" option', () => {
  1769. afterEach(() => { ipcMain.removeAllListeners('answer'); });
  1770. afterEach(closeAllWindows);
  1771. describe('"preload" option', () => {
  1772. const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
  1773. it(name, async () => {
  1774. const w = new BrowserWindow({
  1775. webPreferences: {
  1776. ...webPrefs,
  1777. preload: path.resolve(fixtures, 'module', 'empty.js')
  1778. },
  1779. show: false
  1780. });
  1781. w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
  1782. const [, result] = await emittedOnce(ipcMain, 'leak-result');
  1783. expect(result).to.have.property('require', 'undefined');
  1784. expect(result).to.have.property('exports', 'undefined');
  1785. expect(result).to.have.property('windowExports', 'undefined');
  1786. expect(result).to.have.property('windowPreload', 'undefined');
  1787. expect(result).to.have.property('windowRequire', 'undefined');
  1788. });
  1789. };
  1790. doesNotLeakSpec('does not leak require', {
  1791. nodeIntegration: false,
  1792. sandbox: false,
  1793. contextIsolation: false
  1794. });
  1795. doesNotLeakSpec('does not leak require when sandbox is enabled', {
  1796. nodeIntegration: false,
  1797. sandbox: true,
  1798. contextIsolation: false
  1799. });
  1800. doesNotLeakSpec('does not leak require when context isolation is enabled', {
  1801. nodeIntegration: false,
  1802. sandbox: false,
  1803. contextIsolation: true
  1804. });
  1805. doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
  1806. nodeIntegration: false,
  1807. sandbox: true,
  1808. contextIsolation: true
  1809. });
  1810. it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
  1811. let w = new BrowserWindow({
  1812. webPreferences: {
  1813. contextIsolation: false,
  1814. nodeIntegration: false,
  1815. preload: path.resolve(fixtures, 'module', 'empty.js')
  1816. },
  1817. show: false
  1818. });
  1819. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  1820. const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result');
  1821. expect(notIsolated).to.have.property('globals');
  1822. w.destroy();
  1823. w = new BrowserWindow({
  1824. webPreferences: {
  1825. contextIsolation: true,
  1826. nodeIntegration: false,
  1827. preload: path.resolve(fixtures, 'module', 'empty.js')
  1828. },
  1829. show: false
  1830. });
  1831. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  1832. const [, isolated] = await emittedOnce(ipcMain, 'leak-result');
  1833. expect(isolated).to.have.property('globals');
  1834. const notIsolatedGlobals = new Set(notIsolated.globals);
  1835. for (const isolatedGlobal of isolated.globals) {
  1836. notIsolatedGlobals.delete(isolatedGlobal);
  1837. }
  1838. expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals');
  1839. });
  1840. it('loads the script before other scripts in window', async () => {
  1841. const preload = path.join(fixtures, 'module', 'set-global.js');
  1842. const w = new BrowserWindow({
  1843. show: false,
  1844. webPreferences: {
  1845. nodeIntegration: true,
  1846. contextIsolation: false,
  1847. preload
  1848. }
  1849. });
  1850. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1851. const [, test] = await emittedOnce(ipcMain, 'answer');
  1852. expect(test).to.eql('preload');
  1853. });
  1854. it('has synchronous access to all eventual window APIs', async () => {
  1855. const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
  1856. const w = new BrowserWindow({
  1857. show: false,
  1858. webPreferences: {
  1859. nodeIntegration: true,
  1860. contextIsolation: false,
  1861. preload
  1862. }
  1863. });
  1864. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1865. const [, test] = await emittedOnce(ipcMain, 'answer');
  1866. expect(test).to.be.an('object');
  1867. expect(test.atPreload).to.be.an('array');
  1868. expect(test.atLoad).to.be.an('array');
  1869. expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
  1870. });
  1871. });
  1872. describe('session preload scripts', function () {
  1873. const preloads = [
  1874. path.join(fixtures, 'module', 'set-global-preload-1.js'),
  1875. path.join(fixtures, 'module', 'set-global-preload-2.js'),
  1876. path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
  1877. ];
  1878. const defaultSession = session.defaultSession;
  1879. beforeEach(() => {
  1880. expect(defaultSession.getPreloads()).to.deep.equal([]);
  1881. defaultSession.setPreloads(preloads);
  1882. });
  1883. afterEach(() => {
  1884. defaultSession.setPreloads([]);
  1885. });
  1886. it('can set multiple session preload script', () => {
  1887. expect(defaultSession.getPreloads()).to.deep.equal(preloads);
  1888. });
  1889. const generateSpecs = (description: string, sandbox: boolean) => {
  1890. describe(description, () => {
  1891. it('loads the script before other scripts in window including normal preloads', async () => {
  1892. const w = new BrowserWindow({
  1893. show: false,
  1894. webPreferences: {
  1895. sandbox,
  1896. preload: path.join(fixtures, 'module', 'get-global-preload.js'),
  1897. contextIsolation: false
  1898. }
  1899. });
  1900. w.loadURL('about:blank');
  1901. const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars');
  1902. expect(preload1).to.equal('preload-1');
  1903. expect(preload2).to.equal('preload-1-2');
  1904. expect(preload3).to.be.undefined('preload 3');
  1905. });
  1906. });
  1907. };
  1908. generateSpecs('without sandbox', false);
  1909. generateSpecs('with sandbox', true);
  1910. });
  1911. describe('"additionalArguments" option', () => {
  1912. it('adds extra args to process.argv in the renderer process', async () => {
  1913. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  1914. const w = new BrowserWindow({
  1915. show: false,
  1916. webPreferences: {
  1917. nodeIntegration: true,
  1918. preload,
  1919. additionalArguments: ['--my-magic-arg']
  1920. }
  1921. });
  1922. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1923. const [, argv] = await emittedOnce(ipcMain, 'answer');
  1924. expect(argv).to.include('--my-magic-arg');
  1925. });
  1926. it('adds extra value args to process.argv in the renderer process', async () => {
  1927. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  1928. const w = new BrowserWindow({
  1929. show: false,
  1930. webPreferences: {
  1931. nodeIntegration: true,
  1932. preload,
  1933. additionalArguments: ['--my-magic-arg=foo']
  1934. }
  1935. });
  1936. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1937. const [, argv] = await emittedOnce(ipcMain, 'answer');
  1938. expect(argv).to.include('--my-magic-arg=foo');
  1939. });
  1940. });
  1941. describe('"node-integration" option', () => {
  1942. it('disables node integration by default', async () => {
  1943. const preload = path.join(fixtures, 'module', 'send-later.js');
  1944. const w = new BrowserWindow({
  1945. show: false,
  1946. webPreferences: {
  1947. preload,
  1948. contextIsolation: false
  1949. }
  1950. });
  1951. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1952. const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer');
  1953. expect(typeofProcess).to.equal('undefined');
  1954. expect(typeofBuffer).to.equal('undefined');
  1955. });
  1956. });
  1957. describe('"sandbox" option', () => {
  1958. const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
  1959. let server: http.Server = null as unknown as http.Server;
  1960. let serverUrl: string = null as unknown as string;
  1961. before((done) => {
  1962. server = http.createServer((request, response) => {
  1963. switch (request.url) {
  1964. case '/cross-site':
  1965. response.end(`<html><body><h1>${request.url}</h1></body></html>`);
  1966. break;
  1967. default:
  1968. throw new Error(`unsupported endpoint: ${request.url}`);
  1969. }
  1970. }).listen(0, '127.0.0.1', () => {
  1971. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  1972. done();
  1973. });
  1974. });
  1975. after(() => {
  1976. server.close();
  1977. });
  1978. it('exposes ipcRenderer to preload script', async () => {
  1979. const w = new BrowserWindow({
  1980. show: false,
  1981. webPreferences: {
  1982. sandbox: true,
  1983. preload,
  1984. contextIsolation: false
  1985. }
  1986. });
  1987. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1988. const [, test] = await emittedOnce(ipcMain, 'answer');
  1989. expect(test).to.equal('preload');
  1990. });
  1991. it('exposes ipcRenderer to preload script (path has special chars)', async () => {
  1992. const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
  1993. const w = new BrowserWindow({
  1994. show: false,
  1995. webPreferences: {
  1996. sandbox: true,
  1997. preload: preloadSpecialChars,
  1998. contextIsolation: false
  1999. }
  2000. });
  2001. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2002. const [, test] = await emittedOnce(ipcMain, 'answer');
  2003. expect(test).to.equal('preload');
  2004. });
  2005. it('exposes "loaded" event to preload script', async () => {
  2006. const w = new BrowserWindow({
  2007. show: false,
  2008. webPreferences: {
  2009. sandbox: true,
  2010. preload
  2011. }
  2012. });
  2013. w.loadURL('about:blank');
  2014. await emittedOnce(ipcMain, 'process-loaded');
  2015. });
  2016. it('exposes "exit" event to preload script', async () => {
  2017. const w = new BrowserWindow({
  2018. show: false,
  2019. webPreferences: {
  2020. sandbox: true,
  2021. preload,
  2022. contextIsolation: false
  2023. }
  2024. });
  2025. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
  2026. const pageUrl = 'file://' + htmlPath;
  2027. w.loadURL(pageUrl);
  2028. const [, url] = await emittedOnce(ipcMain, 'answer');
  2029. const expectedUrl = process.platform === 'win32'
  2030. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2031. : pageUrl;
  2032. expect(url).to.equal(expectedUrl);
  2033. });
  2034. it('should open windows in same domain with cross-scripting enabled', async () => {
  2035. const w = new BrowserWindow({
  2036. show: true,
  2037. webPreferences: {
  2038. sandbox: true,
  2039. preload,
  2040. contextIsolation: false
  2041. }
  2042. });
  2043. w.webContents.setWindowOpenHandler(() => ({
  2044. action: 'allow',
  2045. overrideBrowserWindowOptions: {
  2046. webPreferences: {
  2047. preload
  2048. }
  2049. }
  2050. }));
  2051. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
  2052. const pageUrl = 'file://' + htmlPath;
  2053. const answer = emittedOnce(ipcMain, 'answer');
  2054. w.loadURL(pageUrl);
  2055. const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window');
  2056. const expectedUrl = process.platform === 'win32'
  2057. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2058. : pageUrl;
  2059. expect(url).to.equal(expectedUrl);
  2060. expect(frameName).to.equal('popup!');
  2061. expect(options.width).to.equal(500);
  2062. expect(options.height).to.equal(600);
  2063. const [, html] = await answer;
  2064. expect(html).to.equal('<h1>scripting from opener</h1>');
  2065. });
  2066. it('should open windows in another domain with cross-scripting disabled', async () => {
  2067. const w = new BrowserWindow({
  2068. show: true,
  2069. webPreferences: {
  2070. sandbox: true,
  2071. preload,
  2072. contextIsolation: false
  2073. }
  2074. });
  2075. w.webContents.setWindowOpenHandler(() => ({
  2076. action: 'allow',
  2077. overrideBrowserWindowOptions: {
  2078. webPreferences: {
  2079. preload
  2080. }
  2081. }
  2082. }));
  2083. w.loadFile(
  2084. path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
  2085. { search: 'window-open-external' }
  2086. );
  2087. // Wait for a message from the main window saying that it's ready.
  2088. await emittedOnce(ipcMain, 'opener-loaded');
  2089. // Ask the opener to open a popup with window.opener.
  2090. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
  2091. w.webContents.send('open-the-popup', expectedPopupUrl);
  2092. // The page is going to open a popup that it won't be able to close.
  2093. // We have to close it from here later.
  2094. const [, popupWindow] = await emittedOnce(app, 'browser-window-created');
  2095. // Ask the popup window for details.
  2096. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded');
  2097. popupWindow.webContents.send('provide-details');
  2098. const [, openerIsNull, , locationHref] = await detailsAnswer;
  2099. expect(openerIsNull).to.be.false('window.opener is null');
  2100. expect(locationHref).to.equal(expectedPopupUrl);
  2101. // Ask the page to access the popup.
  2102. const touchPopupResult = emittedOnce(ipcMain, 'answer');
  2103. w.webContents.send('touch-the-popup');
  2104. const [, popupAccessMessage] = await touchPopupResult;
  2105. // Ask the popup to access the opener.
  2106. const touchOpenerResult = emittedOnce(ipcMain, 'answer');
  2107. popupWindow.webContents.send('touch-the-opener');
  2108. const [, openerAccessMessage] = await touchOpenerResult;
  2109. // We don't need the popup anymore, and its parent page can't close it,
  2110. // so let's close it from here before we run any checks.
  2111. await closeWindow(popupWindow, { assertNotWindows: false });
  2112. expect(popupAccessMessage).to.be.a('string',
  2113. 'child\'s .document is accessible from its parent window');
  2114. expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
  2115. expect(openerAccessMessage).to.be.a('string',
  2116. 'opener .document is accessible from a popup window');
  2117. expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
  2118. });
  2119. it('should inherit the sandbox setting in opened windows', async () => {
  2120. const w = new BrowserWindow({
  2121. show: false,
  2122. webPreferences: {
  2123. sandbox: true
  2124. }
  2125. });
  2126. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2127. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
  2128. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2129. const [, { argv }] = await emittedOnce(ipcMain, 'answer');
  2130. expect(argv).to.include('--enable-sandbox');
  2131. });
  2132. it('should open windows with the options configured via new-window event listeners', async () => {
  2133. const w = new BrowserWindow({
  2134. show: false,
  2135. webPreferences: {
  2136. sandbox: true
  2137. }
  2138. });
  2139. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2140. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, foo: 'bar' } } }));
  2141. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2142. const [[, childWebContents]] = await Promise.all([
  2143. emittedOnce(app, 'web-contents-created'),
  2144. emittedOnce(ipcMain, 'answer')
  2145. ]);
  2146. const webPreferences = childWebContents.getLastWebPreferences();
  2147. expect(webPreferences.foo).to.equal('bar');
  2148. });
  2149. it('should set ipc event sender correctly', async () => {
  2150. const w = new BrowserWindow({
  2151. show: false,
  2152. webPreferences: {
  2153. sandbox: true,
  2154. preload,
  2155. contextIsolation: false
  2156. }
  2157. });
  2158. let childWc: WebContents | null = null;
  2159. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
  2160. w.webContents.on('did-create-window', (win) => {
  2161. childWc = win.webContents;
  2162. expect(w.webContents).to.not.equal(childWc);
  2163. });
  2164. ipcMain.once('parent-ready', function (event) {
  2165. expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
  2166. event.sender.send('verified');
  2167. });
  2168. ipcMain.once('child-ready', function (event) {
  2169. expect(childWc).to.not.be.null('child webcontents should be available');
  2170. expect(event.sender).to.equal(childWc, 'sender should be the child');
  2171. event.sender.send('verified');
  2172. });
  2173. const done = Promise.all([
  2174. 'parent-answer',
  2175. 'child-answer'
  2176. ].map(name => emittedOnce(ipcMain, name)));
  2177. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
  2178. await done;
  2179. });
  2180. describe('event handling', () => {
  2181. let w: BrowserWindow = null as unknown as BrowserWindow;
  2182. beforeEach(() => {
  2183. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  2184. });
  2185. it('works for window events', async () => {
  2186. const pageTitleUpdated = emittedOnce(w, 'page-title-updated');
  2187. w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
  2188. await pageTitleUpdated;
  2189. });
  2190. it('works for stop events', async () => {
  2191. const done = Promise.all([
  2192. 'did-navigate',
  2193. 'did-fail-load',
  2194. 'did-stop-loading'
  2195. ].map(name => emittedOnce(w.webContents, name)));
  2196. w.loadURL('data:text/html,<script>stop()</script>');
  2197. await done;
  2198. });
  2199. it('works for web contents events', async () => {
  2200. const done = Promise.all([
  2201. 'did-finish-load',
  2202. 'did-frame-finish-load',
  2203. 'did-navigate-in-page',
  2204. 'will-navigate',
  2205. 'did-start-loading',
  2206. 'did-stop-loading',
  2207. 'did-frame-finish-load',
  2208. 'dom-ready'
  2209. ].map(name => emittedOnce(w.webContents, name)));
  2210. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
  2211. await done;
  2212. });
  2213. });
  2214. it('supports calling preventDefault on new-window events', (done) => {
  2215. const w = new BrowserWindow({
  2216. show: false,
  2217. webPreferences: {
  2218. sandbox: true
  2219. }
  2220. });
  2221. const initialWebContents = webContents.getAllWebContents().map((i) => i.id);
  2222. w.webContents.once('new-window', (e) => {
  2223. e.preventDefault();
  2224. // We need to give it some time so the windows get properly disposed (at least on OSX).
  2225. setTimeout(() => {
  2226. const currentWebContents = webContents.getAllWebContents().map((i) => i.id);
  2227. try {
  2228. expect(currentWebContents).to.deep.equal(initialWebContents);
  2229. done();
  2230. } catch (error) {
  2231. done(e);
  2232. }
  2233. }, 100);
  2234. });
  2235. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  2236. });
  2237. it('validates process APIs access in sandboxed renderer', async () => {
  2238. const w = new BrowserWindow({
  2239. show: false,
  2240. webPreferences: {
  2241. sandbox: true,
  2242. preload,
  2243. contextIsolation: false
  2244. }
  2245. });
  2246. w.webContents.once('preload-error', (event, preloadPath, error) => {
  2247. throw error;
  2248. });
  2249. process.env.sandboxmain = 'foo';
  2250. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2251. const [, test] = await emittedOnce(ipcMain, 'answer');
  2252. expect(test.hasCrash).to.be.true('has crash');
  2253. expect(test.hasHang).to.be.true('has hang');
  2254. expect(test.heapStatistics).to.be.an('object');
  2255. expect(test.blinkMemoryInfo).to.be.an('object');
  2256. expect(test.processMemoryInfo).to.be.an('object');
  2257. expect(test.systemVersion).to.be.a('string');
  2258. expect(test.cpuUsage).to.be.an('object');
  2259. expect(test.ioCounters).to.be.an('object');
  2260. expect(test.uptime).to.be.a('number');
  2261. expect(test.arch).to.equal(process.arch);
  2262. expect(test.platform).to.equal(process.platform);
  2263. expect(test.env).to.deep.equal(process.env);
  2264. expect(test.execPath).to.equal(process.helperExecPath);
  2265. expect(test.sandboxed).to.be.true('sandboxed');
  2266. expect(test.contextIsolated).to.be.false('contextIsolated');
  2267. expect(test.type).to.equal('renderer');
  2268. expect(test.version).to.equal(process.version);
  2269. expect(test.versions).to.deep.equal(process.versions);
  2270. expect(test.contextId).to.be.a('string');
  2271. if (process.platform === 'linux' && test.osSandbox) {
  2272. expect(test.creationTime).to.be.null('creation time');
  2273. expect(test.systemMemoryInfo).to.be.null('system memory info');
  2274. } else {
  2275. expect(test.creationTime).to.be.a('number');
  2276. expect(test.systemMemoryInfo).to.be.an('object');
  2277. }
  2278. });
  2279. it('webview in sandbox renderer', async () => {
  2280. const w = new BrowserWindow({
  2281. show: false,
  2282. webPreferences: {
  2283. sandbox: true,
  2284. preload,
  2285. webviewTag: true,
  2286. contextIsolation: false
  2287. }
  2288. });
  2289. const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
  2290. const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready');
  2291. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  2292. const [, webContents] = await didAttachWebview;
  2293. const [, id] = await webviewDomReady;
  2294. expect(webContents.id).to.equal(id);
  2295. });
  2296. });
  2297. describe('nativeWindowOpen option', () => {
  2298. let w: BrowserWindow = null as unknown as BrowserWindow;
  2299. beforeEach(() => {
  2300. w = new BrowserWindow({
  2301. show: false,
  2302. webPreferences: {
  2303. nodeIntegration: true,
  2304. nativeWindowOpen: true,
  2305. // tests relies on preloads in opened windows
  2306. nodeIntegrationInSubFrames: true,
  2307. contextIsolation: false
  2308. }
  2309. });
  2310. });
  2311. it('opens window of about:blank with cross-scripting enabled', async () => {
  2312. const answer = emittedOnce(ipcMain, 'answer');
  2313. w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
  2314. const [, content] = await answer;
  2315. expect(content).to.equal('Hello');
  2316. });
  2317. it('opens window of same domain with cross-scripting enabled', async () => {
  2318. const answer = emittedOnce(ipcMain, 'answer');
  2319. w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
  2320. const [, content] = await answer;
  2321. expect(content).to.equal('Hello');
  2322. });
  2323. it('blocks accessing cross-origin frames', async () => {
  2324. const answer = emittedOnce(ipcMain, 'answer');
  2325. w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
  2326. const [, content] = await answer;
  2327. expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
  2328. });
  2329. it('opens window from <iframe> tags', async () => {
  2330. const answer = emittedOnce(ipcMain, 'answer');
  2331. w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
  2332. const [, content] = await answer;
  2333. expect(content).to.equal('Hello');
  2334. });
  2335. ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
  2336. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
  2337. {
  2338. const [, content] = await emittedOnce(ipcMain, 'answer');
  2339. expect(content).to.equal('function');
  2340. }
  2341. w.reload();
  2342. {
  2343. const [, content] = await emittedOnce(ipcMain, 'answer');
  2344. expect(content).to.equal('function');
  2345. }
  2346. });
  2347. it('<webview> works in a scriptable popup', async () => {
  2348. const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
  2349. const w = new BrowserWindow({
  2350. show: false,
  2351. webPreferences: {
  2352. nodeIntegrationInSubFrames: true,
  2353. nativeWindowOpen: true,
  2354. webviewTag: true,
  2355. contextIsolation: false,
  2356. preload
  2357. }
  2358. });
  2359. w.webContents.setWindowOpenHandler(() => ({
  2360. action: 'allow',
  2361. overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nativeWindowOpen: true, nodeIntegrationInSubFrames: true } }
  2362. }));
  2363. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2364. options.show = false;
  2365. });
  2366. const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded');
  2367. w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
  2368. await webviewLoaded;
  2369. });
  2370. it('should inherit the nativeWindowOpen setting in opened windows', async () => {
  2371. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2372. w.webContents.setWindowOpenHandler(() => ({
  2373. action: 'allow',
  2374. overrideBrowserWindowOptions: {
  2375. webPreferences: {
  2376. preload: preloadPath
  2377. }
  2378. }
  2379. }));
  2380. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2381. const [, { nativeWindowOpen }] = await emittedOnce(ipcMain, 'answer');
  2382. expect(nativeWindowOpen).to.be.true();
  2383. });
  2384. it('should open windows with the options configured via new-window event listeners', async () => {
  2385. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2386. w.webContents.setWindowOpenHandler(() => ({
  2387. action: 'allow',
  2388. overrideBrowserWindowOptions: {
  2389. webPreferences: {
  2390. preload: preloadPath,
  2391. foo: 'bar'
  2392. }
  2393. }
  2394. }));
  2395. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2396. const [[, childWebContents]] = await Promise.all([
  2397. emittedOnce(app, 'web-contents-created'),
  2398. emittedOnce(ipcMain, 'answer')
  2399. ]);
  2400. const webPreferences = childWebContents.getLastWebPreferences();
  2401. expect(webPreferences.foo).to.equal('bar');
  2402. });
  2403. describe('window.location', () => {
  2404. const protocols = [
  2405. ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
  2406. ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
  2407. ];
  2408. beforeEach(() => {
  2409. for (const [scheme, path] of protocols) {
  2410. protocol.registerBufferProtocol(scheme, (request, callback) => {
  2411. callback({
  2412. mimeType: 'text/html',
  2413. data: fs.readFileSync(path)
  2414. });
  2415. });
  2416. }
  2417. });
  2418. afterEach(() => {
  2419. for (const [scheme] of protocols) {
  2420. protocol.unregisterProtocol(scheme);
  2421. }
  2422. });
  2423. it('retains the original web preferences when window.location is changed to a new origin', async () => {
  2424. const w = new BrowserWindow({
  2425. show: false,
  2426. webPreferences: {
  2427. nativeWindowOpen: true,
  2428. // test relies on preloads in opened window
  2429. nodeIntegrationInSubFrames: true,
  2430. contextIsolation: false
  2431. }
  2432. });
  2433. w.webContents.setWindowOpenHandler(() => ({
  2434. action: 'allow',
  2435. overrideBrowserWindowOptions: {
  2436. webPreferences: {
  2437. preload: path.join(fixtures, 'api', 'window-open-preload.js'),
  2438. contextIsolation: false,
  2439. nodeIntegrationInSubFrames: true
  2440. }
  2441. }
  2442. }));
  2443. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  2444. const [, { nodeIntegration, nativeWindowOpen, typeofProcess }] = await emittedOnce(ipcMain, 'answer');
  2445. expect(nodeIntegration).to.be.false();
  2446. expect(nativeWindowOpen).to.be.true();
  2447. expect(typeofProcess).to.eql('undefined');
  2448. });
  2449. it('window.opener is not null when window.location is changed to a new origin', async () => {
  2450. const w = new BrowserWindow({
  2451. show: false,
  2452. webPreferences: {
  2453. nativeWindowOpen: true,
  2454. // test relies on preloads in opened window
  2455. nodeIntegrationInSubFrames: true
  2456. }
  2457. });
  2458. w.webContents.setWindowOpenHandler(() => ({
  2459. action: 'allow',
  2460. overrideBrowserWindowOptions: {
  2461. webPreferences: {
  2462. preload: path.join(fixtures, 'api', 'window-open-preload.js')
  2463. }
  2464. }
  2465. }));
  2466. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  2467. const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer');
  2468. expect(windowOpenerIsNull).to.be.false('window.opener is null');
  2469. });
  2470. });
  2471. });
  2472. describe('"disableHtmlFullscreenWindowResize" option', () => {
  2473. it('prevents window from resizing when set', async () => {
  2474. const w = new BrowserWindow({
  2475. show: false,
  2476. webPreferences: {
  2477. disableHtmlFullscreenWindowResize: true
  2478. }
  2479. });
  2480. await w.loadURL('about:blank');
  2481. const size = w.getSize();
  2482. const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen');
  2483. w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  2484. await enterHtmlFullScreen;
  2485. expect(w.getSize()).to.deep.equal(size);
  2486. });
  2487. });
  2488. });
  2489. describe('nativeWindowOpen + contextIsolation options', () => {
  2490. afterEach(closeAllWindows);
  2491. it('opens window with cross-scripting enabled from isolated context', async () => {
  2492. const w = new BrowserWindow({
  2493. show: false,
  2494. webPreferences: {
  2495. nativeWindowOpen: true,
  2496. contextIsolation: true,
  2497. preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
  2498. }
  2499. });
  2500. w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
  2501. const [, content] = await emittedOnce(ipcMain, 'answer');
  2502. expect(content).to.equal('Hello');
  2503. });
  2504. });
  2505. describe('beforeunload handler', function () {
  2506. let w: BrowserWindow = null as unknown as BrowserWindow;
  2507. beforeEach(() => {
  2508. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  2509. });
  2510. afterEach(closeAllWindows);
  2511. it('returning undefined would not prevent close', async () => {
  2512. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  2513. const wait = emittedOnce(w, 'closed');
  2514. w.close();
  2515. await wait;
  2516. });
  2517. it('returning false would prevent close', async () => {
  2518. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  2519. w.close();
  2520. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  2521. expect(proceed).to.equal(false);
  2522. });
  2523. it('returning empty string would prevent close', async () => {
  2524. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
  2525. w.close();
  2526. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  2527. expect(proceed).to.equal(false);
  2528. });
  2529. it('emits for each close attempt', async () => {
  2530. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2531. const destroyListener = () => { expect.fail('Close was not prevented'); };
  2532. w.webContents.once('destroyed', destroyListener);
  2533. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2534. // The renderer needs to report the status of beforeunload handler
  2535. // back to main process, so wait for next console message, which means
  2536. // the SuddenTerminationStatus message have been flushed.
  2537. await emittedOnce(w.webContents, 'console-message');
  2538. w.close();
  2539. await emittedOnce(w.webContents, 'before-unload-fired');
  2540. w.close();
  2541. await emittedOnce(w.webContents, 'before-unload-fired');
  2542. w.webContents.removeListener('destroyed', destroyListener);
  2543. const wait = emittedOnce(w, 'closed');
  2544. w.close();
  2545. await wait;
  2546. });
  2547. it('emits for each reload attempt', async () => {
  2548. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2549. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  2550. w.webContents.once('did-start-navigation', navigationListener);
  2551. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2552. // The renderer needs to report the status of beforeunload handler
  2553. // back to main process, so wait for next console message, which means
  2554. // the SuddenTerminationStatus message have been flushed.
  2555. await emittedOnce(w.webContents, 'console-message');
  2556. w.reload();
  2557. // Chromium does not emit 'before-unload-fired' on WebContents for
  2558. // navigations, so we have to use other ways to know if beforeunload
  2559. // is fired.
  2560. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2561. w.reload();
  2562. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2563. w.webContents.removeListener('did-start-navigation', navigationListener);
  2564. w.reload();
  2565. await emittedOnce(w.webContents, 'did-finish-load');
  2566. });
  2567. it('emits for each navigation attempt', async () => {
  2568. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2569. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  2570. w.webContents.once('did-start-navigation', navigationListener);
  2571. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2572. // The renderer needs to report the status of beforeunload handler
  2573. // back to main process, so wait for next console message, which means
  2574. // the SuddenTerminationStatus message have been flushed.
  2575. await emittedOnce(w.webContents, 'console-message');
  2576. w.loadURL('about:blank');
  2577. // Chromium does not emit 'before-unload-fired' on WebContents for
  2578. // navigations, so we have to use other ways to know if beforeunload
  2579. // is fired.
  2580. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2581. w.loadURL('about:blank');
  2582. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2583. w.webContents.removeListener('did-start-navigation', navigationListener);
  2584. await w.loadURL('about:blank');
  2585. });
  2586. });
  2587. describe('document.visibilityState/hidden', () => {
  2588. afterEach(closeAllWindows);
  2589. it('visibilityState is initially visible despite window being hidden', async () => {
  2590. const w = new BrowserWindow({
  2591. show: false,
  2592. width: 100,
  2593. height: 100,
  2594. webPreferences: {
  2595. nodeIntegration: true,
  2596. contextIsolation: false
  2597. }
  2598. });
  2599. let readyToShow = false;
  2600. w.once('ready-to-show', () => {
  2601. readyToShow = true;
  2602. });
  2603. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2604. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2605. expect(readyToShow).to.be.false('ready to show');
  2606. expect(visibilityState).to.equal('visible');
  2607. expect(hidden).to.be.false('hidden');
  2608. });
  2609. // TODO(nornagon): figure out why this is failing on windows
  2610. ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
  2611. const w = new BrowserWindow({
  2612. width: 100,
  2613. height: 100,
  2614. webPreferences: {
  2615. nodeIntegration: true,
  2616. contextIsolation: false
  2617. }
  2618. });
  2619. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2620. {
  2621. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2622. expect(visibilityState).to.equal('visible');
  2623. expect(hidden).to.be.false('hidden');
  2624. }
  2625. w.hide();
  2626. {
  2627. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2628. expect(visibilityState).to.equal('hidden');
  2629. expect(hidden).to.be.true('hidden');
  2630. }
  2631. });
  2632. // TODO(nornagon): figure out why this is failing on windows
  2633. ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
  2634. const w = new BrowserWindow({
  2635. width: 100,
  2636. height: 100,
  2637. webPreferences: {
  2638. nodeIntegration: true,
  2639. contextIsolation: false
  2640. }
  2641. });
  2642. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2643. if (process.platform === 'darwin') {
  2644. // See https://github.com/electron/electron/issues/8664
  2645. await emittedOnce(w, 'show');
  2646. }
  2647. w.hide();
  2648. w.show();
  2649. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  2650. expect(visibilityState).to.equal('visible');
  2651. });
  2652. ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
  2653. const w = new BrowserWindow({
  2654. width: 100,
  2655. height: 100,
  2656. webPreferences: {
  2657. nodeIntegration: true,
  2658. contextIsolation: false
  2659. }
  2660. });
  2661. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2662. if (process.platform === 'darwin') {
  2663. // See https://github.com/electron/electron/issues/8664
  2664. await emittedOnce(w, 'show');
  2665. }
  2666. w.hide();
  2667. w.showInactive();
  2668. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  2669. expect(visibilityState).to.equal('visible');
  2670. });
  2671. // TODO(nornagon): figure out why this is failing on windows
  2672. ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
  2673. const w = new BrowserWindow({
  2674. width: 100,
  2675. height: 100,
  2676. webPreferences: {
  2677. nodeIntegration: true,
  2678. contextIsolation: false
  2679. }
  2680. });
  2681. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2682. {
  2683. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2684. expect(visibilityState).to.equal('visible');
  2685. expect(hidden).to.be.false('hidden');
  2686. }
  2687. w.minimize();
  2688. {
  2689. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2690. expect(visibilityState).to.equal('hidden');
  2691. expect(hidden).to.be.true('hidden');
  2692. }
  2693. });
  2694. // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
  2695. // when we introduced the compositor recycling patch. Should figure out how to fix this
  2696. it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => {
  2697. const w = new BrowserWindow({
  2698. show: false,
  2699. width: 100,
  2700. height: 100,
  2701. webPreferences: {
  2702. backgroundThrottling: false,
  2703. nodeIntegration: true
  2704. }
  2705. });
  2706. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2707. {
  2708. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2709. expect(visibilityState).to.equal('visible');
  2710. expect(hidden).to.be.false('hidden');
  2711. }
  2712. ipcMain.once('pong', (event, visibilityState, hidden) => {
  2713. throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
  2714. });
  2715. try {
  2716. const shown1 = emittedOnce(w, 'show');
  2717. w.show();
  2718. await shown1;
  2719. const hidden = emittedOnce(w, 'hide');
  2720. w.hide();
  2721. await hidden;
  2722. const shown2 = emittedOnce(w, 'show');
  2723. w.show();
  2724. await shown2;
  2725. } finally {
  2726. ipcMain.removeAllListeners('pong');
  2727. }
  2728. });
  2729. });
  2730. describe('new-window event', () => {
  2731. afterEach(closeAllWindows);
  2732. it('emits when window.open is called', (done) => {
  2733. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  2734. w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
  2735. e.preventDefault();
  2736. try {
  2737. expect(url).to.equal('http://host/');
  2738. expect(frameName).to.equal('host');
  2739. expect((options as any)['this-is-not-a-standard-feature']).to.equal(true);
  2740. done();
  2741. } catch (e) {
  2742. done(e);
  2743. }
  2744. });
  2745. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  2746. });
  2747. it('emits when window.open is called with no webPreferences', (done) => {
  2748. const w = new BrowserWindow({ show: false });
  2749. w.webContents.once('new-window', function (e, url, frameName, disposition, options) {
  2750. e.preventDefault();
  2751. try {
  2752. expect(url).to.equal('http://host/');
  2753. expect(frameName).to.equal('host');
  2754. expect((options as any)['this-is-not-a-standard-feature']).to.equal(true);
  2755. done();
  2756. } catch (e) {
  2757. done(e);
  2758. }
  2759. });
  2760. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  2761. });
  2762. it('emits when link with target is called', (done) => {
  2763. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  2764. w.webContents.once('new-window', (e, url, frameName) => {
  2765. e.preventDefault();
  2766. try {
  2767. expect(url).to.equal('http://host/');
  2768. expect(frameName).to.equal('target');
  2769. done();
  2770. } catch (e) {
  2771. done(e);
  2772. }
  2773. });
  2774. w.loadFile(path.join(fixtures, 'pages', 'target-name.html'));
  2775. });
  2776. it('includes all properties', async () => {
  2777. const w = new BrowserWindow({ show: false });
  2778. const p = new Promise<{
  2779. url: string,
  2780. frameName: string,
  2781. disposition: string,
  2782. options: BrowserWindowConstructorOptions,
  2783. additionalFeatures: string[],
  2784. referrer: Electron.Referrer,
  2785. postBody: Electron.PostBody
  2786. }>((resolve) => {
  2787. w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => {
  2788. e.preventDefault();
  2789. resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody });
  2790. });
  2791. });
  2792. w.loadURL(`data:text/html,${encodeURIComponent(`
  2793. <form target="_blank" method="POST" id="form" action="http://example.com/test">
  2794. <input type="text" name="post-test-key" value="post-test-value"></input>
  2795. </form>
  2796. <script>form.submit()</script>
  2797. `)}`);
  2798. const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p;
  2799. expect(url).to.equal('http://example.com/test');
  2800. expect(frameName).to.equal('');
  2801. expect(disposition).to.equal('foreground-tab');
  2802. expect(options).to.be.an('object').not.null();
  2803. expect(referrer.policy).to.equal('strict-origin-when-cross-origin');
  2804. expect(referrer.url).to.equal('');
  2805. expect(additionalFeatures).to.deep.equal([]);
  2806. expect(postBody.data).to.have.length(1);
  2807. expect(postBody.data[0].type).to.equal('rawData');
  2808. expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value'));
  2809. expect(postBody.contentType).to.equal('application/x-www-form-urlencoded');
  2810. });
  2811. });
  2812. ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
  2813. afterEach(closeAllWindows);
  2814. it('emits an event when window is maximized', async () => {
  2815. const w = new BrowserWindow({ show: false });
  2816. const maximize = emittedOnce(w, 'maximize');
  2817. w.show();
  2818. w.maximize();
  2819. await maximize;
  2820. });
  2821. it('emits only one event when frameless window is maximized', () => {
  2822. const w = new BrowserWindow({ show: false, frame: false });
  2823. let emitted = 0;
  2824. w.on('maximize', () => emitted++);
  2825. w.show();
  2826. w.maximize();
  2827. expect(emitted).to.equal(1);
  2828. });
  2829. it('emits an event when window is unmaximized', async () => {
  2830. const w = new BrowserWindow({ show: false });
  2831. const unmaximize = emittedOnce(w, 'unmaximize');
  2832. w.show();
  2833. w.maximize();
  2834. w.unmaximize();
  2835. await unmaximize;
  2836. });
  2837. it('emits an event when window is minimized', async () => {
  2838. const w = new BrowserWindow({ show: false });
  2839. const minimize = emittedOnce(w, 'minimize');
  2840. w.show();
  2841. w.minimize();
  2842. await minimize;
  2843. });
  2844. });
  2845. describe('beginFrameSubscription method', () => {
  2846. it('does not crash when callback returns nothing', (done) => {
  2847. const w = new BrowserWindow({ show: false });
  2848. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  2849. w.webContents.on('dom-ready', () => {
  2850. w.webContents.beginFrameSubscription(function () {
  2851. // Pending endFrameSubscription to next tick can reliably reproduce
  2852. // a crash which happens when nothing is returned in the callback.
  2853. setTimeout(() => {
  2854. w.webContents.endFrameSubscription();
  2855. done();
  2856. });
  2857. });
  2858. });
  2859. });
  2860. it('subscribes to frame updates', (done) => {
  2861. const w = new BrowserWindow({ show: false });
  2862. let called = false;
  2863. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  2864. w.webContents.on('dom-ready', () => {
  2865. w.webContents.beginFrameSubscription(function (data) {
  2866. // This callback might be called twice.
  2867. if (called) return;
  2868. called = true;
  2869. try {
  2870. expect(data.constructor.name).to.equal('NativeImage');
  2871. expect(data.isEmpty()).to.be.false('data is empty');
  2872. done();
  2873. } catch (e) {
  2874. done(e);
  2875. } finally {
  2876. w.webContents.endFrameSubscription();
  2877. }
  2878. });
  2879. });
  2880. });
  2881. it('subscribes to frame updates (only dirty rectangle)', (done) => {
  2882. const w = new BrowserWindow({ show: false });
  2883. let called = false;
  2884. let gotInitialFullSizeFrame = false;
  2885. const [contentWidth, contentHeight] = w.getContentSize();
  2886. w.webContents.on('did-finish-load', () => {
  2887. w.webContents.beginFrameSubscription(true, (image, rect) => {
  2888. if (image.isEmpty()) {
  2889. // Chromium sometimes sends a 0x0 frame at the beginning of the
  2890. // page load.
  2891. return;
  2892. }
  2893. if (rect.height === contentHeight && rect.width === contentWidth &&
  2894. !gotInitialFullSizeFrame) {
  2895. // The initial frame is full-size, but we're looking for a call
  2896. // with just the dirty-rect. The next frame should be a smaller
  2897. // rect.
  2898. gotInitialFullSizeFrame = true;
  2899. return;
  2900. }
  2901. // This callback might be called twice.
  2902. if (called) return;
  2903. // We asked for just the dirty rectangle, so we expect to receive a
  2904. // rect smaller than the full size.
  2905. // TODO(jeremy): this is failing on windows currently; investigate.
  2906. // assert(rect.width < contentWidth || rect.height < contentHeight)
  2907. called = true;
  2908. try {
  2909. const expectedSize = rect.width * rect.height * 4;
  2910. expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
  2911. done();
  2912. } catch (e) {
  2913. done(e);
  2914. } finally {
  2915. w.webContents.endFrameSubscription();
  2916. }
  2917. });
  2918. });
  2919. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  2920. });
  2921. it('throws error when subscriber is not well defined', () => {
  2922. const w = new BrowserWindow({ show: false });
  2923. expect(() => {
  2924. w.webContents.beginFrameSubscription(true, true as any);
  2925. // TODO(zcbenz): gin is weak at guessing parameter types, we should
  2926. // upstream native_mate's implementation to gin.
  2927. }).to.throw('Error processing argument at index 1, conversion failure from ');
  2928. });
  2929. });
  2930. describe('savePage method', () => {
  2931. const savePageDir = path.join(fixtures, 'save_page');
  2932. const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
  2933. const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
  2934. const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
  2935. after(() => {
  2936. try {
  2937. fs.unlinkSync(savePageCssPath);
  2938. fs.unlinkSync(savePageJsPath);
  2939. fs.unlinkSync(savePageHtmlPath);
  2940. fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
  2941. fs.rmdirSync(savePageDir);
  2942. } catch (e) {
  2943. // Ignore error
  2944. }
  2945. });
  2946. afterEach(closeAllWindows);
  2947. it('should save page to disk', async () => {
  2948. const w = new BrowserWindow({ show: false });
  2949. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  2950. await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
  2951. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  2952. expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
  2953. expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
  2954. });
  2955. });
  2956. describe('BrowserWindow options argument is optional', () => {
  2957. afterEach(closeAllWindows);
  2958. it('should create a window with default size (800x600)', () => {
  2959. const w = new BrowserWindow();
  2960. expect(w.getSize()).to.deep.equal([800, 600]);
  2961. });
  2962. });
  2963. describe('BrowserWindow.restore()', () => {
  2964. afterEach(closeAllWindows);
  2965. it('should restore the previous window size', () => {
  2966. const w = new BrowserWindow({
  2967. minWidth: 800,
  2968. width: 800
  2969. });
  2970. const initialSize = w.getSize();
  2971. w.minimize();
  2972. w.restore();
  2973. expectBoundsEqual(w.getSize(), initialSize);
  2974. });
  2975. it('does not crash when restoring hidden minimized window', () => {
  2976. const w = new BrowserWindow({});
  2977. w.minimize();
  2978. w.hide();
  2979. w.show();
  2980. });
  2981. });
  2982. describe('BrowserWindow.unmaximize()', () => {
  2983. afterEach(closeAllWindows);
  2984. it('should restore the previous window position', () => {
  2985. const w = new BrowserWindow();
  2986. const initialPosition = w.getPosition();
  2987. w.maximize();
  2988. w.unmaximize();
  2989. expectBoundsEqual(w.getPosition(), initialPosition);
  2990. });
  2991. });
  2992. describe('setFullScreen(false)', () => {
  2993. afterEach(closeAllWindows);
  2994. // only applicable to windows: https://github.com/electron/electron/issues/6036
  2995. ifdescribe(process.platform === 'win32')('on windows', () => {
  2996. it('should restore a normal visible window from a fullscreen startup state', async () => {
  2997. const w = new BrowserWindow({ show: false });
  2998. await w.loadURL('about:blank');
  2999. const shown = emittedOnce(w, 'show');
  3000. // start fullscreen and hidden
  3001. w.setFullScreen(true);
  3002. w.show();
  3003. await shown;
  3004. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3005. w.setFullScreen(false);
  3006. await leftFullScreen;
  3007. expect(w.isVisible()).to.be.true('visible');
  3008. expect(w.isFullScreen()).to.be.false('fullscreen');
  3009. });
  3010. it('should keep window hidden if already in hidden state', async () => {
  3011. const w = new BrowserWindow({ show: false });
  3012. await w.loadURL('about:blank');
  3013. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3014. w.setFullScreen(false);
  3015. await leftFullScreen;
  3016. expect(w.isVisible()).to.be.false('visible');
  3017. expect(w.isFullScreen()).to.be.false('fullscreen');
  3018. });
  3019. });
  3020. ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
  3021. it('exits HTML fullscreen when window leaves fullscreen', async () => {
  3022. const w = new BrowserWindow();
  3023. await w.loadURL('about:blank');
  3024. await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  3025. await emittedOnce(w, 'enter-full-screen');
  3026. // Wait a tick for the full-screen state to 'stick'
  3027. await delay();
  3028. w.setFullScreen(false);
  3029. await emittedOnce(w, 'leave-html-full-screen');
  3030. });
  3031. });
  3032. });
  3033. describe('parent window', () => {
  3034. afterEach(closeAllWindows);
  3035. ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
  3036. const w = new BrowserWindow();
  3037. const sheetBegin = emittedOnce(w, 'sheet-begin');
  3038. // eslint-disable-next-line no-new
  3039. new BrowserWindow({
  3040. modal: true,
  3041. parent: w
  3042. });
  3043. await sheetBegin;
  3044. });
  3045. ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
  3046. const w = new BrowserWindow();
  3047. const sheet = new BrowserWindow({
  3048. modal: true,
  3049. parent: w
  3050. });
  3051. const sheetEnd = emittedOnce(w, 'sheet-end');
  3052. sheet.close();
  3053. await sheetEnd;
  3054. });
  3055. describe('parent option', () => {
  3056. it('sets parent window', () => {
  3057. const w = new BrowserWindow({ show: false });
  3058. const c = new BrowserWindow({ show: false, parent: w });
  3059. expect(c.getParentWindow()).to.equal(w);
  3060. });
  3061. it('adds window to child windows of parent', () => {
  3062. const w = new BrowserWindow({ show: false });
  3063. const c = new BrowserWindow({ show: false, parent: w });
  3064. expect(w.getChildWindows()).to.deep.equal([c]);
  3065. });
  3066. it('removes from child windows of parent when window is closed', async () => {
  3067. const w = new BrowserWindow({ show: false });
  3068. const c = new BrowserWindow({ show: false, parent: w });
  3069. const closed = emittedOnce(c, 'closed');
  3070. c.close();
  3071. await closed;
  3072. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3073. await delay();
  3074. expect(w.getChildWindows().length).to.equal(0);
  3075. });
  3076. it('should not affect the show option', () => {
  3077. const w = new BrowserWindow({ show: false });
  3078. const c = new BrowserWindow({ show: false, parent: w });
  3079. expect(c.isVisible()).to.be.false('child is visible');
  3080. expect(c.getParentWindow().isVisible()).to.be.false('parent is visible');
  3081. });
  3082. });
  3083. describe('win.setParentWindow(parent)', () => {
  3084. it('sets parent window', () => {
  3085. const w = new BrowserWindow({ show: false });
  3086. const c = new BrowserWindow({ show: false });
  3087. expect(w.getParentWindow()).to.be.null('w.parent');
  3088. expect(c.getParentWindow()).to.be.null('c.parent');
  3089. c.setParentWindow(w);
  3090. expect(c.getParentWindow()).to.equal(w);
  3091. c.setParentWindow(null);
  3092. expect(c.getParentWindow()).to.be.null('c.parent');
  3093. });
  3094. it('adds window to child windows of parent', () => {
  3095. const w = new BrowserWindow({ show: false });
  3096. const c = new BrowserWindow({ show: false });
  3097. expect(w.getChildWindows()).to.deep.equal([]);
  3098. c.setParentWindow(w);
  3099. expect(w.getChildWindows()).to.deep.equal([c]);
  3100. c.setParentWindow(null);
  3101. expect(w.getChildWindows()).to.deep.equal([]);
  3102. });
  3103. it('removes from child windows of parent when window is closed', async () => {
  3104. const w = new BrowserWindow({ show: false });
  3105. const c = new BrowserWindow({ show: false });
  3106. const closed = emittedOnce(c, 'closed');
  3107. c.setParentWindow(w);
  3108. c.close();
  3109. await closed;
  3110. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3111. await delay();
  3112. expect(w.getChildWindows().length).to.equal(0);
  3113. });
  3114. });
  3115. describe('modal option', () => {
  3116. it('does not freeze or crash', async () => {
  3117. const parentWindow = new BrowserWindow();
  3118. const createTwo = async () => {
  3119. const two = new BrowserWindow({
  3120. width: 300,
  3121. height: 200,
  3122. parent: parentWindow,
  3123. modal: true,
  3124. show: false
  3125. });
  3126. const twoShown = emittedOnce(two, 'show');
  3127. two.show();
  3128. await twoShown;
  3129. setTimeout(() => two.close(), 500);
  3130. await emittedOnce(two, 'closed');
  3131. };
  3132. const one = new BrowserWindow({
  3133. width: 600,
  3134. height: 400,
  3135. parent: parentWindow,
  3136. modal: true,
  3137. show: false
  3138. });
  3139. const oneShown = emittedOnce(one, 'show');
  3140. one.show();
  3141. await oneShown;
  3142. setTimeout(() => one.destroy(), 500);
  3143. await emittedOnce(one, 'closed');
  3144. await createTwo();
  3145. });
  3146. ifit(process.platform !== 'darwin')('disables parent window', () => {
  3147. const w = new BrowserWindow({ show: false });
  3148. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3149. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3150. c.show();
  3151. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3152. });
  3153. ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
  3154. const w = new BrowserWindow({ show: false });
  3155. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3156. const closed = emittedOnce(c, 'closed');
  3157. c.show();
  3158. c.close();
  3159. await closed;
  3160. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3161. });
  3162. ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
  3163. const w = new BrowserWindow({ show: false });
  3164. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3165. const closed = emittedOnce(c, 'closed');
  3166. w.setEnabled(false);
  3167. c.show();
  3168. c.close();
  3169. await closed;
  3170. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3171. });
  3172. ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
  3173. const w = new BrowserWindow({ show: false });
  3174. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3175. const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
  3176. c.show();
  3177. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3178. c2.show();
  3179. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3180. c.destroy();
  3181. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3182. c2.destroy();
  3183. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3184. });
  3185. });
  3186. });
  3187. describe('window states', () => {
  3188. afterEach(closeAllWindows);
  3189. it('does not resize frameless windows when states change', () => {
  3190. const w = new BrowserWindow({
  3191. frame: false,
  3192. width: 300,
  3193. height: 200,
  3194. show: false
  3195. });
  3196. w.minimizable = false;
  3197. w.minimizable = true;
  3198. expect(w.getSize()).to.deep.equal([300, 200]);
  3199. w.resizable = false;
  3200. w.resizable = true;
  3201. expect(w.getSize()).to.deep.equal([300, 200]);
  3202. w.maximizable = false;
  3203. w.maximizable = true;
  3204. expect(w.getSize()).to.deep.equal([300, 200]);
  3205. w.fullScreenable = false;
  3206. w.fullScreenable = true;
  3207. expect(w.getSize()).to.deep.equal([300, 200]);
  3208. w.closable = false;
  3209. w.closable = true;
  3210. expect(w.getSize()).to.deep.equal([300, 200]);
  3211. });
  3212. describe('resizable state', () => {
  3213. it('with properties', () => {
  3214. it('can be set with resizable constructor option', () => {
  3215. const w = new BrowserWindow({ show: false, resizable: false });
  3216. expect(w.resizable).to.be.false('resizable');
  3217. if (process.platform === 'darwin') {
  3218. expect(w.maximizable).to.to.true('maximizable');
  3219. }
  3220. });
  3221. it('can be changed', () => {
  3222. const w = new BrowserWindow({ show: false });
  3223. expect(w.resizable).to.be.true('resizable');
  3224. w.resizable = false;
  3225. expect(w.resizable).to.be.false('resizable');
  3226. w.resizable = true;
  3227. expect(w.resizable).to.be.true('resizable');
  3228. });
  3229. });
  3230. it('with functions', () => {
  3231. it('can be set with resizable constructor option', () => {
  3232. const w = new BrowserWindow({ show: false, resizable: false });
  3233. expect(w.isResizable()).to.be.false('resizable');
  3234. if (process.platform === 'darwin') {
  3235. expect(w.isMaximizable()).to.to.true('maximizable');
  3236. }
  3237. });
  3238. it('can be changed', () => {
  3239. const w = new BrowserWindow({ show: false });
  3240. expect(w.isResizable()).to.be.true('resizable');
  3241. w.setResizable(false);
  3242. expect(w.isResizable()).to.be.false('resizable');
  3243. w.setResizable(true);
  3244. expect(w.isResizable()).to.be.true('resizable');
  3245. });
  3246. });
  3247. it('works for a frameless window', () => {
  3248. const w = new BrowserWindow({ show: false, frame: false });
  3249. expect(w.resizable).to.be.true('resizable');
  3250. if (process.platform === 'win32') {
  3251. const w = new BrowserWindow({ show: false, thickFrame: false });
  3252. expect(w.resizable).to.be.false('resizable');
  3253. }
  3254. });
  3255. ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
  3256. const w = new BrowserWindow({
  3257. show: false,
  3258. frame: false,
  3259. resizable: false,
  3260. transparent: true
  3261. });
  3262. w.setContentSize(60, 60);
  3263. expectBoundsEqual(w.getContentSize(), [60, 60]);
  3264. w.setContentSize(30, 30);
  3265. expectBoundsEqual(w.getContentSize(), [30, 30]);
  3266. w.setContentSize(10, 10);
  3267. expectBoundsEqual(w.getContentSize(), [10, 10]);
  3268. });
  3269. });
  3270. describe('loading main frame state', () => {
  3271. let server: http.Server = null as unknown as http.Server;
  3272. let serverUrl: string = null as unknown as string;
  3273. before((done) => {
  3274. server = http.createServer((request, response) => {
  3275. response.end();
  3276. }).listen(0, '127.0.0.1', () => {
  3277. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  3278. done();
  3279. });
  3280. });
  3281. after(() => {
  3282. server.close();
  3283. });
  3284. it('is true when the main frame is loading', async () => {
  3285. const w = new BrowserWindow({ show: false });
  3286. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3287. w.webContents.loadURL(serverUrl);
  3288. await didStartLoading;
  3289. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3290. });
  3291. it('is false when only a subframe is loading', async () => {
  3292. const w = new BrowserWindow({ show: false });
  3293. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3294. w.webContents.loadURL(serverUrl);
  3295. await didStopLoading;
  3296. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3297. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3298. w.webContents.executeJavaScript(`
  3299. var iframe = document.createElement('iframe')
  3300. iframe.src = '${serverUrl}/page2'
  3301. document.body.appendChild(iframe)
  3302. `);
  3303. await didStartLoading;
  3304. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3305. });
  3306. it('is true when navigating to pages from the same origin', async () => {
  3307. const w = new BrowserWindow({ show: false });
  3308. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3309. w.webContents.loadURL(serverUrl);
  3310. await didStopLoading;
  3311. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3312. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3313. w.webContents.loadURL(`${serverUrl}/page2`);
  3314. await didStartLoading;
  3315. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3316. });
  3317. });
  3318. });
  3319. ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
  3320. // Not implemented on Linux.
  3321. afterEach(closeAllWindows);
  3322. describe('movable state', () => {
  3323. it('with properties', () => {
  3324. it('can be set with movable constructor option', () => {
  3325. const w = new BrowserWindow({ show: false, movable: false });
  3326. expect(w.movable).to.be.false('movable');
  3327. });
  3328. it('can be changed', () => {
  3329. const w = new BrowserWindow({ show: false });
  3330. expect(w.movable).to.be.true('movable');
  3331. w.movable = false;
  3332. expect(w.movable).to.be.false('movable');
  3333. w.movable = true;
  3334. expect(w.movable).to.be.true('movable');
  3335. });
  3336. });
  3337. it('with functions', () => {
  3338. it('can be set with movable constructor option', () => {
  3339. const w = new BrowserWindow({ show: false, movable: false });
  3340. expect(w.isMovable()).to.be.false('movable');
  3341. });
  3342. it('can be changed', () => {
  3343. const w = new BrowserWindow({ show: false });
  3344. expect(w.isMovable()).to.be.true('movable');
  3345. w.setMovable(false);
  3346. expect(w.isMovable()).to.be.false('movable');
  3347. w.setMovable(true);
  3348. expect(w.isMovable()).to.be.true('movable');
  3349. });
  3350. });
  3351. });
  3352. describe('visibleOnAllWorkspaces state', () => {
  3353. it('with properties', () => {
  3354. it('can be changed', () => {
  3355. const w = new BrowserWindow({ show: false });
  3356. expect(w.visibleOnAllWorkspaces).to.be.false();
  3357. w.visibleOnAllWorkspaces = true;
  3358. expect(w.visibleOnAllWorkspaces).to.be.true();
  3359. });
  3360. });
  3361. it('with functions', () => {
  3362. it('can be changed', () => {
  3363. const w = new BrowserWindow({ show: false });
  3364. expect(w.isVisibleOnAllWorkspaces()).to.be.false();
  3365. w.setVisibleOnAllWorkspaces(true);
  3366. expect(w.isVisibleOnAllWorkspaces()).to.be.true();
  3367. });
  3368. });
  3369. });
  3370. ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
  3371. it('with properties', () => {
  3372. it('can be changed', () => {
  3373. const w = new BrowserWindow({ show: false });
  3374. expect(w.documentEdited).to.be.false();
  3375. w.documentEdited = true;
  3376. expect(w.documentEdited).to.be.true();
  3377. });
  3378. });
  3379. it('with functions', () => {
  3380. it('can be changed', () => {
  3381. const w = new BrowserWindow({ show: false });
  3382. expect(w.isDocumentEdited()).to.be.false();
  3383. w.setDocumentEdited(true);
  3384. expect(w.isDocumentEdited()).to.be.true();
  3385. });
  3386. });
  3387. });
  3388. ifdescribe(process.platform === 'darwin')('representedFilename', () => {
  3389. it('with properties', () => {
  3390. it('can be changed', () => {
  3391. const w = new BrowserWindow({ show: false });
  3392. expect(w.representedFilename).to.eql('');
  3393. w.representedFilename = 'a name';
  3394. expect(w.representedFilename).to.eql('a name');
  3395. });
  3396. });
  3397. it('with functions', () => {
  3398. it('can be changed', () => {
  3399. const w = new BrowserWindow({ show: false });
  3400. expect(w.getRepresentedFilename()).to.eql('');
  3401. w.setRepresentedFilename('a name');
  3402. expect(w.getRepresentedFilename()).to.eql('a name');
  3403. });
  3404. });
  3405. });
  3406. describe('native window title', () => {
  3407. it('with properties', () => {
  3408. it('can be set with title constructor option', () => {
  3409. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  3410. expect(w.title).to.eql('mYtItLe');
  3411. });
  3412. it('can be changed', () => {
  3413. const w = new BrowserWindow({ show: false });
  3414. expect(w.title).to.eql('Electron Test Main');
  3415. w.title = 'NEW TITLE';
  3416. expect(w.title).to.eql('NEW TITLE');
  3417. });
  3418. });
  3419. it('with functions', () => {
  3420. it('can be set with minimizable constructor option', () => {
  3421. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  3422. expect(w.getTitle()).to.eql('mYtItLe');
  3423. });
  3424. it('can be changed', () => {
  3425. const w = new BrowserWindow({ show: false });
  3426. expect(w.getTitle()).to.eql('Electron Test Main');
  3427. w.setTitle('NEW TITLE');
  3428. expect(w.getTitle()).to.eql('NEW TITLE');
  3429. });
  3430. });
  3431. });
  3432. describe('minimizable state', () => {
  3433. it('with properties', () => {
  3434. it('can be set with minimizable constructor option', () => {
  3435. const w = new BrowserWindow({ show: false, minimizable: false });
  3436. expect(w.minimizable).to.be.false('minimizable');
  3437. });
  3438. it('can be changed', () => {
  3439. const w = new BrowserWindow({ show: false });
  3440. expect(w.minimizable).to.be.true('minimizable');
  3441. w.minimizable = false;
  3442. expect(w.minimizable).to.be.false('minimizable');
  3443. w.minimizable = true;
  3444. expect(w.minimizable).to.be.true('minimizable');
  3445. });
  3446. });
  3447. it('with functions', () => {
  3448. it('can be set with minimizable constructor option', () => {
  3449. const w = new BrowserWindow({ show: false, minimizable: false });
  3450. expect(w.isMinimizable()).to.be.false('movable');
  3451. });
  3452. it('can be changed', () => {
  3453. const w = new BrowserWindow({ show: false });
  3454. expect(w.isMinimizable()).to.be.true('isMinimizable');
  3455. w.setMinimizable(false);
  3456. expect(w.isMinimizable()).to.be.false('isMinimizable');
  3457. w.setMinimizable(true);
  3458. expect(w.isMinimizable()).to.be.true('isMinimizable');
  3459. });
  3460. });
  3461. });
  3462. describe('maximizable state (property)', () => {
  3463. it('with properties', () => {
  3464. it('can be set with maximizable constructor option', () => {
  3465. const w = new BrowserWindow({ show: false, maximizable: false });
  3466. expect(w.maximizable).to.be.false('maximizable');
  3467. });
  3468. it('can be changed', () => {
  3469. const w = new BrowserWindow({ show: false });
  3470. expect(w.maximizable).to.be.true('maximizable');
  3471. w.maximizable = false;
  3472. expect(w.maximizable).to.be.false('maximizable');
  3473. w.maximizable = true;
  3474. expect(w.maximizable).to.be.true('maximizable');
  3475. });
  3476. it('is not affected when changing other states', () => {
  3477. const w = new BrowserWindow({ show: false });
  3478. w.maximizable = false;
  3479. expect(w.maximizable).to.be.false('maximizable');
  3480. w.minimizable = false;
  3481. expect(w.maximizable).to.be.false('maximizable');
  3482. w.closable = false;
  3483. expect(w.maximizable).to.be.false('maximizable');
  3484. w.maximizable = true;
  3485. expect(w.maximizable).to.be.true('maximizable');
  3486. w.closable = true;
  3487. expect(w.maximizable).to.be.true('maximizable');
  3488. w.fullScreenable = false;
  3489. expect(w.maximizable).to.be.true('maximizable');
  3490. });
  3491. });
  3492. it('with functions', () => {
  3493. it('can be set with maximizable constructor option', () => {
  3494. const w = new BrowserWindow({ show: false, maximizable: false });
  3495. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3496. });
  3497. it('can be changed', () => {
  3498. const w = new BrowserWindow({ show: false });
  3499. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3500. w.setMaximizable(false);
  3501. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3502. w.setMaximizable(true);
  3503. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3504. });
  3505. it('is not affected when changing other states', () => {
  3506. const w = new BrowserWindow({ show: false });
  3507. w.setMaximizable(false);
  3508. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3509. w.setMinimizable(false);
  3510. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3511. w.setClosable(false);
  3512. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3513. w.setMaximizable(true);
  3514. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3515. w.setClosable(true);
  3516. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3517. w.setFullScreenable(false);
  3518. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3519. });
  3520. });
  3521. });
  3522. ifdescribe(process.platform === 'win32')('maximizable state', () => {
  3523. it('with properties', () => {
  3524. it('is reset to its former state', () => {
  3525. const w = new BrowserWindow({ show: false });
  3526. w.maximizable = false;
  3527. w.resizable = false;
  3528. w.resizable = true;
  3529. expect(w.maximizable).to.be.false('maximizable');
  3530. w.maximizable = true;
  3531. w.resizable = false;
  3532. w.resizable = true;
  3533. expect(w.maximizable).to.be.true('maximizable');
  3534. });
  3535. });
  3536. it('with functions', () => {
  3537. it('is reset to its former state', () => {
  3538. const w = new BrowserWindow({ show: false });
  3539. w.setMaximizable(false);
  3540. w.setResizable(false);
  3541. w.setResizable(true);
  3542. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3543. w.setMaximizable(true);
  3544. w.setResizable(false);
  3545. w.setResizable(true);
  3546. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3547. });
  3548. });
  3549. });
  3550. ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
  3551. describe('with properties', () => {
  3552. it('can be changed', () => {
  3553. const w = new BrowserWindow({ show: false });
  3554. expect(w.menuBarVisible).to.be.true();
  3555. w.menuBarVisible = false;
  3556. expect(w.menuBarVisible).to.be.false();
  3557. w.menuBarVisible = true;
  3558. expect(w.menuBarVisible).to.be.true();
  3559. });
  3560. });
  3561. describe('with functions', () => {
  3562. it('can be changed', () => {
  3563. const w = new BrowserWindow({ show: false });
  3564. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  3565. w.setMenuBarVisibility(false);
  3566. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  3567. w.setMenuBarVisibility(true);
  3568. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  3569. });
  3570. });
  3571. });
  3572. ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
  3573. it('with functions', () => {
  3574. it('can be set with fullscreenable constructor option', () => {
  3575. const w = new BrowserWindow({ show: false, fullscreenable: false });
  3576. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  3577. });
  3578. it('can be changed', () => {
  3579. const w = new BrowserWindow({ show: false });
  3580. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  3581. w.setFullScreenable(false);
  3582. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  3583. w.setFullScreenable(true);
  3584. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  3585. });
  3586. });
  3587. });
  3588. // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
  3589. ifdescribe(process.platform === 'darwin')('kiosk state', () => {
  3590. it('with properties', () => {
  3591. it('can be set with a constructor property', () => {
  3592. const w = new BrowserWindow({ kiosk: true });
  3593. expect(w.kiosk).to.be.true();
  3594. });
  3595. it('can be changed ', async () => {
  3596. const w = new BrowserWindow();
  3597. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3598. w.kiosk = true;
  3599. expect(w.isKiosk()).to.be.true('isKiosk');
  3600. await enterFullScreen;
  3601. await delay();
  3602. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3603. w.kiosk = false;
  3604. expect(w.isKiosk()).to.be.false('isKiosk');
  3605. await leaveFullScreen;
  3606. });
  3607. });
  3608. it('with functions', () => {
  3609. it('can be set with a constructor property', () => {
  3610. const w = new BrowserWindow({ kiosk: true });
  3611. expect(w.isKiosk()).to.be.true();
  3612. });
  3613. it('can be changed ', async () => {
  3614. const w = new BrowserWindow();
  3615. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3616. w.setKiosk(true);
  3617. expect(w.isKiosk()).to.be.true('isKiosk');
  3618. await enterFullScreen;
  3619. await delay();
  3620. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3621. w.setKiosk(false);
  3622. expect(w.isKiosk()).to.be.false('isKiosk');
  3623. await leaveFullScreen;
  3624. });
  3625. });
  3626. });
  3627. ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
  3628. it('resizable flag should be set to true and restored', async () => {
  3629. const w = new BrowserWindow({ resizable: false });
  3630. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3631. w.setFullScreen(true);
  3632. await enterFullScreen;
  3633. expect(w.resizable).to.be.true('resizable');
  3634. await delay();
  3635. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3636. w.setFullScreen(false);
  3637. await leaveFullScreen;
  3638. expect(w.resizable).to.be.false('resizable');
  3639. });
  3640. });
  3641. ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
  3642. it('should not cause a crash if called when exiting fullscreen', async () => {
  3643. const w = new BrowserWindow();
  3644. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3645. w.setFullScreen(true);
  3646. await enterFullScreen;
  3647. await delay();
  3648. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3649. w.setFullScreen(false);
  3650. await leaveFullScreen;
  3651. w.close();
  3652. });
  3653. it('can be changed with setFullScreen method', async () => {
  3654. const w = new BrowserWindow();
  3655. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3656. w.setFullScreen(true);
  3657. await enterFullScreen;
  3658. expect(w.isFullScreen()).to.be.true('isFullScreen');
  3659. await delay();
  3660. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3661. w.setFullScreen(false);
  3662. await leaveFullScreen;
  3663. expect(w.isFullScreen()).to.be.false('isFullScreen');
  3664. });
  3665. it('handles several transitions starting with fullscreen', async () => {
  3666. const w = new BrowserWindow({ fullscreen: true, show: true });
  3667. expect(w.isFullScreen()).to.be.true('not fullscreen');
  3668. w.setFullScreen(false);
  3669. w.setFullScreen(true);
  3670. const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
  3671. await enterFullScreen;
  3672. expect(w.isFullScreen()).to.be.true('not fullscreen');
  3673. await delay();
  3674. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3675. w.setFullScreen(false);
  3676. await leaveFullScreen;
  3677. expect(w.isFullScreen()).to.be.false('is fullscreen');
  3678. });
  3679. it('handles several transitions in close proximity', async () => {
  3680. const w = new BrowserWindow();
  3681. expect(w.isFullScreen()).to.be.false('is fullscreen');
  3682. w.setFullScreen(true);
  3683. w.setFullScreen(false);
  3684. w.setFullScreen(true);
  3685. const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
  3686. await enterFullScreen;
  3687. expect(w.isFullScreen()).to.be.true('not fullscreen');
  3688. });
  3689. it('does not crash when exiting simpleFullScreen (properties)', async () => {
  3690. const w = new BrowserWindow();
  3691. w.setSimpleFullScreen(true);
  3692. await delay(1000);
  3693. w.setFullScreen(!w.isFullScreen());
  3694. });
  3695. it('does not crash when exiting simpleFullScreen (functions)', async () => {
  3696. const w = new BrowserWindow();
  3697. w.simpleFullScreen = true;
  3698. await delay(1000);
  3699. w.setFullScreen(!w.isFullScreen());
  3700. });
  3701. it('should not be changed by setKiosk method', async () => {
  3702. const w = new BrowserWindow();
  3703. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3704. w.setFullScreen(true);
  3705. await enterFullScreen;
  3706. expect(w.isFullScreen()).to.be.true('isFullScreen');
  3707. await delay();
  3708. w.setKiosk(true);
  3709. await delay();
  3710. w.setKiosk(false);
  3711. expect(w.isFullScreen()).to.be.true('isFullScreen');
  3712. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3713. w.setFullScreen(false);
  3714. await leaveFullScreen;
  3715. expect(w.isFullScreen()).to.be.false('isFullScreen');
  3716. });
  3717. });
  3718. describe('closable state', () => {
  3719. it('with properties', () => {
  3720. it('can be set with closable constructor option', () => {
  3721. const w = new BrowserWindow({ show: false, closable: false });
  3722. expect(w.closable).to.be.false('closable');
  3723. });
  3724. it('can be changed', () => {
  3725. const w = new BrowserWindow({ show: false });
  3726. expect(w.closable).to.be.true('closable');
  3727. w.closable = false;
  3728. expect(w.closable).to.be.false('closable');
  3729. w.closable = true;
  3730. expect(w.closable).to.be.true('closable');
  3731. });
  3732. });
  3733. it('with functions', () => {
  3734. it('can be set with closable constructor option', () => {
  3735. const w = new BrowserWindow({ show: false, closable: false });
  3736. expect(w.isClosable()).to.be.false('isClosable');
  3737. });
  3738. it('can be changed', () => {
  3739. const w = new BrowserWindow({ show: false });
  3740. expect(w.isClosable()).to.be.true('isClosable');
  3741. w.setClosable(false);
  3742. expect(w.isClosable()).to.be.false('isClosable');
  3743. w.setClosable(true);
  3744. expect(w.isClosable()).to.be.true('isClosable');
  3745. });
  3746. });
  3747. });
  3748. describe('hasShadow state', () => {
  3749. it('with properties', () => {
  3750. it('returns a boolean on all platforms', () => {
  3751. const w = new BrowserWindow({ show: false });
  3752. expect(w.shadow).to.be.a('boolean');
  3753. });
  3754. // On Windows there's no shadow by default & it can't be changed dynamically.
  3755. it('can be changed with hasShadow option', () => {
  3756. const hasShadow = process.platform !== 'darwin';
  3757. const w = new BrowserWindow({ show: false, hasShadow });
  3758. expect(w.shadow).to.equal(hasShadow);
  3759. });
  3760. it('can be changed with setHasShadow method', () => {
  3761. const w = new BrowserWindow({ show: false });
  3762. w.shadow = false;
  3763. expect(w.shadow).to.be.false('hasShadow');
  3764. w.shadow = true;
  3765. expect(w.shadow).to.be.true('hasShadow');
  3766. w.shadow = false;
  3767. expect(w.shadow).to.be.false('hasShadow');
  3768. });
  3769. });
  3770. describe('with functions', () => {
  3771. it('returns a boolean on all platforms', () => {
  3772. const w = new BrowserWindow({ show: false });
  3773. const hasShadow = w.hasShadow();
  3774. expect(hasShadow).to.be.a('boolean');
  3775. });
  3776. // On Windows there's no shadow by default & it can't be changed dynamically.
  3777. it('can be changed with hasShadow option', () => {
  3778. const hasShadow = process.platform !== 'darwin';
  3779. const w = new BrowserWindow({ show: false, hasShadow });
  3780. expect(w.hasShadow()).to.equal(hasShadow);
  3781. });
  3782. it('can be changed with setHasShadow method', () => {
  3783. const w = new BrowserWindow({ show: false });
  3784. w.setHasShadow(false);
  3785. expect(w.hasShadow()).to.be.false('hasShadow');
  3786. w.setHasShadow(true);
  3787. expect(w.hasShadow()).to.be.true('hasShadow');
  3788. w.setHasShadow(false);
  3789. expect(w.hasShadow()).to.be.false('hasShadow');
  3790. });
  3791. });
  3792. });
  3793. });
  3794. describe('window.getMediaSourceId()', () => {
  3795. afterEach(closeAllWindows);
  3796. it('returns valid source id', async () => {
  3797. const w = new BrowserWindow({ show: false });
  3798. const shown = emittedOnce(w, 'show');
  3799. w.show();
  3800. await shown;
  3801. // Check format 'window:1234:0'.
  3802. const sourceId = w.getMediaSourceId();
  3803. expect(sourceId).to.match(/^window:\d+:\d+$/);
  3804. });
  3805. });
  3806. ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
  3807. afterEach(closeAllWindows);
  3808. it('returns valid handle', () => {
  3809. const w = new BrowserWindow({ show: false });
  3810. // The module's source code is hosted at
  3811. // https://github.com/electron/node-is-valid-window
  3812. const isValidWindow = require('is-valid-window');
  3813. expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
  3814. });
  3815. });
  3816. ifdescribe(process.platform === 'darwin')('previewFile', () => {
  3817. afterEach(closeAllWindows);
  3818. it('opens the path in Quick Look on macOS', () => {
  3819. const w = new BrowserWindow({ show: false });
  3820. expect(() => {
  3821. w.previewFile(__filename);
  3822. w.closeFilePreview();
  3823. }).to.not.throw();
  3824. });
  3825. });
  3826. describe('contextIsolation option with and without sandbox option', () => {
  3827. const expectedContextData = {
  3828. preloadContext: {
  3829. preloadProperty: 'number',
  3830. pageProperty: 'undefined',
  3831. typeofRequire: 'function',
  3832. typeofProcess: 'object',
  3833. typeofArrayPush: 'function',
  3834. typeofFunctionApply: 'function',
  3835. typeofPreloadExecuteJavaScriptProperty: 'undefined'
  3836. },
  3837. pageContext: {
  3838. preloadProperty: 'undefined',
  3839. pageProperty: 'string',
  3840. typeofRequire: 'undefined',
  3841. typeofProcess: 'undefined',
  3842. typeofArrayPush: 'number',
  3843. typeofFunctionApply: 'boolean',
  3844. typeofPreloadExecuteJavaScriptProperty: 'number',
  3845. typeofOpenedWindow: 'object'
  3846. }
  3847. };
  3848. afterEach(closeAllWindows);
  3849. it('separates the page context from the Electron/preload context', async () => {
  3850. const iw = new BrowserWindow({
  3851. show: false,
  3852. webPreferences: {
  3853. contextIsolation: true,
  3854. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3855. }
  3856. });
  3857. const p = emittedOnce(ipcMain, 'isolated-world');
  3858. iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3859. const [, data] = await p;
  3860. expect(data).to.deep.equal(expectedContextData);
  3861. });
  3862. it('recreates the contexts on reload', async () => {
  3863. const iw = new BrowserWindow({
  3864. show: false,
  3865. webPreferences: {
  3866. contextIsolation: true,
  3867. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3868. }
  3869. });
  3870. await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3871. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  3872. iw.webContents.reload();
  3873. const [, data] = await isolatedWorld;
  3874. expect(data).to.deep.equal(expectedContextData);
  3875. });
  3876. it('enables context isolation on child windows', async () => {
  3877. const iw = new BrowserWindow({
  3878. show: false,
  3879. webPreferences: {
  3880. contextIsolation: true,
  3881. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3882. }
  3883. });
  3884. const browserWindowCreated = emittedOnce(app, 'browser-window-created');
  3885. iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  3886. const [, window] = await browserWindowCreated;
  3887. expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
  3888. });
  3889. it('separates the page context from the Electron/preload context with sandbox on', async () => {
  3890. const ws = new BrowserWindow({
  3891. show: false,
  3892. webPreferences: {
  3893. sandbox: true,
  3894. contextIsolation: true,
  3895. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3896. }
  3897. });
  3898. const p = emittedOnce(ipcMain, 'isolated-world');
  3899. ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3900. const [, data] = await p;
  3901. expect(data).to.deep.equal(expectedContextData);
  3902. });
  3903. it('recreates the contexts on reload with sandbox on', async () => {
  3904. const ws = new BrowserWindow({
  3905. show: false,
  3906. webPreferences: {
  3907. sandbox: true,
  3908. contextIsolation: true,
  3909. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3910. }
  3911. });
  3912. await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3913. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  3914. ws.webContents.reload();
  3915. const [, data] = await isolatedWorld;
  3916. expect(data).to.deep.equal(expectedContextData);
  3917. });
  3918. it('supports fetch api', async () => {
  3919. const fetchWindow = new BrowserWindow({
  3920. show: false,
  3921. webPreferences: {
  3922. contextIsolation: true,
  3923. preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
  3924. }
  3925. });
  3926. const p = emittedOnce(ipcMain, 'isolated-fetch-error');
  3927. fetchWindow.loadURL('about:blank');
  3928. const [, error] = await p;
  3929. expect(error).to.equal('Failed to fetch');
  3930. });
  3931. it('doesn\'t break ipc serialization', async () => {
  3932. const iw = new BrowserWindow({
  3933. show: false,
  3934. webPreferences: {
  3935. contextIsolation: true,
  3936. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3937. }
  3938. });
  3939. const p = emittedOnce(ipcMain, 'isolated-world');
  3940. iw.loadURL('about:blank');
  3941. iw.webContents.executeJavaScript(`
  3942. const opened = window.open()
  3943. openedLocation = opened.location.href
  3944. opened.close()
  3945. window.postMessage({openedLocation}, '*')
  3946. `);
  3947. const [, data] = await p;
  3948. expect(data.pageContext.openedLocation).to.equal('about:blank');
  3949. });
  3950. it('reports process.contextIsolated', async () => {
  3951. const iw = new BrowserWindow({
  3952. show: false,
  3953. webPreferences: {
  3954. contextIsolation: true,
  3955. preload: path.join(fixtures, 'api', 'isolated-process.js')
  3956. }
  3957. });
  3958. const p = emittedOnce(ipcMain, 'context-isolation');
  3959. iw.loadURL('about:blank');
  3960. const [, contextIsolation] = await p;
  3961. expect(contextIsolation).to.be.true('contextIsolation');
  3962. });
  3963. });
  3964. it('reloading does not cause Node.js module API hangs after reload', (done) => {
  3965. const w = new BrowserWindow({
  3966. show: false,
  3967. webPreferences: {
  3968. nodeIntegration: true,
  3969. contextIsolation: false
  3970. }
  3971. });
  3972. let count = 0;
  3973. ipcMain.on('async-node-api-done', () => {
  3974. if (count === 3) {
  3975. ipcMain.removeAllListeners('async-node-api-done');
  3976. done();
  3977. } else {
  3978. count++;
  3979. w.reload();
  3980. }
  3981. });
  3982. w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
  3983. });
  3984. describe('window.webContents.focus()', () => {
  3985. afterEach(closeAllWindows);
  3986. it('focuses window', async () => {
  3987. const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
  3988. w1.loadURL('about:blank');
  3989. const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
  3990. w2.loadURL('about:blank');
  3991. w1.webContents.focus();
  3992. // Give focus some time to switch to w1
  3993. await delay();
  3994. expect(w1.webContents.isFocused()).to.be.true('focuses window');
  3995. });
  3996. });
  3997. ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
  3998. let w: BrowserWindow;
  3999. beforeEach(function () {
  4000. w = new BrowserWindow({
  4001. width: 100,
  4002. height: 100,
  4003. show: false,
  4004. webPreferences: {
  4005. backgroundThrottling: false,
  4006. offscreen: true
  4007. }
  4008. });
  4009. });
  4010. afterEach(closeAllWindows);
  4011. it('creates offscreen window with correct size', async () => {
  4012. const paint = emittedOnce(w.webContents, 'paint');
  4013. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4014. const [,, data] = await paint;
  4015. expect(data.constructor.name).to.equal('NativeImage');
  4016. expect(data.isEmpty()).to.be.false('data is empty');
  4017. const size = data.getSize();
  4018. const { scaleFactor } = screen.getPrimaryDisplay();
  4019. expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
  4020. expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
  4021. });
  4022. it('does not crash after navigation', () => {
  4023. w.webContents.loadURL('about:blank');
  4024. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4025. });
  4026. describe('window.webContents.isOffscreen()', () => {
  4027. it('is true for offscreen type', () => {
  4028. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4029. expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
  4030. });
  4031. it('is false for regular window', () => {
  4032. const c = new BrowserWindow({ show: false });
  4033. expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
  4034. c.destroy();
  4035. });
  4036. });
  4037. describe('window.webContents.isPainting()', () => {
  4038. it('returns whether is currently painting', async () => {
  4039. const paint = emittedOnce(w.webContents, 'paint');
  4040. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4041. await paint;
  4042. expect(w.webContents.isPainting()).to.be.true('isPainting');
  4043. });
  4044. });
  4045. describe('window.webContents.stopPainting()', () => {
  4046. it('stops painting', async () => {
  4047. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4048. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4049. await domReady;
  4050. w.webContents.stopPainting();
  4051. expect(w.webContents.isPainting()).to.be.false('isPainting');
  4052. });
  4053. });
  4054. describe('window.webContents.startPainting()', () => {
  4055. it('starts painting', async () => {
  4056. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4057. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4058. await domReady;
  4059. w.webContents.stopPainting();
  4060. w.webContents.startPainting();
  4061. await emittedOnce(w.webContents, 'paint');
  4062. expect(w.webContents.isPainting()).to.be.true('isPainting');
  4063. });
  4064. });
  4065. describe('frameRate APIs', () => {
  4066. it('has default frame rate (function)', async () => {
  4067. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4068. await emittedOnce(w.webContents, 'paint');
  4069. expect(w.webContents.getFrameRate()).to.equal(60);
  4070. });
  4071. it('has default frame rate (property)', async () => {
  4072. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4073. await emittedOnce(w.webContents, 'paint');
  4074. expect(w.webContents.frameRate).to.equal(60);
  4075. });
  4076. it('sets custom frame rate (function)', async () => {
  4077. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4078. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4079. await domReady;
  4080. w.webContents.setFrameRate(30);
  4081. await emittedOnce(w.webContents, 'paint');
  4082. expect(w.webContents.getFrameRate()).to.equal(30);
  4083. });
  4084. it('sets custom frame rate (property)', async () => {
  4085. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4086. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4087. await domReady;
  4088. w.webContents.frameRate = 30;
  4089. await emittedOnce(w.webContents, 'paint');
  4090. expect(w.webContents.frameRate).to.equal(30);
  4091. });
  4092. });
  4093. });
  4094. });