api-browser-window-spec.ts 234 KB

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