api-browser-window-spec.ts 237 KB

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