api-browser-window-spec.ts 225 KB

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