api-browser-window-spec.ts 211 KB

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