api-browser-window-spec.ts 234 KB

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