api-browser-window-spec.ts 231 KB

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