api-browser-window-spec.ts 198 KB

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