api-browser-window-spec.ts 235 KB

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