api-browser-window-spec.ts 159 KB

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