api-browser-window-spec.ts 240 KB

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