api-browser-window-spec.ts 234 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731
  1. import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main';
  2. import { expect } from 'chai';
  3. import * as childProcess from 'node:child_process';
  4. import { once } from 'node:events';
  5. import * as fs from 'node:fs';
  6. import * as http from 'node:http';
  7. import { AddressInfo } from 'node:net';
  8. import * as os from 'node:os';
  9. import * as path from 'node:path';
  10. import * as qs from 'node:querystring';
  11. import { setTimeout as syncSetTimeout } from 'node:timers';
  12. import { setTimeout } from 'node:timers/promises';
  13. import { emittedUntil, emittedNTimes } from './lib/events-helpers';
  14. import { HexColors, hasCapturableScreen, ScreenCapture } from './lib/screen-helpers';
  15. import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers';
  16. import { closeWindow, closeAllWindows } from './lib/window-helpers';
  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,
  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
  1500. });
  1501. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  1502. });
  1503. it('returns correct value from setBackgroundColor()', () => {
  1504. const backgroundColor = '#AABBFF';
  1505. w.destroy();
  1506. w = new BrowserWindow({});
  1507. w.setBackgroundColor(backgroundColor);
  1508. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  1509. });
  1510. it('returns correct color with multiple passed formats', () => {
  1511. w.destroy();
  1512. w = new BrowserWindow({});
  1513. w.setBackgroundColor('#AABBFF');
  1514. expect(w.getBackgroundColor()).to.equal('#AABBFF');
  1515. w.setBackgroundColor('blueviolet');
  1516. expect(w.getBackgroundColor()).to.equal('#8A2BE2');
  1517. w.setBackgroundColor('rgb(255, 0, 185)');
  1518. expect(w.getBackgroundColor()).to.equal('#FF00B9');
  1519. w.setBackgroundColor('rgba(245, 40, 145, 0.8)');
  1520. expect(w.getBackgroundColor()).to.equal('#F52891');
  1521. w.setBackgroundColor('hsl(155, 100%, 50%)');
  1522. expect(w.getBackgroundColor()).to.equal('#00FF95');
  1523. });
  1524. });
  1525. describe('BrowserWindow.getNormalBounds()', () => {
  1526. describe('Normal state', () => {
  1527. it('checks normal bounds after resize', async () => {
  1528. const size = [300, 400];
  1529. const resize = once(w, 'resize');
  1530. w.setSize(size[0], size[1]);
  1531. await resize;
  1532. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  1533. });
  1534. it('checks normal bounds after move', async () => {
  1535. const pos = [10, 10];
  1536. const move = once(w, 'move');
  1537. w.setPosition(pos[0], pos[1]);
  1538. await move;
  1539. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  1540. });
  1541. });
  1542. ifdescribe(process.platform !== 'linux')('Maximized state', () => {
  1543. it('checks normal bounds when maximized', async () => {
  1544. const bounds = w.getBounds();
  1545. const maximize = once(w, 'maximize');
  1546. w.show();
  1547. w.maximize();
  1548. await maximize;
  1549. expectBoundsEqual(w.getNormalBounds(), bounds);
  1550. });
  1551. it('updates normal bounds after resize and maximize', async () => {
  1552. const size = [300, 400];
  1553. const resize = once(w, 'resize');
  1554. w.setSize(size[0], size[1]);
  1555. await resize;
  1556. const original = w.getBounds();
  1557. const maximize = once(w, 'maximize');
  1558. w.maximize();
  1559. await maximize;
  1560. const normal = w.getNormalBounds();
  1561. const bounds = w.getBounds();
  1562. expect(normal).to.deep.equal(original);
  1563. expect(normal).to.not.deep.equal(bounds);
  1564. const close = once(w, 'close');
  1565. w.close();
  1566. await close;
  1567. });
  1568. it('updates normal bounds after move and maximize', async () => {
  1569. const pos = [10, 10];
  1570. const move = once(w, 'move');
  1571. w.setPosition(pos[0], pos[1]);
  1572. await move;
  1573. const original = w.getBounds();
  1574. const maximize = once(w, 'maximize');
  1575. w.maximize();
  1576. await maximize;
  1577. const normal = w.getNormalBounds();
  1578. const bounds = w.getBounds();
  1579. expect(normal).to.deep.equal(original);
  1580. expect(normal).to.not.deep.equal(bounds);
  1581. const close = once(w, 'close');
  1582. w.close();
  1583. await close;
  1584. });
  1585. it('checks normal bounds when unmaximized', async () => {
  1586. const bounds = w.getBounds();
  1587. w.once('maximize', () => {
  1588. w.unmaximize();
  1589. });
  1590. const unmaximize = once(w, 'unmaximize');
  1591. w.show();
  1592. w.maximize();
  1593. await unmaximize;
  1594. expectBoundsEqual(w.getNormalBounds(), bounds);
  1595. });
  1596. it('correctly reports maximized state after maximizing then minimizing', async () => {
  1597. w.destroy();
  1598. w = new BrowserWindow({ show: false });
  1599. w.show();
  1600. const maximize = once(w, 'maximize');
  1601. w.maximize();
  1602. await maximize;
  1603. const minimize = once(w, 'minimize');
  1604. w.minimize();
  1605. await minimize;
  1606. expect(w.isMaximized()).to.equal(false);
  1607. expect(w.isMinimized()).to.equal(true);
  1608. });
  1609. it('correctly reports maximized state after maximizing then fullscreening', async () => {
  1610. w.destroy();
  1611. w = new BrowserWindow({ show: false });
  1612. w.show();
  1613. const maximize = once(w, 'maximize');
  1614. w.maximize();
  1615. await maximize;
  1616. const enterFS = once(w, 'enter-full-screen');
  1617. w.setFullScreen(true);
  1618. await enterFS;
  1619. expect(w.isMaximized()).to.equal(false);
  1620. expect(w.isFullScreen()).to.equal(true);
  1621. });
  1622. it('does not crash if maximized, minimized, then restored to maximized state', (done) => {
  1623. w.destroy();
  1624. w = new BrowserWindow({ show: false });
  1625. w.show();
  1626. let count = 0;
  1627. w.on('maximize', () => {
  1628. if (count === 0) syncSetTimeout(() => { w.minimize(); });
  1629. count++;
  1630. });
  1631. w.on('minimize', () => {
  1632. if (count === 1) syncSetTimeout(() => { w.restore(); });
  1633. count++;
  1634. });
  1635. w.on('restore', () => {
  1636. try {
  1637. throw new Error('hey!');
  1638. } catch (e: any) {
  1639. expect(e.message).to.equal('hey!');
  1640. done();
  1641. }
  1642. });
  1643. w.maximize();
  1644. });
  1645. it('checks normal bounds for maximized transparent window', async () => {
  1646. w.destroy();
  1647. w = new BrowserWindow({
  1648. transparent: true,
  1649. show: false
  1650. });
  1651. w.show();
  1652. const bounds = w.getNormalBounds();
  1653. const maximize = once(w, 'maximize');
  1654. w.maximize();
  1655. await maximize;
  1656. expectBoundsEqual(w.getNormalBounds(), bounds);
  1657. });
  1658. it('does not change size for a frameless window with min size', async () => {
  1659. w.destroy();
  1660. w = new BrowserWindow({
  1661. show: false,
  1662. frame: false,
  1663. width: 300,
  1664. height: 300,
  1665. minWidth: 300,
  1666. minHeight: 300
  1667. });
  1668. const bounds = w.getBounds();
  1669. w.once('maximize', () => {
  1670. w.unmaximize();
  1671. });
  1672. const unmaximize = once(w, 'unmaximize');
  1673. w.show();
  1674. w.maximize();
  1675. await unmaximize;
  1676. expectBoundsEqual(w.getNormalBounds(), bounds);
  1677. });
  1678. it('correctly checks transparent window maximization state', async () => {
  1679. w.destroy();
  1680. w = new BrowserWindow({
  1681. show: false,
  1682. width: 300,
  1683. height: 300,
  1684. transparent: true
  1685. });
  1686. const maximize = once(w, 'maximize');
  1687. w.show();
  1688. w.maximize();
  1689. await maximize;
  1690. expect(w.isMaximized()).to.equal(true);
  1691. const unmaximize = once(w, 'unmaximize');
  1692. w.unmaximize();
  1693. await unmaximize;
  1694. expect(w.isMaximized()).to.equal(false);
  1695. });
  1696. it('returns the correct value for windows with an aspect ratio', async () => {
  1697. w.destroy();
  1698. w = new BrowserWindow({
  1699. show: false,
  1700. fullscreenable: false
  1701. });
  1702. w.setAspectRatio(16 / 11);
  1703. const maximize = once(w, 'maximize');
  1704. w.show();
  1705. w.maximize();
  1706. await maximize;
  1707. expect(w.isMaximized()).to.equal(true);
  1708. w.resizable = false;
  1709. expect(w.isMaximized()).to.equal(true);
  1710. });
  1711. });
  1712. ifdescribe(process.platform !== 'linux')('Minimized state', () => {
  1713. it('checks normal bounds when minimized', async () => {
  1714. const bounds = w.getBounds();
  1715. const minimize = once(w, 'minimize');
  1716. w.show();
  1717. w.minimize();
  1718. await minimize;
  1719. expectBoundsEqual(w.getNormalBounds(), bounds);
  1720. });
  1721. it('updates normal bounds after move and minimize', async () => {
  1722. const pos = [10, 10];
  1723. const move = once(w, 'move');
  1724. w.setPosition(pos[0], pos[1]);
  1725. await move;
  1726. const original = w.getBounds();
  1727. const minimize = once(w, 'minimize');
  1728. w.minimize();
  1729. await minimize;
  1730. const normal = w.getNormalBounds();
  1731. expect(original).to.deep.equal(normal);
  1732. expectBoundsEqual(normal, w.getBounds());
  1733. });
  1734. it('updates normal bounds after resize and minimize', async () => {
  1735. const size = [300, 400];
  1736. const resize = once(w, 'resize');
  1737. w.setSize(size[0], size[1]);
  1738. await resize;
  1739. const original = w.getBounds();
  1740. const minimize = once(w, 'minimize');
  1741. w.minimize();
  1742. await minimize;
  1743. const normal = w.getNormalBounds();
  1744. expect(original).to.deep.equal(normal);
  1745. expectBoundsEqual(normal, w.getBounds());
  1746. });
  1747. it('checks normal bounds when restored', async () => {
  1748. const bounds = w.getBounds();
  1749. w.once('minimize', () => {
  1750. w.restore();
  1751. });
  1752. const restore = once(w, 'restore');
  1753. w.show();
  1754. w.minimize();
  1755. await restore;
  1756. expectBoundsEqual(w.getNormalBounds(), bounds);
  1757. });
  1758. it('does not change size for a frameless window with min size', async () => {
  1759. w.destroy();
  1760. w = new BrowserWindow({
  1761. show: false,
  1762. frame: false,
  1763. width: 300,
  1764. height: 300,
  1765. minWidth: 300,
  1766. minHeight: 300
  1767. });
  1768. const bounds = w.getBounds();
  1769. w.once('minimize', () => {
  1770. w.restore();
  1771. });
  1772. const restore = once(w, 'restore');
  1773. w.show();
  1774. w.minimize();
  1775. await restore;
  1776. expectBoundsEqual(w.getNormalBounds(), bounds);
  1777. });
  1778. });
  1779. ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
  1780. it('with properties', () => {
  1781. it('can be set with the fullscreen constructor option', () => {
  1782. w = new BrowserWindow({ fullscreen: true });
  1783. expect(w.fullScreen).to.be.true();
  1784. });
  1785. it('does not go fullscreen if roundedCorners are enabled', async () => {
  1786. w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true });
  1787. expect(w.fullScreen).to.be.false();
  1788. });
  1789. it('can be changed', () => {
  1790. w.fullScreen = false;
  1791. expect(w.fullScreen).to.be.false();
  1792. w.fullScreen = true;
  1793. expect(w.fullScreen).to.be.true();
  1794. });
  1795. it('checks normal bounds when fullscreen\'ed', async () => {
  1796. const bounds = w.getBounds();
  1797. const enterFullScreen = once(w, 'enter-full-screen');
  1798. w.show();
  1799. w.fullScreen = true;
  1800. await enterFullScreen;
  1801. expectBoundsEqual(w.getNormalBounds(), bounds);
  1802. });
  1803. it('updates normal bounds after resize and fullscreen', async () => {
  1804. const size = [300, 400];
  1805. const resize = once(w, 'resize');
  1806. w.setSize(size[0], size[1]);
  1807. await resize;
  1808. const original = w.getBounds();
  1809. const fsc = once(w, 'enter-full-screen');
  1810. w.fullScreen = true;
  1811. await fsc;
  1812. const normal = w.getNormalBounds();
  1813. const bounds = w.getBounds();
  1814. expect(normal).to.deep.equal(original);
  1815. expect(normal).to.not.deep.equal(bounds);
  1816. const close = once(w, 'close');
  1817. w.close();
  1818. await close;
  1819. });
  1820. it('updates normal bounds after move and fullscreen', async () => {
  1821. const pos = [10, 10];
  1822. const move = once(w, 'move');
  1823. w.setPosition(pos[0], pos[1]);
  1824. await move;
  1825. const original = w.getBounds();
  1826. const fsc = once(w, 'enter-full-screen');
  1827. w.fullScreen = true;
  1828. await fsc;
  1829. const normal = w.getNormalBounds();
  1830. const bounds = w.getBounds();
  1831. expect(normal).to.deep.equal(original);
  1832. expect(normal).to.not.deep.equal(bounds);
  1833. const close = once(w, 'close');
  1834. w.close();
  1835. await close;
  1836. });
  1837. it('checks normal bounds when unfullscreen\'ed', async () => {
  1838. const bounds = w.getBounds();
  1839. w.once('enter-full-screen', () => {
  1840. w.fullScreen = false;
  1841. });
  1842. const leaveFullScreen = once(w, 'leave-full-screen');
  1843. w.show();
  1844. w.fullScreen = true;
  1845. await leaveFullScreen;
  1846. expectBoundsEqual(w.getNormalBounds(), bounds);
  1847. });
  1848. });
  1849. it('with functions', () => {
  1850. it('can be set with the fullscreen constructor option', () => {
  1851. w = new BrowserWindow({ fullscreen: true });
  1852. expect(w.isFullScreen()).to.be.true();
  1853. });
  1854. it('can be changed', () => {
  1855. w.setFullScreen(false);
  1856. expect(w.isFullScreen()).to.be.false();
  1857. w.setFullScreen(true);
  1858. expect(w.isFullScreen()).to.be.true();
  1859. });
  1860. it('checks normal bounds when fullscreen\'ed', async () => {
  1861. const bounds = w.getBounds();
  1862. w.show();
  1863. const enterFullScreen = once(w, 'enter-full-screen');
  1864. w.setFullScreen(true);
  1865. await enterFullScreen;
  1866. expectBoundsEqual(w.getNormalBounds(), bounds);
  1867. });
  1868. it('updates normal bounds after resize and fullscreen', async () => {
  1869. const size = [300, 400];
  1870. const resize = once(w, 'resize');
  1871. w.setSize(size[0], size[1]);
  1872. await resize;
  1873. const original = w.getBounds();
  1874. const fsc = once(w, 'enter-full-screen');
  1875. w.setFullScreen(true);
  1876. await fsc;
  1877. const normal = w.getNormalBounds();
  1878. const bounds = w.getBounds();
  1879. expect(normal).to.deep.equal(original);
  1880. expect(normal).to.not.deep.equal(bounds);
  1881. const close = once(w, 'close');
  1882. w.close();
  1883. await close;
  1884. });
  1885. it('updates normal bounds after move and fullscreen', async () => {
  1886. const pos = [10, 10];
  1887. const move = once(w, 'move');
  1888. w.setPosition(pos[0], pos[1]);
  1889. await move;
  1890. const original = w.getBounds();
  1891. const fsc = once(w, 'enter-full-screen');
  1892. w.setFullScreen(true);
  1893. await fsc;
  1894. const normal = w.getNormalBounds();
  1895. const bounds = w.getBounds();
  1896. expect(normal).to.deep.equal(original);
  1897. expect(normal).to.not.deep.equal(bounds);
  1898. const close = once(w, 'close');
  1899. w.close();
  1900. await close;
  1901. });
  1902. it('checks normal bounds when unfullscreen\'ed', async () => {
  1903. const bounds = w.getBounds();
  1904. w.show();
  1905. const enterFullScreen = once(w, 'enter-full-screen');
  1906. w.setFullScreen(true);
  1907. await enterFullScreen;
  1908. const leaveFullScreen = once(w, 'leave-full-screen');
  1909. w.setFullScreen(false);
  1910. await leaveFullScreen;
  1911. expectBoundsEqual(w.getNormalBounds(), bounds);
  1912. });
  1913. });
  1914. });
  1915. });
  1916. });
  1917. ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
  1918. let w: BrowserWindow;
  1919. beforeEach(() => {
  1920. w = new BrowserWindow({ show: false });
  1921. });
  1922. afterEach(closeAllWindows);
  1923. describe('BrowserWindow.selectPreviousTab()', () => {
  1924. it('does not throw', () => {
  1925. expect(() => {
  1926. w.selectPreviousTab();
  1927. }).to.not.throw();
  1928. });
  1929. });
  1930. describe('BrowserWindow.selectNextTab()', () => {
  1931. it('does not throw', () => {
  1932. expect(() => {
  1933. w.selectNextTab();
  1934. }).to.not.throw();
  1935. });
  1936. });
  1937. describe('BrowserWindow.showAllTabs()', () => {
  1938. it('does not throw', () => {
  1939. expect(() => {
  1940. w.showAllTabs();
  1941. }).to.not.throw();
  1942. });
  1943. });
  1944. describe('BrowserWindow.mergeAllWindows()', () => {
  1945. it('does not throw', () => {
  1946. expect(() => {
  1947. w.mergeAllWindows();
  1948. }).to.not.throw();
  1949. });
  1950. });
  1951. describe('BrowserWindow.moveTabToNewWindow()', () => {
  1952. it('does not throw', () => {
  1953. expect(() => {
  1954. w.moveTabToNewWindow();
  1955. }).to.not.throw();
  1956. });
  1957. });
  1958. describe('BrowserWindow.toggleTabBar()', () => {
  1959. it('does not throw', () => {
  1960. expect(() => {
  1961. w.toggleTabBar();
  1962. }).to.not.throw();
  1963. });
  1964. });
  1965. describe('BrowserWindow.addTabbedWindow()', () => {
  1966. it('does not throw', async () => {
  1967. const tabbedWindow = new BrowserWindow({});
  1968. expect(() => {
  1969. w.addTabbedWindow(tabbedWindow);
  1970. }).to.not.throw();
  1971. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
  1972. await closeWindow(tabbedWindow, { assertNotWindows: false });
  1973. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
  1974. });
  1975. it('throws when called on itself', () => {
  1976. expect(() => {
  1977. w.addTabbedWindow(w);
  1978. }).to.throw('AddTabbedWindow cannot be called by a window on itself.');
  1979. });
  1980. });
  1981. describe('BrowserWindow.tabbingIdentifier', () => {
  1982. it('is undefined if no tabbingIdentifier was set', () => {
  1983. const w = new BrowserWindow({ show: false });
  1984. expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier');
  1985. });
  1986. it('returns the window tabbingIdentifier', () => {
  1987. const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' });
  1988. expect(w.tabbingIdentifier).to.equal('group1');
  1989. });
  1990. });
  1991. });
  1992. describe('autoHideMenuBar state', () => {
  1993. afterEach(closeAllWindows);
  1994. it('for properties', () => {
  1995. it('can be set with autoHideMenuBar constructor option', () => {
  1996. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1997. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1998. });
  1999. it('can be changed', () => {
  2000. const w = new BrowserWindow({ show: false });
  2001. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  2002. w.autoHideMenuBar = true;
  2003. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  2004. w.autoHideMenuBar = false;
  2005. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  2006. });
  2007. });
  2008. it('for functions', () => {
  2009. it('can be set with autoHideMenuBar constructor option', () => {
  2010. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  2011. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  2012. });
  2013. it('can be changed', () => {
  2014. const w = new BrowserWindow({ show: false });
  2015. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  2016. w.setAutoHideMenuBar(true);
  2017. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  2018. w.setAutoHideMenuBar(false);
  2019. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  2020. });
  2021. });
  2022. });
  2023. describe('BrowserWindow.capturePage(rect)', () => {
  2024. afterEach(closeAllWindows);
  2025. it('returns a Promise with a Buffer', async () => {
  2026. const w = new BrowserWindow({ show: false });
  2027. const image = await w.capturePage({
  2028. x: 0,
  2029. y: 0,
  2030. width: 100,
  2031. height: 100
  2032. });
  2033. expect(image.isEmpty()).to.equal(true);
  2034. });
  2035. ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => {
  2036. const w = new BrowserWindow({
  2037. webPreferences: {
  2038. nodeIntegration: true,
  2039. contextIsolation: false
  2040. }
  2041. });
  2042. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2043. {
  2044. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  2045. expect(visibilityState).to.equal('visible');
  2046. expect(hidden).to.be.false('hidden');
  2047. }
  2048. w.hide();
  2049. {
  2050. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  2051. expect(visibilityState).to.equal('hidden');
  2052. expect(hidden).to.be.true('hidden');
  2053. }
  2054. await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true });
  2055. const visible = await w.webContents.executeJavaScript('document.visibilityState');
  2056. expect(visible).to.equal('hidden');
  2057. });
  2058. it('resolves when the window is occluded', async () => {
  2059. const w1 = new BrowserWindow({ show: false });
  2060. w1.loadFile(path.join(fixtures, 'pages', 'a.html'));
  2061. await once(w1, 'ready-to-show');
  2062. w1.show();
  2063. const w2 = new BrowserWindow({ show: false });
  2064. w2.loadFile(path.join(fixtures, 'pages', 'a.html'));
  2065. await once(w2, 'ready-to-show');
  2066. w2.show();
  2067. const visibleImage = await w1.capturePage();
  2068. expect(visibleImage.isEmpty()).to.equal(false);
  2069. });
  2070. it('resolves when the window is not visible', async () => {
  2071. const w = new BrowserWindow({ show: false });
  2072. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  2073. await once(w, 'ready-to-show');
  2074. w.show();
  2075. const visibleImage = await w.capturePage();
  2076. expect(visibleImage.isEmpty()).to.equal(false);
  2077. w.minimize();
  2078. const hiddenImage = await w.capturePage();
  2079. expect(hiddenImage.isEmpty()).to.equal(false);
  2080. });
  2081. it('preserves transparency', async () => {
  2082. const w = new BrowserWindow({ show: false, transparent: true });
  2083. w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
  2084. await once(w, 'ready-to-show');
  2085. w.show();
  2086. const image = await w.capturePage();
  2087. const imgBuffer = image.toPNG();
  2088. // Check the 25th byte in the PNG.
  2089. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  2090. expect(imgBuffer[25]).to.equal(6);
  2091. });
  2092. });
  2093. describe('BrowserWindow.setProgressBar(progress)', () => {
  2094. let w: BrowserWindow;
  2095. before(() => {
  2096. w = new BrowserWindow({ show: false });
  2097. });
  2098. after(async () => {
  2099. await closeWindow(w);
  2100. w = null as unknown as BrowserWindow;
  2101. });
  2102. it('sets the progress', () => {
  2103. expect(() => {
  2104. if (process.platform === 'darwin') {
  2105. app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
  2106. }
  2107. w.setProgressBar(0.5);
  2108. if (process.platform === 'darwin') {
  2109. app.dock.setIcon(null as any);
  2110. }
  2111. w.setProgressBar(-1);
  2112. }).to.not.throw();
  2113. });
  2114. it('sets the progress using "paused" mode', () => {
  2115. expect(() => {
  2116. w.setProgressBar(0.5, { mode: 'paused' });
  2117. }).to.not.throw();
  2118. });
  2119. it('sets the progress using "error" mode', () => {
  2120. expect(() => {
  2121. w.setProgressBar(0.5, { mode: 'error' });
  2122. }).to.not.throw();
  2123. });
  2124. it('sets the progress using "normal" mode', () => {
  2125. expect(() => {
  2126. w.setProgressBar(0.5, { mode: 'normal' });
  2127. }).to.not.throw();
  2128. });
  2129. });
  2130. describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
  2131. let w: BrowserWindow;
  2132. afterEach(closeAllWindows);
  2133. beforeEach(() => {
  2134. w = new BrowserWindow({ show: true });
  2135. });
  2136. it('sets the window as always on top', () => {
  2137. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  2138. w.setAlwaysOnTop(true, 'screen-saver');
  2139. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  2140. w.setAlwaysOnTop(false);
  2141. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  2142. w.setAlwaysOnTop(true);
  2143. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  2144. });
  2145. ifit(process.platform === 'darwin')('resets the windows level on minimize', async () => {
  2146. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  2147. w.setAlwaysOnTop(true, 'screen-saver');
  2148. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  2149. const minimized = once(w, 'minimize');
  2150. w.minimize();
  2151. await minimized;
  2152. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  2153. const restored = once(w, 'restore');
  2154. w.restore();
  2155. await restored;
  2156. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  2157. });
  2158. it('causes the right value to be emitted on `always-on-top-changed`', async () => {
  2159. const alwaysOnTopChanged = once(w, 'always-on-top-changed') as Promise<[any, boolean]>;
  2160. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  2161. w.setAlwaysOnTop(true);
  2162. const [, alwaysOnTop] = await alwaysOnTopChanged;
  2163. expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
  2164. });
  2165. ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
  2166. w = new BrowserWindow({ show: false });
  2167. const c = new BrowserWindow({ parent: w });
  2168. c.setAlwaysOnTop(true, 'screen-saver');
  2169. expect(w.isAlwaysOnTop()).to.be.false();
  2170. expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
  2171. expect(c._getAlwaysOnTopLevel()).to.equal('screen-saver');
  2172. });
  2173. });
  2174. describe('preconnect feature', () => {
  2175. let w: BrowserWindow;
  2176. let server: http.Server;
  2177. let url: string;
  2178. let connections = 0;
  2179. beforeEach(async () => {
  2180. connections = 0;
  2181. server = http.createServer((req, res) => {
  2182. if (req.url === '/link') {
  2183. res.setHeader('Content-type', 'text/html');
  2184. res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
  2185. return;
  2186. }
  2187. res.end();
  2188. });
  2189. server.on('connection', () => { connections++; });
  2190. url = (await listen(server)).url;
  2191. });
  2192. afterEach(async () => {
  2193. server.close();
  2194. await closeWindow(w);
  2195. w = null as unknown as BrowserWindow;
  2196. server = null as unknown as http.Server;
  2197. });
  2198. it('calling preconnect() connects to the server', async () => {
  2199. w = new BrowserWindow({ show: false });
  2200. w.webContents.on('did-start-navigation', (event, url) => {
  2201. w.webContents.session.preconnect({ url, numSockets: 4 });
  2202. });
  2203. await w.loadURL(url);
  2204. expect(connections).to.equal(4);
  2205. });
  2206. it('does not preconnect unless requested', async () => {
  2207. w = new BrowserWindow({ show: false });
  2208. await w.loadURL(url);
  2209. expect(connections).to.equal(1);
  2210. });
  2211. it('parses <link rel=preconnect>', async () => {
  2212. w = new BrowserWindow({ show: true });
  2213. const p = once(w.webContents.session, 'preconnect');
  2214. w.loadURL(url + '/link');
  2215. const [, preconnectUrl, allowCredentials] = await p;
  2216. expect(preconnectUrl).to.equal('http://example.com/');
  2217. expect(allowCredentials).to.be.true('allowCredentials');
  2218. });
  2219. });
  2220. describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
  2221. let w: BrowserWindow;
  2222. beforeEach(() => {
  2223. w = new BrowserWindow({ show: false });
  2224. });
  2225. afterEach(async () => {
  2226. await closeWindow(w);
  2227. w = null as unknown as BrowserWindow;
  2228. });
  2229. ifit(process.platform === 'darwin')('on macOS', () => {
  2230. it('allows changing cursor auto-hiding', () => {
  2231. expect(() => {
  2232. w.setAutoHideCursor(false);
  2233. w.setAutoHideCursor(true);
  2234. }).to.not.throw();
  2235. });
  2236. });
  2237. ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
  2238. it('is not available', () => {
  2239. expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
  2240. });
  2241. });
  2242. });
  2243. ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
  2244. afterEach(closeAllWindows);
  2245. it('does not throw', () => {
  2246. const w = new BrowserWindow({ show: false });
  2247. expect(() => {
  2248. w.setWindowButtonVisibility(true);
  2249. w.setWindowButtonVisibility(false);
  2250. }).to.not.throw();
  2251. });
  2252. it('changes window button visibility for normal window', () => {
  2253. const w = new BrowserWindow({ show: false });
  2254. expect(w._getWindowButtonVisibility()).to.equal(true);
  2255. w.setWindowButtonVisibility(false);
  2256. expect(w._getWindowButtonVisibility()).to.equal(false);
  2257. w.setWindowButtonVisibility(true);
  2258. expect(w._getWindowButtonVisibility()).to.equal(true);
  2259. });
  2260. it('changes window button visibility for frameless window', () => {
  2261. const w = new BrowserWindow({ show: false, frame: false });
  2262. expect(w._getWindowButtonVisibility()).to.equal(false);
  2263. w.setWindowButtonVisibility(true);
  2264. expect(w._getWindowButtonVisibility()).to.equal(true);
  2265. w.setWindowButtonVisibility(false);
  2266. expect(w._getWindowButtonVisibility()).to.equal(false);
  2267. });
  2268. it('changes window button visibility for hiddenInset window', () => {
  2269. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  2270. expect(w._getWindowButtonVisibility()).to.equal(true);
  2271. w.setWindowButtonVisibility(false);
  2272. expect(w._getWindowButtonVisibility()).to.equal(false);
  2273. w.setWindowButtonVisibility(true);
  2274. expect(w._getWindowButtonVisibility()).to.equal(true);
  2275. });
  2276. // Buttons of customButtonsOnHover are always hidden unless hovered.
  2277. it('does not change window button visibility for customButtonsOnHover window', () => {
  2278. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
  2279. expect(w._getWindowButtonVisibility()).to.equal(false);
  2280. w.setWindowButtonVisibility(true);
  2281. expect(w._getWindowButtonVisibility()).to.equal(false);
  2282. w.setWindowButtonVisibility(false);
  2283. expect(w._getWindowButtonVisibility()).to.equal(false);
  2284. });
  2285. it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
  2286. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
  2287. expect(w._getWindowButtonVisibility()).to.equal(true);
  2288. w.setWindowButtonVisibility(false);
  2289. expect(w._getWindowButtonVisibility()).to.equal(false);
  2290. const enterFS = once(w, 'enter-full-screen');
  2291. w.setFullScreen(true);
  2292. await enterFS;
  2293. const leaveFS = once(w, 'leave-full-screen');
  2294. w.setFullScreen(false);
  2295. await leaveFS;
  2296. w.setWindowButtonVisibility(true);
  2297. expect(w._getWindowButtonVisibility()).to.equal(true);
  2298. });
  2299. it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
  2300. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  2301. expect(w._getWindowButtonVisibility()).to.equal(true);
  2302. w.setWindowButtonVisibility(false);
  2303. expect(w._getWindowButtonVisibility()).to.equal(false);
  2304. const enterFS = once(w, 'enter-full-screen');
  2305. w.setFullScreen(true);
  2306. await enterFS;
  2307. const leaveFS = once(w, 'leave-full-screen');
  2308. w.setFullScreen(false);
  2309. await leaveFS;
  2310. w.setWindowButtonVisibility(true);
  2311. expect(w._getWindowButtonVisibility()).to.equal(true);
  2312. });
  2313. });
  2314. ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
  2315. afterEach(closeAllWindows);
  2316. it('allows setting, changing, and removing the vibrancy', () => {
  2317. const w = new BrowserWindow({ show: false });
  2318. expect(() => {
  2319. w.setVibrancy('titlebar');
  2320. w.setVibrancy('selection');
  2321. w.setVibrancy(null);
  2322. w.setVibrancy('menu');
  2323. w.setVibrancy('' as any);
  2324. }).to.not.throw();
  2325. });
  2326. it('does not crash if vibrancy is set to an invalid value', () => {
  2327. const w = new BrowserWindow({ show: false });
  2328. expect(() => {
  2329. w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
  2330. }).to.not.throw();
  2331. });
  2332. });
  2333. ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
  2334. const pos = { x: 10, y: 10 };
  2335. afterEach(closeAllWindows);
  2336. describe('BrowserWindow.getWindowButtonPosition(pos)', () => {
  2337. it('returns null when there is no custom position', () => {
  2338. const w = new BrowserWindow({ show: false });
  2339. expect(w.getWindowButtonPosition()).to.be.null('getWindowButtonPosition');
  2340. });
  2341. it('gets position property for "hidden" titleBarStyle', () => {
  2342. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  2343. expect(w.getWindowButtonPosition()).to.deep.equal(pos);
  2344. });
  2345. it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
  2346. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  2347. expect(w.getWindowButtonPosition()).to.deep.equal(pos);
  2348. });
  2349. });
  2350. describe('BrowserWindow.setWindowButtonPosition(pos)', () => {
  2351. it('resets the position when null is passed', () => {
  2352. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  2353. w.setWindowButtonPosition(null);
  2354. expect(w.getWindowButtonPosition()).to.be.null('setWindowButtonPosition');
  2355. });
  2356. it('sets position property for "hidden" titleBarStyle', () => {
  2357. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  2358. const newPos = { x: 20, y: 20 };
  2359. w.setWindowButtonPosition(newPos);
  2360. expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
  2361. });
  2362. it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
  2363. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  2364. const newPos = { x: 20, y: 20 };
  2365. w.setWindowButtonPosition(newPos);
  2366. expect(w.getWindowButtonPosition()).to.deep.equal(newPos);
  2367. });
  2368. });
  2369. });
  2370. ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
  2371. afterEach(closeAllWindows);
  2372. it('supports setting the app details', () => {
  2373. const w = new BrowserWindow({ show: false });
  2374. const iconPath = path.join(fixtures, 'assets', 'icon.ico');
  2375. expect(() => {
  2376. w.setAppDetails({ appId: 'my.app.id' });
  2377. w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
  2378. w.setAppDetails({ appIconPath: iconPath });
  2379. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
  2380. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
  2381. w.setAppDetails({ relaunchDisplayName: 'My app name' });
  2382. w.setAppDetails({
  2383. appId: 'my.app.id',
  2384. appIconPath: iconPath,
  2385. appIconIndex: 0,
  2386. relaunchCommand: 'my-app.exe arg1 arg2',
  2387. relaunchDisplayName: 'My app name'
  2388. });
  2389. w.setAppDetails({});
  2390. }).to.not.throw();
  2391. expect(() => {
  2392. (w.setAppDetails as any)();
  2393. }).to.throw('Insufficient number of arguments.');
  2394. });
  2395. });
  2396. describe('BrowserWindow.fromId(id)', () => {
  2397. afterEach(closeAllWindows);
  2398. it('returns the window with id', () => {
  2399. const w = new BrowserWindow({ show: false });
  2400. expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
  2401. });
  2402. });
  2403. describe('Opening a BrowserWindow from a link', () => {
  2404. let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
  2405. afterEach(() => {
  2406. if (appProcess && !appProcess.killed) {
  2407. appProcess.kill();
  2408. appProcess = undefined;
  2409. }
  2410. });
  2411. it('can properly open and load a new window from a link', async () => {
  2412. const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
  2413. appProcess = childProcess.spawn(process.execPath, [appPath]);
  2414. const [code] = await once(appProcess, 'exit');
  2415. expect(code).to.equal(0);
  2416. });
  2417. });
  2418. describe('BrowserWindow.fromWebContents(webContents)', () => {
  2419. afterEach(closeAllWindows);
  2420. it('returns the window with the webContents', () => {
  2421. const w = new BrowserWindow({ show: false });
  2422. const found = BrowserWindow.fromWebContents(w.webContents);
  2423. expect(found!.id).to.equal(w.id);
  2424. });
  2425. it('returns null for webContents without a BrowserWindow', () => {
  2426. const contents = (webContents as typeof ElectronInternal.WebContents).create();
  2427. try {
  2428. expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
  2429. } finally {
  2430. contents.destroy();
  2431. }
  2432. });
  2433. it('returns the correct window for a BrowserView webcontents', async () => {
  2434. const w = new BrowserWindow({ show: false });
  2435. const bv = new BrowserView();
  2436. w.setBrowserView(bv);
  2437. defer(() => {
  2438. w.removeBrowserView(bv);
  2439. bv.webContents.destroy();
  2440. });
  2441. await bv.webContents.loadURL('about:blank');
  2442. expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
  2443. });
  2444. it('returns the correct window for a WebView webcontents', async () => {
  2445. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  2446. w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
  2447. // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
  2448. // https://github.com/electron/electron/issues/25413, and is not integral
  2449. // to the test.
  2450. const p = once(w.webContents, 'did-attach-webview');
  2451. const [, webviewContents] = await once(app, 'web-contents-created') as [any, WebContents];
  2452. expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
  2453. await p;
  2454. });
  2455. it('is usable immediately on browser-window-created', async () => {
  2456. const w = new BrowserWindow({ show: false });
  2457. w.loadURL('about:blank');
  2458. w.webContents.executeJavaScript('window.open(""); null');
  2459. const [win, winFromWebContents] = await new Promise<any>((resolve) => {
  2460. app.once('browser-window-created', (e, win) => {
  2461. resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
  2462. });
  2463. });
  2464. expect(winFromWebContents).to.equal(win);
  2465. });
  2466. });
  2467. describe('BrowserWindow.openDevTools()', () => {
  2468. afterEach(closeAllWindows);
  2469. it('does not crash for frameless window', () => {
  2470. const w = new BrowserWindow({ show: false, frame: false });
  2471. w.webContents.openDevTools();
  2472. });
  2473. });
  2474. describe('BrowserWindow.fromBrowserView(browserView)', () => {
  2475. afterEach(closeAllWindows);
  2476. it('returns the window with the BrowserView', () => {
  2477. const w = new BrowserWindow({ show: false });
  2478. const bv = new BrowserView();
  2479. w.setBrowserView(bv);
  2480. defer(() => {
  2481. w.removeBrowserView(bv);
  2482. bv.webContents.destroy();
  2483. });
  2484. expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
  2485. });
  2486. it('returns the window when there are multiple BrowserViews', () => {
  2487. const w = new BrowserWindow({ show: false });
  2488. const bv1 = new BrowserView();
  2489. w.addBrowserView(bv1);
  2490. const bv2 = new BrowserView();
  2491. w.addBrowserView(bv2);
  2492. defer(() => {
  2493. w.removeBrowserView(bv1);
  2494. w.removeBrowserView(bv2);
  2495. bv1.webContents.destroy();
  2496. bv2.webContents.destroy();
  2497. });
  2498. expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
  2499. expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
  2500. });
  2501. it('returns undefined if not attached', () => {
  2502. const bv = new BrowserView();
  2503. defer(() => {
  2504. bv.webContents.destroy();
  2505. });
  2506. expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
  2507. });
  2508. });
  2509. describe('BrowserWindow.setOpacity(opacity)', () => {
  2510. afterEach(closeAllWindows);
  2511. ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
  2512. it('make window with initial opacity', () => {
  2513. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  2514. expect(w.getOpacity()).to.equal(0.5);
  2515. });
  2516. it('allows setting the opacity', () => {
  2517. const w = new BrowserWindow({ show: false });
  2518. expect(() => {
  2519. w.setOpacity(0.0);
  2520. expect(w.getOpacity()).to.equal(0.0);
  2521. w.setOpacity(0.5);
  2522. expect(w.getOpacity()).to.equal(0.5);
  2523. w.setOpacity(1.0);
  2524. expect(w.getOpacity()).to.equal(1.0);
  2525. }).to.not.throw();
  2526. });
  2527. it('clamps opacity to [0.0...1.0]', () => {
  2528. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  2529. w.setOpacity(100);
  2530. expect(w.getOpacity()).to.equal(1.0);
  2531. w.setOpacity(-100);
  2532. expect(w.getOpacity()).to.equal(0.0);
  2533. });
  2534. });
  2535. ifdescribe(process.platform === 'linux')(('Linux'), () => {
  2536. it('sets 1 regardless of parameter', () => {
  2537. const w = new BrowserWindow({ show: false });
  2538. w.setOpacity(0);
  2539. expect(w.getOpacity()).to.equal(1.0);
  2540. w.setOpacity(0.5);
  2541. expect(w.getOpacity()).to.equal(1.0);
  2542. });
  2543. });
  2544. });
  2545. describe('BrowserWindow.setShape(rects)', () => {
  2546. afterEach(closeAllWindows);
  2547. it('allows setting shape', () => {
  2548. const w = new BrowserWindow({ show: false });
  2549. expect(() => {
  2550. w.setShape([]);
  2551. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
  2552. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
  2553. w.setShape([]);
  2554. }).to.not.throw();
  2555. });
  2556. });
  2557. describe('"useContentSize" option', () => {
  2558. afterEach(closeAllWindows);
  2559. it('make window created with content size when used', () => {
  2560. const w = new BrowserWindow({
  2561. show: false,
  2562. width: 400,
  2563. height: 400,
  2564. useContentSize: true
  2565. });
  2566. const contentSize = w.getContentSize();
  2567. expect(contentSize).to.deep.equal([400, 400]);
  2568. });
  2569. it('make window created with window size when not used', () => {
  2570. const w = new BrowserWindow({
  2571. show: false,
  2572. width: 400,
  2573. height: 400
  2574. });
  2575. const size = w.getSize();
  2576. expect(size).to.deep.equal([400, 400]);
  2577. });
  2578. it('works for a frameless window', () => {
  2579. const w = new BrowserWindow({
  2580. show: false,
  2581. frame: false,
  2582. width: 400,
  2583. height: 400,
  2584. useContentSize: true
  2585. });
  2586. const contentSize = w.getContentSize();
  2587. expect(contentSize).to.deep.equal([400, 400]);
  2588. const size = w.getSize();
  2589. expect(size).to.deep.equal([400, 400]);
  2590. });
  2591. });
  2592. describe('"titleBarStyle" option', () => {
  2593. const testWindowsOverlay = async (style: any) => {
  2594. const w = new BrowserWindow({
  2595. show: false,
  2596. width: 400,
  2597. height: 400,
  2598. titleBarStyle: style,
  2599. webPreferences: {
  2600. nodeIntegration: true,
  2601. contextIsolation: false
  2602. },
  2603. titleBarOverlay: true
  2604. });
  2605. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2606. if (process.platform === 'darwin') {
  2607. await w.loadFile(overlayHTML);
  2608. } else {
  2609. const overlayReady = once(ipcMain, 'geometrychange');
  2610. await w.loadFile(overlayHTML);
  2611. await overlayReady;
  2612. }
  2613. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2614. expect(overlayEnabled).to.be.true('overlayEnabled');
  2615. const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2616. expect(overlayRect.y).to.equal(0);
  2617. if (process.platform === 'darwin') {
  2618. expect(overlayRect.x).to.be.greaterThan(0);
  2619. } else {
  2620. expect(overlayRect.x).to.equal(0);
  2621. }
  2622. expect(overlayRect.width).to.be.greaterThan(0);
  2623. expect(overlayRect.height).to.be.greaterThan(0);
  2624. const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
  2625. expect(cssOverlayRect).to.deep.equal(overlayRect);
  2626. const geometryChange = once(ipcMain, 'geometrychange');
  2627. w.setBounds({ width: 800 });
  2628. const [, newOverlayRect] = await geometryChange;
  2629. expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
  2630. };
  2631. afterEach(async () => {
  2632. await closeAllWindows();
  2633. ipcMain.removeAllListeners('geometrychange');
  2634. });
  2635. it('creates browser window with hidden title bar', () => {
  2636. const w = new BrowserWindow({
  2637. show: false,
  2638. width: 400,
  2639. height: 400,
  2640. titleBarStyle: 'hidden'
  2641. });
  2642. const contentSize = w.getContentSize();
  2643. expect(contentSize).to.deep.equal([400, 400]);
  2644. });
  2645. ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
  2646. const w = new BrowserWindow({
  2647. show: false,
  2648. width: 400,
  2649. height: 400,
  2650. titleBarStyle: 'hiddenInset'
  2651. });
  2652. const contentSize = w.getContentSize();
  2653. expect(contentSize).to.deep.equal([400, 400]);
  2654. });
  2655. it('sets Window Control Overlay with hidden title bar', async () => {
  2656. await testWindowsOverlay('hidden');
  2657. });
  2658. ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
  2659. await testWindowsOverlay('hiddenInset');
  2660. });
  2661. ifdescribe(process.platform !== 'darwin')('when an invalid titleBarStyle is initially set', () => {
  2662. let w: BrowserWindow;
  2663. beforeEach(() => {
  2664. w = new BrowserWindow({
  2665. show: false,
  2666. webPreferences: {
  2667. nodeIntegration: true,
  2668. contextIsolation: false
  2669. },
  2670. titleBarOverlay: {
  2671. color: '#0000f0',
  2672. symbolColor: '#ffffff'
  2673. },
  2674. titleBarStyle: 'hiddenInset'
  2675. });
  2676. });
  2677. afterEach(async () => {
  2678. await closeAllWindows();
  2679. });
  2680. it('does not crash changing minimizability ', () => {
  2681. expect(() => {
  2682. w.setMinimizable(false);
  2683. }).to.not.throw();
  2684. });
  2685. it('does not crash changing maximizability', () => {
  2686. expect(() => {
  2687. w.setMaximizable(false);
  2688. }).to.not.throw();
  2689. });
  2690. });
  2691. });
  2692. describe('"titleBarOverlay" option', () => {
  2693. const testWindowsOverlayHeight = async (size: any) => {
  2694. const w = new BrowserWindow({
  2695. show: false,
  2696. width: 400,
  2697. height: 400,
  2698. titleBarStyle: 'hidden',
  2699. webPreferences: {
  2700. nodeIntegration: true,
  2701. contextIsolation: false
  2702. },
  2703. titleBarOverlay: {
  2704. height: size
  2705. }
  2706. });
  2707. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2708. if (process.platform === 'darwin') {
  2709. await w.loadFile(overlayHTML);
  2710. } else {
  2711. const overlayReady = once(ipcMain, 'geometrychange');
  2712. await w.loadFile(overlayHTML);
  2713. await overlayReady;
  2714. }
  2715. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2716. expect(overlayEnabled).to.be.true('overlayEnabled');
  2717. const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2718. expect(overlayRectPreMax.y).to.equal(0);
  2719. if (process.platform === 'darwin') {
  2720. expect(overlayRectPreMax.x).to.be.greaterThan(0);
  2721. } else {
  2722. expect(overlayRectPreMax.x).to.equal(0);
  2723. }
  2724. expect(overlayRectPreMax.width).to.be.greaterThan(0);
  2725. expect(overlayRectPreMax.height).to.equal(size);
  2726. // 'maximize' event is not emitted on Linux in CI.
  2727. if (process.platform !== 'linux' && !w.isMaximized()) {
  2728. const maximize = once(w, 'maximize');
  2729. w.show();
  2730. w.maximize();
  2731. await maximize;
  2732. expect(w.isMaximized()).to.be.true('not maximized');
  2733. const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2734. expect(overlayRectPostMax.height).to.equal(size);
  2735. }
  2736. };
  2737. afterEach(async () => {
  2738. await closeAllWindows();
  2739. ipcMain.removeAllListeners('geometrychange');
  2740. });
  2741. it('sets Window Control Overlay with title bar height of 40', async () => {
  2742. await testWindowsOverlayHeight(40);
  2743. });
  2744. });
  2745. ifdescribe(process.platform !== 'darwin')('BrowserWindow.setTitlebarOverlay', () => {
  2746. afterEach(async () => {
  2747. await closeAllWindows();
  2748. ipcMain.removeAllListeners('geometrychange');
  2749. });
  2750. it('throws when an invalid titleBarStyle is initially set', () => {
  2751. const win = new BrowserWindow({
  2752. show: false,
  2753. webPreferences: {
  2754. nodeIntegration: true,
  2755. contextIsolation: false
  2756. },
  2757. titleBarOverlay: {
  2758. color: '#0000f0',
  2759. symbolColor: '#ffffff'
  2760. },
  2761. titleBarStyle: 'hiddenInset'
  2762. });
  2763. expect(() => {
  2764. win.setTitleBarOverlay({
  2765. color: '#000000'
  2766. });
  2767. }).to.throw('Titlebar overlay is not enabled');
  2768. });
  2769. it('correctly updates the height of the overlay', async () => {
  2770. const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
  2771. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2772. const overlayReady = once(ipcMain, 'geometrychange');
  2773. await w.loadFile(overlayHTML);
  2774. if (firstRun) {
  2775. await overlayReady;
  2776. }
  2777. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2778. expect(overlayEnabled).to.be.true('overlayEnabled');
  2779. const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2780. expect(preMaxHeight).to.equal(size);
  2781. // 'maximize' event is not emitted on Linux in CI.
  2782. if (process.platform !== 'linux' && !w.isMaximized()) {
  2783. const maximize = once(w, 'maximize');
  2784. w.show();
  2785. w.maximize();
  2786. await maximize;
  2787. expect(w.isMaximized()).to.be.true('not maximized');
  2788. const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2789. expect(x).to.equal(0);
  2790. expect(y).to.equal(0);
  2791. expect(width).to.be.greaterThan(0);
  2792. expect(height).to.equal(size);
  2793. }
  2794. };
  2795. const INITIAL_SIZE = 40;
  2796. const w = new BrowserWindow({
  2797. show: false,
  2798. width: 400,
  2799. height: 400,
  2800. titleBarStyle: 'hidden',
  2801. webPreferences: {
  2802. nodeIntegration: true,
  2803. contextIsolation: false
  2804. },
  2805. titleBarOverlay: {
  2806. height: INITIAL_SIZE
  2807. }
  2808. });
  2809. await testOverlay(w, INITIAL_SIZE, true);
  2810. w.setTitleBarOverlay({
  2811. height: INITIAL_SIZE + 10
  2812. });
  2813. await testOverlay(w, INITIAL_SIZE + 10, false);
  2814. });
  2815. });
  2816. ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
  2817. afterEach(closeAllWindows);
  2818. it('can move the window out of screen', () => {
  2819. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2820. w.setPosition(-10, 50);
  2821. const after = w.getPosition();
  2822. expect(after).to.deep.equal([-10, 50]);
  2823. });
  2824. it('cannot move the window behind menu bar', () => {
  2825. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2826. w.setPosition(-10, -10);
  2827. const after = w.getPosition();
  2828. expect(after[1]).to.be.at.least(0);
  2829. });
  2830. it('can move the window behind menu bar if it has no frame', () => {
  2831. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
  2832. w.setPosition(-10, -10);
  2833. const after = w.getPosition();
  2834. expect(after[0]).to.be.equal(-10);
  2835. expect(after[1]).to.be.equal(-10);
  2836. });
  2837. it('without it, cannot move the window out of screen', () => {
  2838. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2839. w.setPosition(-10, -10);
  2840. const after = w.getPosition();
  2841. expect(after[1]).to.be.at.least(0);
  2842. });
  2843. it('can set the window larger than screen', () => {
  2844. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2845. const size = screen.getPrimaryDisplay().size;
  2846. size.width += 100;
  2847. size.height += 100;
  2848. w.setSize(size.width, size.height);
  2849. expectBoundsEqual(w.getSize(), [size.width, size.height]);
  2850. });
  2851. it('without it, cannot set the window larger than screen', () => {
  2852. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2853. const size = screen.getPrimaryDisplay().size;
  2854. size.width += 100;
  2855. size.height += 100;
  2856. w.setSize(size.width, size.height);
  2857. expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
  2858. });
  2859. });
  2860. ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
  2861. afterEach(closeAllWindows);
  2862. it('sets the window width to the page width when used', () => {
  2863. const w = new BrowserWindow({
  2864. show: false,
  2865. width: 500,
  2866. height: 400,
  2867. zoomToPageWidth: true
  2868. });
  2869. w.maximize();
  2870. expect(w.getSize()[0]).to.equal(500);
  2871. });
  2872. });
  2873. describe('"tabbingIdentifier" option', () => {
  2874. afterEach(closeAllWindows);
  2875. it('can be set on a window', () => {
  2876. expect(() => {
  2877. /* eslint-disable-next-line no-new */
  2878. new BrowserWindow({
  2879. tabbingIdentifier: 'group1'
  2880. });
  2881. /* eslint-disable-next-line no-new */
  2882. new BrowserWindow({
  2883. tabbingIdentifier: 'group2',
  2884. frame: false
  2885. });
  2886. }).not.to.throw();
  2887. });
  2888. });
  2889. describe('"webPreferences" option', () => {
  2890. afterEach(() => { ipcMain.removeAllListeners('answer'); });
  2891. afterEach(closeAllWindows);
  2892. describe('"preload" option', () => {
  2893. const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
  2894. it(name, async () => {
  2895. const w = new BrowserWindow({
  2896. webPreferences: {
  2897. ...webPrefs,
  2898. preload: path.resolve(fixtures, 'module', 'empty.js')
  2899. },
  2900. show: false
  2901. });
  2902. w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
  2903. const [, result] = await once(ipcMain, 'leak-result');
  2904. expect(result).to.have.property('require', 'undefined');
  2905. expect(result).to.have.property('exports', 'undefined');
  2906. expect(result).to.have.property('windowExports', 'undefined');
  2907. expect(result).to.have.property('windowPreload', 'undefined');
  2908. expect(result).to.have.property('windowRequire', 'undefined');
  2909. });
  2910. };
  2911. doesNotLeakSpec('does not leak require', {
  2912. nodeIntegration: false,
  2913. sandbox: false,
  2914. contextIsolation: false
  2915. });
  2916. doesNotLeakSpec('does not leak require when sandbox is enabled', {
  2917. nodeIntegration: false,
  2918. sandbox: true,
  2919. contextIsolation: false
  2920. });
  2921. doesNotLeakSpec('does not leak require when context isolation is enabled', {
  2922. nodeIntegration: false,
  2923. sandbox: false,
  2924. contextIsolation: true
  2925. });
  2926. doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
  2927. nodeIntegration: false,
  2928. sandbox: true,
  2929. contextIsolation: true
  2930. });
  2931. it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
  2932. let w = new BrowserWindow({
  2933. webPreferences: {
  2934. contextIsolation: false,
  2935. nodeIntegration: false,
  2936. preload: path.resolve(fixtures, 'module', 'empty.js')
  2937. },
  2938. show: false
  2939. });
  2940. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2941. const [, notIsolated] = await once(ipcMain, 'leak-result');
  2942. expect(notIsolated).to.have.property('globals');
  2943. w.destroy();
  2944. w = new BrowserWindow({
  2945. webPreferences: {
  2946. contextIsolation: true,
  2947. nodeIntegration: false,
  2948. preload: path.resolve(fixtures, 'module', 'empty.js')
  2949. },
  2950. show: false
  2951. });
  2952. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2953. const [, isolated] = await once(ipcMain, 'leak-result');
  2954. expect(isolated).to.have.property('globals');
  2955. const notIsolatedGlobals = new Set(notIsolated.globals);
  2956. for (const isolatedGlobal of isolated.globals) {
  2957. notIsolatedGlobals.delete(isolatedGlobal);
  2958. }
  2959. expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
  2960. });
  2961. it('loads the script before other scripts in window', async () => {
  2962. const preload = path.join(fixtures, 'module', 'set-global.js');
  2963. const w = new BrowserWindow({
  2964. show: false,
  2965. webPreferences: {
  2966. nodeIntegration: true,
  2967. contextIsolation: false,
  2968. preload
  2969. }
  2970. });
  2971. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2972. const [, test] = await once(ipcMain, 'answer');
  2973. expect(test).to.eql('preload');
  2974. });
  2975. it('has synchronous access to all eventual window APIs', async () => {
  2976. const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
  2977. const w = new BrowserWindow({
  2978. show: false,
  2979. webPreferences: {
  2980. nodeIntegration: true,
  2981. contextIsolation: false,
  2982. preload
  2983. }
  2984. });
  2985. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2986. const [, test] = await once(ipcMain, 'answer');
  2987. expect(test).to.be.an('object');
  2988. expect(test.atPreload).to.be.an('array');
  2989. expect(test.atLoad).to.be.an('array');
  2990. expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
  2991. });
  2992. });
  2993. describe('session preload scripts', function () {
  2994. const preloads = [
  2995. path.join(fixtures, 'module', 'set-global-preload-1.js'),
  2996. path.join(fixtures, 'module', 'set-global-preload-2.js'),
  2997. path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
  2998. ];
  2999. const defaultSession = session.defaultSession;
  3000. beforeEach(() => {
  3001. expect(defaultSession.getPreloads()).to.deep.equal([]);
  3002. defaultSession.setPreloads(preloads);
  3003. });
  3004. afterEach(() => {
  3005. defaultSession.setPreloads([]);
  3006. });
  3007. it('can set multiple session preload script', () => {
  3008. expect(defaultSession.getPreloads()).to.deep.equal(preloads);
  3009. });
  3010. const generateSpecs = (description: string, sandbox: boolean) => {
  3011. describe(description, () => {
  3012. it('loads the script before other scripts in window including normal preloads', async () => {
  3013. const w = new BrowserWindow({
  3014. show: false,
  3015. webPreferences: {
  3016. sandbox,
  3017. preload: path.join(fixtures, 'module', 'get-global-preload.js'),
  3018. contextIsolation: false
  3019. }
  3020. });
  3021. w.loadURL('about:blank');
  3022. const [, preload1, preload2, preload3] = await once(ipcMain, 'vars');
  3023. expect(preload1).to.equal('preload-1');
  3024. expect(preload2).to.equal('preload-1-2');
  3025. expect(preload3).to.be.undefined('preload 3');
  3026. });
  3027. });
  3028. };
  3029. generateSpecs('without sandbox', false);
  3030. generateSpecs('with sandbox', true);
  3031. });
  3032. describe('"additionalArguments" option', () => {
  3033. it('adds extra args to process.argv in the renderer process', async () => {
  3034. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  3035. const w = new BrowserWindow({
  3036. show: false,
  3037. webPreferences: {
  3038. nodeIntegration: true,
  3039. preload,
  3040. additionalArguments: ['--my-magic-arg']
  3041. }
  3042. });
  3043. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  3044. const [, argv] = await once(ipcMain, 'answer');
  3045. expect(argv).to.include('--my-magic-arg');
  3046. });
  3047. it('adds extra value args to process.argv in the renderer process', async () => {
  3048. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  3049. const w = new BrowserWindow({
  3050. show: false,
  3051. webPreferences: {
  3052. nodeIntegration: true,
  3053. preload,
  3054. additionalArguments: ['--my-magic-arg=foo']
  3055. }
  3056. });
  3057. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  3058. const [, argv] = await once(ipcMain, 'answer');
  3059. expect(argv).to.include('--my-magic-arg=foo');
  3060. });
  3061. });
  3062. describe('"node-integration" option', () => {
  3063. it('disables node integration by default', async () => {
  3064. const preload = path.join(fixtures, 'module', 'send-later.js');
  3065. const w = new BrowserWindow({
  3066. show: false,
  3067. webPreferences: {
  3068. preload,
  3069. contextIsolation: false
  3070. }
  3071. });
  3072. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  3073. const [, typeofProcess, typeofBuffer] = await once(ipcMain, 'answer');
  3074. expect(typeofProcess).to.equal('undefined');
  3075. expect(typeofBuffer).to.equal('undefined');
  3076. });
  3077. });
  3078. describe('"sandbox" option', () => {
  3079. const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
  3080. let server: http.Server;
  3081. let serverUrl: string;
  3082. before(async () => {
  3083. server = http.createServer((request, response) => {
  3084. switch (request.url) {
  3085. case '/cross-site':
  3086. response.end(`<html><body><h1>${request.url}</h1></body></html>`);
  3087. break;
  3088. default:
  3089. throw new Error(`unsupported endpoint: ${request.url}`);
  3090. }
  3091. });
  3092. serverUrl = (await listen(server)).url;
  3093. });
  3094. after(() => {
  3095. server.close();
  3096. });
  3097. it('exposes ipcRenderer to preload script', async () => {
  3098. const w = new BrowserWindow({
  3099. show: false,
  3100. webPreferences: {
  3101. sandbox: true,
  3102. preload,
  3103. contextIsolation: false
  3104. }
  3105. });
  3106. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  3107. const [, test] = await once(ipcMain, 'answer');
  3108. expect(test).to.equal('preload');
  3109. });
  3110. it('exposes ipcRenderer to preload script (path has special chars)', async () => {
  3111. const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
  3112. const w = new BrowserWindow({
  3113. show: false,
  3114. webPreferences: {
  3115. sandbox: true,
  3116. preload: preloadSpecialChars,
  3117. contextIsolation: false
  3118. }
  3119. });
  3120. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  3121. const [, test] = await once(ipcMain, 'answer');
  3122. expect(test).to.equal('preload');
  3123. });
  3124. it('exposes "loaded" event to preload script', async () => {
  3125. const w = new BrowserWindow({
  3126. show: false,
  3127. webPreferences: {
  3128. sandbox: true,
  3129. preload
  3130. }
  3131. });
  3132. w.loadURL('about:blank');
  3133. await once(ipcMain, 'process-loaded');
  3134. });
  3135. it('exposes "exit" event to preload script', async () => {
  3136. const w = new BrowserWindow({
  3137. show: false,
  3138. webPreferences: {
  3139. sandbox: true,
  3140. preload,
  3141. contextIsolation: false
  3142. }
  3143. });
  3144. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
  3145. const pageUrl = 'file://' + htmlPath;
  3146. w.loadURL(pageUrl);
  3147. const [, url] = await once(ipcMain, 'answer');
  3148. const expectedUrl = process.platform === 'win32'
  3149. ? 'file:///' + htmlPath.replaceAll('\\', '/')
  3150. : pageUrl;
  3151. expect(url).to.equal(expectedUrl);
  3152. });
  3153. it('exposes full EventEmitter object to preload script', async () => {
  3154. const w = new BrowserWindow({
  3155. show: false,
  3156. webPreferences: {
  3157. sandbox: true,
  3158. preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
  3159. }
  3160. });
  3161. w.loadURL('about:blank');
  3162. const [, rendererEventEmitterProperties] = await once(ipcMain, 'answer');
  3163. const { EventEmitter } = require('node:events');
  3164. const emitter = new EventEmitter();
  3165. const browserEventEmitterProperties = [];
  3166. let currentObj = emitter;
  3167. do {
  3168. browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
  3169. } while ((currentObj = Object.getPrototypeOf(currentObj)));
  3170. expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
  3171. });
  3172. it('should open windows in same domain with cross-scripting enabled', async () => {
  3173. const w = new BrowserWindow({
  3174. show: true,
  3175. webPreferences: {
  3176. sandbox: true,
  3177. preload,
  3178. contextIsolation: false
  3179. }
  3180. });
  3181. w.webContents.setWindowOpenHandler(() => ({
  3182. action: 'allow',
  3183. overrideBrowserWindowOptions: {
  3184. webPreferences: {
  3185. preload
  3186. }
  3187. }
  3188. }));
  3189. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
  3190. const pageUrl = 'file://' + htmlPath;
  3191. const answer = once(ipcMain, 'answer');
  3192. w.loadURL(pageUrl);
  3193. const [, { url, frameName, options }] = await once(w.webContents, 'did-create-window') as [BrowserWindow, Electron.DidCreateWindowDetails];
  3194. const expectedUrl = process.platform === 'win32'
  3195. ? 'file:///' + htmlPath.replaceAll('\\', '/')
  3196. : pageUrl;
  3197. expect(url).to.equal(expectedUrl);
  3198. expect(frameName).to.equal('popup!');
  3199. expect(options.width).to.equal(500);
  3200. expect(options.height).to.equal(600);
  3201. const [, html] = await answer;
  3202. expect(html).to.equal('<h1>scripting from opener</h1>');
  3203. });
  3204. it('should open windows in another domain with cross-scripting disabled', async () => {
  3205. const w = new BrowserWindow({
  3206. show: true,
  3207. webPreferences: {
  3208. sandbox: true,
  3209. preload,
  3210. contextIsolation: false
  3211. }
  3212. });
  3213. w.webContents.setWindowOpenHandler(() => ({
  3214. action: 'allow',
  3215. overrideBrowserWindowOptions: {
  3216. webPreferences: {
  3217. preload
  3218. }
  3219. }
  3220. }));
  3221. w.loadFile(
  3222. path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
  3223. { search: 'window-open-external' }
  3224. );
  3225. // Wait for a message from the main window saying that it's ready.
  3226. await once(ipcMain, 'opener-loaded');
  3227. // Ask the opener to open a popup with window.opener.
  3228. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
  3229. w.webContents.send('open-the-popup', expectedPopupUrl);
  3230. // The page is going to open a popup that it won't be able to close.
  3231. // We have to close it from here later.
  3232. const [, popupWindow] = await once(app, 'browser-window-created') as [any, BrowserWindow];
  3233. // Ask the popup window for details.
  3234. const detailsAnswer = once(ipcMain, 'child-loaded');
  3235. popupWindow.webContents.send('provide-details');
  3236. const [, openerIsNull, , locationHref] = await detailsAnswer;
  3237. expect(openerIsNull).to.be.false('window.opener is null');
  3238. expect(locationHref).to.equal(expectedPopupUrl);
  3239. // Ask the page to access the popup.
  3240. const touchPopupResult = once(ipcMain, 'answer');
  3241. w.webContents.send('touch-the-popup');
  3242. const [, popupAccessMessage] = await touchPopupResult;
  3243. // Ask the popup to access the opener.
  3244. const touchOpenerResult = once(ipcMain, 'answer');
  3245. popupWindow.webContents.send('touch-the-opener');
  3246. const [, openerAccessMessage] = await touchOpenerResult;
  3247. // We don't need the popup anymore, and its parent page can't close it,
  3248. // so let's close it from here before we run any checks.
  3249. await closeWindow(popupWindow, { assertNotWindows: false });
  3250. const errorPattern = /Failed to read a named property 'document' from 'Window': Blocked a frame with origin "(.*?)" from accessing a cross-origin frame./;
  3251. expect(popupAccessMessage).to.be.a('string',
  3252. 'child\'s .document is accessible from its parent window');
  3253. expect(popupAccessMessage).to.match(errorPattern);
  3254. expect(openerAccessMessage).to.be.a('string',
  3255. 'opener .document is accessible from a popup window');
  3256. expect(openerAccessMessage).to.match(errorPattern);
  3257. });
  3258. it('should inherit the sandbox setting in opened windows', async () => {
  3259. const w = new BrowserWindow({
  3260. show: false,
  3261. webPreferences: {
  3262. sandbox: true
  3263. }
  3264. });
  3265. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  3266. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
  3267. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  3268. const [, { argv }] = await once(ipcMain, 'answer');
  3269. expect(argv).to.include('--enable-sandbox');
  3270. });
  3271. it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
  3272. const w = new BrowserWindow({
  3273. show: false,
  3274. webPreferences: {
  3275. sandbox: true
  3276. }
  3277. });
  3278. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  3279. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
  3280. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  3281. const [[, childWebContents]] = await Promise.all([
  3282. once(app, 'web-contents-created') as Promise<[any, WebContents]>,
  3283. once(ipcMain, 'answer')
  3284. ]);
  3285. const webPreferences = childWebContents.getLastWebPreferences();
  3286. expect(webPreferences!.contextIsolation).to.equal(false);
  3287. });
  3288. it('should set ipc event sender correctly', async () => {
  3289. const w = new BrowserWindow({
  3290. show: false,
  3291. webPreferences: {
  3292. sandbox: true,
  3293. preload,
  3294. contextIsolation: false
  3295. }
  3296. });
  3297. let childWc: WebContents | null = null;
  3298. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
  3299. w.webContents.on('did-create-window', (win) => {
  3300. childWc = win.webContents;
  3301. expect(w.webContents).to.not.equal(childWc);
  3302. });
  3303. ipcMain.once('parent-ready', function (event) {
  3304. expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
  3305. event.sender.send('verified');
  3306. });
  3307. ipcMain.once('child-ready', function (event) {
  3308. expect(childWc).to.not.be.null('child webcontents should be available');
  3309. expect(event.sender).to.equal(childWc, 'sender should be the child');
  3310. event.sender.send('verified');
  3311. });
  3312. const done = Promise.all([
  3313. 'parent-answer',
  3314. 'child-answer'
  3315. ].map(name => once(ipcMain, name)));
  3316. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
  3317. await done;
  3318. });
  3319. describe('event handling', () => {
  3320. let w: BrowserWindow;
  3321. beforeEach(() => {
  3322. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  3323. });
  3324. it('works for window events', async () => {
  3325. const pageTitleUpdated = once(w, 'page-title-updated');
  3326. w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
  3327. await pageTitleUpdated;
  3328. });
  3329. it('works for stop events', async () => {
  3330. const done = Promise.all([
  3331. 'did-navigate',
  3332. 'did-fail-load',
  3333. 'did-stop-loading'
  3334. ].map(name => once(w.webContents, name)));
  3335. w.loadURL('data:text/html,<script>stop()</script>');
  3336. await done;
  3337. });
  3338. it('works for web contents events', async () => {
  3339. const done = Promise.all([
  3340. 'did-finish-load',
  3341. 'did-frame-finish-load',
  3342. 'did-navigate-in-page',
  3343. 'will-navigate',
  3344. 'did-start-loading',
  3345. 'did-stop-loading',
  3346. 'did-frame-finish-load',
  3347. 'dom-ready'
  3348. ].map(name => once(w.webContents, name)));
  3349. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
  3350. await done;
  3351. });
  3352. });
  3353. it('validates process APIs access in sandboxed renderer', async () => {
  3354. const w = new BrowserWindow({
  3355. show: false,
  3356. webPreferences: {
  3357. sandbox: true,
  3358. preload,
  3359. contextIsolation: false
  3360. }
  3361. });
  3362. w.webContents.once('preload-error', (event, preloadPath, error) => {
  3363. throw error;
  3364. });
  3365. process.env.sandboxmain = 'foo';
  3366. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  3367. const [, test] = await once(ipcMain, 'answer');
  3368. expect(test.hasCrash).to.be.true('has crash');
  3369. expect(test.hasHang).to.be.true('has hang');
  3370. expect(test.heapStatistics).to.be.an('object');
  3371. expect(test.blinkMemoryInfo).to.be.an('object');
  3372. expect(test.processMemoryInfo).to.be.an('object');
  3373. expect(test.systemVersion).to.be.a('string');
  3374. expect(test.cpuUsage).to.be.an('object');
  3375. expect(test.uptime).to.be.a('number');
  3376. expect(test.arch).to.equal(process.arch);
  3377. expect(test.platform).to.equal(process.platform);
  3378. expect(test.env).to.deep.equal(process.env);
  3379. expect(test.execPath).to.equal(process.helperExecPath);
  3380. expect(test.sandboxed).to.be.true('sandboxed');
  3381. expect(test.contextIsolated).to.be.false('contextIsolated');
  3382. expect(test.type).to.equal('renderer');
  3383. expect(test.version).to.equal(process.version);
  3384. expect(test.versions).to.deep.equal(process.versions);
  3385. expect(test.contextId).to.be.a('string');
  3386. expect(test.nodeEvents).to.equal(true);
  3387. expect(test.nodeTimers).to.equal(true);
  3388. expect(test.nodeUrl).to.equal(true);
  3389. if (process.platform === 'linux' && test.osSandbox) {
  3390. expect(test.creationTime).to.be.null('creation time');
  3391. expect(test.systemMemoryInfo).to.be.null('system memory info');
  3392. } else {
  3393. expect(test.creationTime).to.be.a('number');
  3394. expect(test.systemMemoryInfo).to.be.an('object');
  3395. }
  3396. });
  3397. it('webview in sandbox renderer', async () => {
  3398. const w = new BrowserWindow({
  3399. show: false,
  3400. webPreferences: {
  3401. sandbox: true,
  3402. preload,
  3403. webviewTag: true,
  3404. contextIsolation: false
  3405. }
  3406. });
  3407. const didAttachWebview = once(w.webContents, 'did-attach-webview') as Promise<[any, WebContents]>;
  3408. const webviewDomReady = once(ipcMain, 'webview-dom-ready');
  3409. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  3410. const [, webContents] = await didAttachWebview;
  3411. const [, id] = await webviewDomReady;
  3412. expect(webContents.id).to.equal(id);
  3413. });
  3414. });
  3415. describe('child windows', () => {
  3416. let w: BrowserWindow;
  3417. beforeEach(() => {
  3418. w = new BrowserWindow({
  3419. show: false,
  3420. webPreferences: {
  3421. nodeIntegration: true,
  3422. // tests relies on preloads in opened windows
  3423. nodeIntegrationInSubFrames: true,
  3424. contextIsolation: false
  3425. }
  3426. });
  3427. });
  3428. it('opens window of about:blank with cross-scripting enabled', async () => {
  3429. const answer = once(ipcMain, 'answer');
  3430. w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
  3431. const [, content] = await answer;
  3432. expect(content).to.equal('Hello');
  3433. });
  3434. it('opens window of same domain with cross-scripting enabled', async () => {
  3435. const answer = once(ipcMain, 'answer');
  3436. w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
  3437. const [, content] = await answer;
  3438. expect(content).to.equal('Hello');
  3439. });
  3440. it('blocks accessing cross-origin frames', async () => {
  3441. const answer = once(ipcMain, 'answer');
  3442. w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
  3443. const [, content] = await answer;
  3444. expect(content).to.equal('Failed to read a named property \'toString\' from \'Location\': Blocked a frame with origin "file://" from accessing a cross-origin frame.');
  3445. });
  3446. it('opens window from <iframe> tags', async () => {
  3447. const answer = once(ipcMain, 'answer');
  3448. w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
  3449. const [, content] = await answer;
  3450. expect(content).to.equal('Hello');
  3451. });
  3452. it('opens window with cross-scripting enabled from isolated context', async () => {
  3453. const w = new BrowserWindow({
  3454. show: false,
  3455. webPreferences: {
  3456. preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
  3457. }
  3458. });
  3459. w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
  3460. const [, content] = await once(ipcMain, 'answer');
  3461. expect(content).to.equal('Hello');
  3462. });
  3463. ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
  3464. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
  3465. {
  3466. const [, content] = await once(ipcMain, 'answer');
  3467. expect(content).to.equal('function');
  3468. }
  3469. w.reload();
  3470. {
  3471. const [, content] = await once(ipcMain, 'answer');
  3472. expect(content).to.equal('function');
  3473. }
  3474. });
  3475. it('<webview> works in a scriptable popup', async () => {
  3476. const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
  3477. const w = new BrowserWindow({
  3478. show: false,
  3479. webPreferences: {
  3480. nodeIntegrationInSubFrames: true,
  3481. webviewTag: true,
  3482. contextIsolation: false,
  3483. preload
  3484. }
  3485. });
  3486. w.webContents.setWindowOpenHandler(() => ({
  3487. action: 'allow',
  3488. overrideBrowserWindowOptions: {
  3489. show: false,
  3490. webPreferences: {
  3491. contextIsolation: false,
  3492. webviewTag: true,
  3493. nodeIntegrationInSubFrames: true,
  3494. preload
  3495. }
  3496. }
  3497. }));
  3498. const webviewLoaded = once(ipcMain, 'webview-loaded');
  3499. w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
  3500. await webviewLoaded;
  3501. });
  3502. it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
  3503. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  3504. w.webContents.setWindowOpenHandler(() => ({
  3505. action: 'allow',
  3506. overrideBrowserWindowOptions: {
  3507. webPreferences: {
  3508. preload: preloadPath,
  3509. contextIsolation: false
  3510. }
  3511. }
  3512. }));
  3513. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  3514. const [[, childWebContents]] = await Promise.all([
  3515. once(app, 'web-contents-created') as Promise<[any, WebContents]>,
  3516. once(ipcMain, 'answer')
  3517. ]);
  3518. const webPreferences = childWebContents.getLastWebPreferences();
  3519. expect(webPreferences!.contextIsolation).to.equal(false);
  3520. });
  3521. describe('window.location', () => {
  3522. const protocols = [
  3523. ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
  3524. ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
  3525. ];
  3526. beforeEach(() => {
  3527. for (const [scheme, path] of protocols) {
  3528. protocol.registerBufferProtocol(scheme, (request, callback) => {
  3529. callback({
  3530. mimeType: 'text/html',
  3531. data: fs.readFileSync(path)
  3532. });
  3533. });
  3534. }
  3535. });
  3536. afterEach(() => {
  3537. for (const [scheme] of protocols) {
  3538. protocol.unregisterProtocol(scheme);
  3539. }
  3540. });
  3541. it('retains the original web preferences when window.location is changed to a new origin', async () => {
  3542. const w = new BrowserWindow({
  3543. show: false,
  3544. webPreferences: {
  3545. // test relies on preloads in opened window
  3546. nodeIntegrationInSubFrames: true,
  3547. contextIsolation: false
  3548. }
  3549. });
  3550. w.webContents.setWindowOpenHandler(() => ({
  3551. action: 'allow',
  3552. overrideBrowserWindowOptions: {
  3553. webPreferences: {
  3554. preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
  3555. contextIsolation: false,
  3556. nodeIntegrationInSubFrames: true
  3557. }
  3558. }
  3559. }));
  3560. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  3561. const [, { nodeIntegration, typeofProcess }] = await once(ipcMain, 'answer');
  3562. expect(nodeIntegration).to.be.false();
  3563. expect(typeofProcess).to.eql('undefined');
  3564. });
  3565. it('window.opener is not null when window.location is changed to a new origin', async () => {
  3566. const w = new BrowserWindow({
  3567. show: false,
  3568. webPreferences: {
  3569. // test relies on preloads in opened window
  3570. nodeIntegrationInSubFrames: true
  3571. }
  3572. });
  3573. w.webContents.setWindowOpenHandler(() => ({
  3574. action: 'allow',
  3575. overrideBrowserWindowOptions: {
  3576. webPreferences: {
  3577. preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
  3578. }
  3579. }
  3580. }));
  3581. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  3582. const [, { windowOpenerIsNull }] = await once(ipcMain, 'answer');
  3583. expect(windowOpenerIsNull).to.be.false('window.opener is null');
  3584. });
  3585. });
  3586. });
  3587. describe('"disableHtmlFullscreenWindowResize" option', () => {
  3588. it('prevents window from resizing when set', async () => {
  3589. const w = new BrowserWindow({
  3590. show: false,
  3591. webPreferences: {
  3592. disableHtmlFullscreenWindowResize: true
  3593. }
  3594. });
  3595. await w.loadURL('about:blank');
  3596. const size = w.getSize();
  3597. const enterHtmlFullScreen = once(w.webContents, 'enter-html-full-screen');
  3598. w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  3599. await enterHtmlFullScreen;
  3600. expect(w.getSize()).to.deep.equal(size);
  3601. });
  3602. });
  3603. describe('"defaultFontFamily" option', () => {
  3604. it('can change the standard font family', async () => {
  3605. const w = new BrowserWindow({
  3606. show: false,
  3607. webPreferences: {
  3608. defaultFontFamily: {
  3609. standard: 'Impact'
  3610. }
  3611. }
  3612. });
  3613. await w.loadFile(path.join(fixtures, 'pages', 'content.html'));
  3614. const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true);
  3615. expect(fontFamily).to.equal('Impact');
  3616. });
  3617. });
  3618. });
  3619. describe('beforeunload handler', function () {
  3620. let w: BrowserWindow;
  3621. beforeEach(() => {
  3622. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  3623. });
  3624. afterEach(closeAllWindows);
  3625. it('returning undefined would not prevent close', async () => {
  3626. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  3627. const wait = once(w, 'closed');
  3628. w.close();
  3629. await wait;
  3630. });
  3631. it('returning false would prevent close', async () => {
  3632. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  3633. w.close();
  3634. const [, proceed] = await once(w.webContents, '-before-unload-fired');
  3635. expect(proceed).to.equal(false);
  3636. });
  3637. it('returning empty string would prevent close', async () => {
  3638. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
  3639. w.close();
  3640. const [, proceed] = await once(w.webContents, '-before-unload-fired');
  3641. expect(proceed).to.equal(false);
  3642. });
  3643. it('emits for each close attempt', async () => {
  3644. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3645. const destroyListener = () => { expect.fail('Close was not prevented'); };
  3646. w.webContents.once('destroyed', destroyListener);
  3647. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3648. // The renderer needs to report the status of beforeunload handler
  3649. // back to main process, so wait for next console message, which means
  3650. // the SuddenTerminationStatus message have been flushed.
  3651. await once(w.webContents, 'console-message');
  3652. w.close();
  3653. await once(w.webContents, '-before-unload-fired');
  3654. w.close();
  3655. await once(w.webContents, '-before-unload-fired');
  3656. w.webContents.removeListener('destroyed', destroyListener);
  3657. const wait = once(w, 'closed');
  3658. w.close();
  3659. await wait;
  3660. });
  3661. it('emits for each reload attempt', async () => {
  3662. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3663. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  3664. w.webContents.once('did-start-navigation', navigationListener);
  3665. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3666. // The renderer needs to report the status of beforeunload handler
  3667. // back to main process, so wait for next console message, which means
  3668. // the SuddenTerminationStatus message have been flushed.
  3669. await once(w.webContents, 'console-message');
  3670. w.reload();
  3671. // Chromium does not emit '-before-unload-fired' on WebContents for
  3672. // navigations, so we have to use other ways to know if beforeunload
  3673. // is fired.
  3674. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3675. w.reload();
  3676. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3677. w.webContents.removeListener('did-start-navigation', navigationListener);
  3678. w.reload();
  3679. await once(w.webContents, 'did-finish-load');
  3680. });
  3681. it('emits for each navigation attempt', async () => {
  3682. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3683. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  3684. w.webContents.once('did-start-navigation', navigationListener);
  3685. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3686. // The renderer needs to report the status of beforeunload handler
  3687. // back to main process, so wait for next console message, which means
  3688. // the SuddenTerminationStatus message have been flushed.
  3689. await once(w.webContents, 'console-message');
  3690. w.loadURL('about:blank');
  3691. // Chromium does not emit '-before-unload-fired' on WebContents for
  3692. // navigations, so we have to use other ways to know if beforeunload
  3693. // is fired.
  3694. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3695. w.loadURL('about:blank');
  3696. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3697. w.webContents.removeListener('did-start-navigation', navigationListener);
  3698. await w.loadURL('about:blank');
  3699. });
  3700. });
  3701. // TODO(codebytere): figure out how to make these pass in CI on Windows.
  3702. ifdescribe(process.platform !== 'win32')('document.visibilityState/hidden', () => {
  3703. afterEach(closeAllWindows);
  3704. it('visibilityState is initially visible despite window being hidden', async () => {
  3705. const w = new BrowserWindow({
  3706. show: false,
  3707. width: 100,
  3708. height: 100,
  3709. webPreferences: {
  3710. nodeIntegration: true,
  3711. contextIsolation: false
  3712. }
  3713. });
  3714. let readyToShow = false;
  3715. w.once('ready-to-show', () => {
  3716. readyToShow = true;
  3717. });
  3718. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3719. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  3720. expect(readyToShow).to.be.false('ready to show');
  3721. expect(visibilityState).to.equal('visible');
  3722. expect(hidden).to.be.false('hidden');
  3723. });
  3724. it('visibilityState changes when window is hidden', async () => {
  3725. const w = new BrowserWindow({
  3726. width: 100,
  3727. height: 100,
  3728. webPreferences: {
  3729. nodeIntegration: true,
  3730. contextIsolation: false
  3731. }
  3732. });
  3733. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3734. {
  3735. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  3736. expect(visibilityState).to.equal('visible');
  3737. expect(hidden).to.be.false('hidden');
  3738. }
  3739. w.hide();
  3740. {
  3741. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  3742. expect(visibilityState).to.equal('hidden');
  3743. expect(hidden).to.be.true('hidden');
  3744. }
  3745. });
  3746. it('visibilityState changes when window is shown', async () => {
  3747. const w = new BrowserWindow({
  3748. width: 100,
  3749. height: 100,
  3750. webPreferences: {
  3751. nodeIntegration: true,
  3752. contextIsolation: false
  3753. }
  3754. });
  3755. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3756. if (process.platform === 'darwin') {
  3757. // See https://github.com/electron/electron/issues/8664
  3758. await once(w, 'show');
  3759. }
  3760. w.hide();
  3761. w.show();
  3762. const [, visibilityState] = await once(ipcMain, 'pong');
  3763. expect(visibilityState).to.equal('visible');
  3764. });
  3765. it('visibilityState changes when window is shown inactive', async () => {
  3766. const w = new BrowserWindow({
  3767. width: 100,
  3768. height: 100,
  3769. webPreferences: {
  3770. nodeIntegration: true,
  3771. contextIsolation: false
  3772. }
  3773. });
  3774. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3775. if (process.platform === 'darwin') {
  3776. // See https://github.com/electron/electron/issues/8664
  3777. await once(w, 'show');
  3778. }
  3779. w.hide();
  3780. w.showInactive();
  3781. const [, visibilityState] = await once(ipcMain, 'pong');
  3782. expect(visibilityState).to.equal('visible');
  3783. });
  3784. ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
  3785. const w = new BrowserWindow({
  3786. width: 100,
  3787. height: 100,
  3788. webPreferences: {
  3789. nodeIntegration: true,
  3790. contextIsolation: false
  3791. }
  3792. });
  3793. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3794. {
  3795. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  3796. expect(visibilityState).to.equal('visible');
  3797. expect(hidden).to.be.false('hidden');
  3798. }
  3799. w.minimize();
  3800. {
  3801. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  3802. expect(visibilityState).to.equal('hidden');
  3803. expect(hidden).to.be.true('hidden');
  3804. }
  3805. });
  3806. it('visibilityState remains visible if backgroundThrottling is disabled', async () => {
  3807. const w = new BrowserWindow({
  3808. show: false,
  3809. width: 100,
  3810. height: 100,
  3811. webPreferences: {
  3812. backgroundThrottling: false,
  3813. nodeIntegration: true,
  3814. contextIsolation: false
  3815. }
  3816. });
  3817. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3818. {
  3819. const [, visibilityState, hidden] = await once(ipcMain, 'pong');
  3820. expect(visibilityState).to.equal('visible');
  3821. expect(hidden).to.be.false('hidden');
  3822. }
  3823. ipcMain.once('pong', (event, visibilityState, hidden) => {
  3824. throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
  3825. });
  3826. try {
  3827. const shown1 = once(w, 'show');
  3828. w.show();
  3829. await shown1;
  3830. const hidden = once(w, 'hide');
  3831. w.hide();
  3832. await hidden;
  3833. const shown2 = once(w, 'show');
  3834. w.show();
  3835. await shown2;
  3836. } finally {
  3837. ipcMain.removeAllListeners('pong');
  3838. }
  3839. });
  3840. });
  3841. ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
  3842. afterEach(closeAllWindows);
  3843. it('emits an event when window is maximized', async () => {
  3844. const w = new BrowserWindow({ show: false });
  3845. const maximize = once(w, 'maximize');
  3846. w.show();
  3847. w.maximize();
  3848. await maximize;
  3849. });
  3850. it('emits an event when a transparent window is maximized', async () => {
  3851. const w = new BrowserWindow({
  3852. show: false,
  3853. frame: false,
  3854. transparent: true
  3855. });
  3856. const maximize = once(w, 'maximize');
  3857. w.show();
  3858. w.maximize();
  3859. await maximize;
  3860. });
  3861. it('emits only one event when frameless window is maximized', () => {
  3862. const w = new BrowserWindow({ show: false, frame: false });
  3863. let emitted = 0;
  3864. w.on('maximize', () => emitted++);
  3865. w.show();
  3866. w.maximize();
  3867. expect(emitted).to.equal(1);
  3868. });
  3869. it('emits an event when window is unmaximized', async () => {
  3870. const w = new BrowserWindow({ show: false });
  3871. const unmaximize = once(w, 'unmaximize');
  3872. w.show();
  3873. w.maximize();
  3874. w.unmaximize();
  3875. await unmaximize;
  3876. });
  3877. it('emits an event when a transparent window is unmaximized', async () => {
  3878. const w = new BrowserWindow({
  3879. show: false,
  3880. frame: false,
  3881. transparent: true
  3882. });
  3883. const maximize = once(w, 'maximize');
  3884. const unmaximize = once(w, 'unmaximize');
  3885. w.show();
  3886. w.maximize();
  3887. await maximize;
  3888. w.unmaximize();
  3889. await unmaximize;
  3890. });
  3891. it('emits an event when window is minimized', async () => {
  3892. const w = new BrowserWindow({ show: false });
  3893. const minimize = once(w, 'minimize');
  3894. w.show();
  3895. w.minimize();
  3896. await minimize;
  3897. });
  3898. });
  3899. describe('beginFrameSubscription method', () => {
  3900. it('does not crash when callback returns nothing', (done) => {
  3901. const w = new BrowserWindow({ show: false });
  3902. let called = false;
  3903. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3904. w.webContents.on('dom-ready', () => {
  3905. w.webContents.beginFrameSubscription(function () {
  3906. // This callback might be called twice.
  3907. if (called) return;
  3908. called = true;
  3909. // Pending endFrameSubscription to next tick can reliably reproduce
  3910. // a crash which happens when nothing is returned in the callback.
  3911. setTimeout().then(() => {
  3912. w.webContents.endFrameSubscription();
  3913. done();
  3914. });
  3915. });
  3916. });
  3917. });
  3918. it('subscribes to frame updates', (done) => {
  3919. const w = new BrowserWindow({ show: false });
  3920. let called = false;
  3921. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3922. w.webContents.on('dom-ready', () => {
  3923. w.webContents.beginFrameSubscription(function (data) {
  3924. // This callback might be called twice.
  3925. if (called) return;
  3926. called = true;
  3927. try {
  3928. expect(data.constructor.name).to.equal('NativeImage');
  3929. expect(data.isEmpty()).to.be.false('data is empty');
  3930. done();
  3931. } catch (e) {
  3932. done(e);
  3933. } finally {
  3934. w.webContents.endFrameSubscription();
  3935. }
  3936. });
  3937. });
  3938. });
  3939. it('subscribes to frame updates (only dirty rectangle)', (done) => {
  3940. const w = new BrowserWindow({ show: false });
  3941. let called = false;
  3942. let gotInitialFullSizeFrame = false;
  3943. const [contentWidth, contentHeight] = w.getContentSize();
  3944. w.webContents.on('did-finish-load', () => {
  3945. w.webContents.beginFrameSubscription(true, (image, rect) => {
  3946. if (image.isEmpty()) {
  3947. // Chromium sometimes sends a 0x0 frame at the beginning of the
  3948. // page load.
  3949. return;
  3950. }
  3951. if (rect.height === contentHeight && rect.width === contentWidth &&
  3952. !gotInitialFullSizeFrame) {
  3953. // The initial frame is full-size, but we're looking for a call
  3954. // with just the dirty-rect. The next frame should be a smaller
  3955. // rect.
  3956. gotInitialFullSizeFrame = true;
  3957. return;
  3958. }
  3959. // This callback might be called twice.
  3960. if (called) return;
  3961. // We asked for just the dirty rectangle, so we expect to receive a
  3962. // rect smaller than the full size.
  3963. // TODO(jeremy): this is failing on windows currently; investigate.
  3964. // assert(rect.width < contentWidth || rect.height < contentHeight)
  3965. called = true;
  3966. try {
  3967. const expectedSize = rect.width * rect.height * 4;
  3968. expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
  3969. done();
  3970. } catch (e) {
  3971. done(e);
  3972. } finally {
  3973. w.webContents.endFrameSubscription();
  3974. }
  3975. });
  3976. });
  3977. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3978. });
  3979. it('throws error when subscriber is not well defined', () => {
  3980. const w = new BrowserWindow({ show: false });
  3981. expect(() => {
  3982. w.webContents.beginFrameSubscription(true, true as any);
  3983. // TODO(zcbenz): gin is weak at guessing parameter types, we should
  3984. // upstream native_mate's implementation to gin.
  3985. }).to.throw('Error processing argument at index 1, conversion failure from ');
  3986. });
  3987. });
  3988. describe('savePage method', () => {
  3989. const savePageDir = path.join(fixtures, 'save_page');
  3990. const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
  3991. const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
  3992. const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
  3993. afterEach(() => {
  3994. closeAllWindows();
  3995. try {
  3996. fs.unlinkSync(savePageCssPath);
  3997. fs.unlinkSync(savePageJsPath);
  3998. fs.unlinkSync(savePageHtmlPath);
  3999. fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
  4000. fs.rmdirSync(savePageDir);
  4001. } catch {}
  4002. });
  4003. it('should throw when passing relative paths', async () => {
  4004. const w = new BrowserWindow({ show: false });
  4005. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  4006. await expect(
  4007. w.webContents.savePage('save_page.html', 'HTMLComplete')
  4008. ).to.eventually.be.rejectedWith('Path must be absolute');
  4009. await expect(
  4010. w.webContents.savePage('save_page.html', 'HTMLOnly')
  4011. ).to.eventually.be.rejectedWith('Path must be absolute');
  4012. await expect(
  4013. w.webContents.savePage('save_page.html', 'MHTML')
  4014. ).to.eventually.be.rejectedWith('Path must be absolute');
  4015. });
  4016. it('should save page to disk with HTMLOnly', async () => {
  4017. const w = new BrowserWindow({ show: false });
  4018. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  4019. await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
  4020. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  4021. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  4022. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  4023. });
  4024. it('should save page to disk with MHTML', async () => {
  4025. /* Use temp directory for saving MHTML file since the write handle
  4026. * gets passed to untrusted process and chromium will deny exec access to
  4027. * the path. To perform this task, chromium requires that the path is one
  4028. * of the browser controlled paths, refs https://chromium-review.googlesource.com/c/chromium/src/+/3774416
  4029. */
  4030. const tmpDir = await fs.promises.mkdtemp(path.resolve(os.tmpdir(), 'electron-mhtml-save-'));
  4031. const savePageMHTMLPath = path.join(tmpDir, 'save_page.html');
  4032. const w = new BrowserWindow({ show: false });
  4033. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  4034. await w.webContents.savePage(savePageMHTMLPath, 'MHTML');
  4035. expect(fs.existsSync(savePageMHTMLPath)).to.be.true('html path');
  4036. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  4037. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  4038. try {
  4039. await fs.promises.unlink(savePageMHTMLPath);
  4040. await fs.promises.rmdir(tmpDir);
  4041. } catch {}
  4042. });
  4043. it('should save page to disk with HTMLComplete', async () => {
  4044. const w = new BrowserWindow({ show: false });
  4045. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  4046. await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
  4047. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  4048. expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
  4049. expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
  4050. });
  4051. });
  4052. describe('BrowserWindow options argument is optional', () => {
  4053. afterEach(closeAllWindows);
  4054. it('should create a window with default size (800x600)', () => {
  4055. const w = new BrowserWindow();
  4056. expect(w.getSize()).to.deep.equal([800, 600]);
  4057. });
  4058. });
  4059. describe('BrowserWindow.restore()', () => {
  4060. afterEach(closeAllWindows);
  4061. it('should restore the previous window size', () => {
  4062. const w = new BrowserWindow({
  4063. minWidth: 800,
  4064. width: 800
  4065. });
  4066. const initialSize = w.getSize();
  4067. w.minimize();
  4068. w.restore();
  4069. expectBoundsEqual(w.getSize(), initialSize);
  4070. });
  4071. it('does not crash when restoring hidden minimized window', () => {
  4072. const w = new BrowserWindow({});
  4073. w.minimize();
  4074. w.hide();
  4075. w.show();
  4076. });
  4077. // TODO(zcbenz):
  4078. // This test does not run on Linux CI. See:
  4079. // https://github.com/electron/electron/issues/28699
  4080. ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => {
  4081. const w = new BrowserWindow({});
  4082. const maximize = once(w, 'maximize');
  4083. w.maximize();
  4084. await maximize;
  4085. const minimize = once(w, 'minimize');
  4086. w.minimize();
  4087. await minimize;
  4088. expect(w.isMaximized()).to.equal(false);
  4089. const restore = once(w, 'restore');
  4090. w.restore();
  4091. await restore;
  4092. expect(w.isMaximized()).to.equal(true);
  4093. });
  4094. });
  4095. // TODO(dsanders11): Enable once maximize event works on Linux again on CI
  4096. ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
  4097. afterEach(closeAllWindows);
  4098. it('should show the window if it is not currently shown', async () => {
  4099. const w = new BrowserWindow({ show: false });
  4100. const hidden = once(w, 'hide');
  4101. let shown = once(w, 'show');
  4102. const maximize = once(w, 'maximize');
  4103. expect(w.isVisible()).to.be.false('visible');
  4104. w.maximize();
  4105. await maximize;
  4106. await shown;
  4107. expect(w.isMaximized()).to.be.true('maximized');
  4108. expect(w.isVisible()).to.be.true('visible');
  4109. // Even if the window is already maximized
  4110. w.hide();
  4111. await hidden;
  4112. expect(w.isVisible()).to.be.false('visible');
  4113. shown = once(w, 'show');
  4114. w.maximize();
  4115. await shown;
  4116. expect(w.isVisible()).to.be.true('visible');
  4117. });
  4118. });
  4119. describe('BrowserWindow.unmaximize()', () => {
  4120. afterEach(closeAllWindows);
  4121. it('should restore the previous window position', () => {
  4122. const w = new BrowserWindow();
  4123. const initialPosition = w.getPosition();
  4124. w.maximize();
  4125. w.unmaximize();
  4126. expectBoundsEqual(w.getPosition(), initialPosition);
  4127. });
  4128. // TODO(dsanders11): Enable once minimize event works on Linux again.
  4129. // See https://github.com/electron/electron/issues/28699
  4130. ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
  4131. const w = new BrowserWindow();
  4132. const minimize = once(w, 'minimize');
  4133. w.minimize();
  4134. await minimize;
  4135. w.unmaximize();
  4136. await setTimeout(1000);
  4137. expect(w.isMinimized()).to.be.true();
  4138. });
  4139. it('should not change the size or position of a normal window', async () => {
  4140. const w = new BrowserWindow();
  4141. const initialSize = w.getSize();
  4142. const initialPosition = w.getPosition();
  4143. w.unmaximize();
  4144. await setTimeout(1000);
  4145. expectBoundsEqual(w.getSize(), initialSize);
  4146. expectBoundsEqual(w.getPosition(), initialPosition);
  4147. });
  4148. ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
  4149. const { workArea } = screen.getPrimaryDisplay();
  4150. const bounds = {
  4151. x: workArea.x,
  4152. y: workArea.y,
  4153. width: workArea.width,
  4154. height: workArea.height
  4155. };
  4156. const w = new BrowserWindow(bounds);
  4157. w.unmaximize();
  4158. await setTimeout(1000);
  4159. expectBoundsEqual(w.getBounds(), bounds);
  4160. });
  4161. });
  4162. describe('setFullScreen(false)', () => {
  4163. afterEach(closeAllWindows);
  4164. // only applicable to windows: https://github.com/electron/electron/issues/6036
  4165. ifdescribe(process.platform === 'win32')('on windows', () => {
  4166. it('should restore a normal visible window from a fullscreen startup state', async () => {
  4167. const w = new BrowserWindow({ show: false });
  4168. await w.loadURL('about:blank');
  4169. const shown = once(w, 'show');
  4170. // start fullscreen and hidden
  4171. w.setFullScreen(true);
  4172. w.show();
  4173. await shown;
  4174. const leftFullScreen = once(w, 'leave-full-screen');
  4175. w.setFullScreen(false);
  4176. await leftFullScreen;
  4177. expect(w.isVisible()).to.be.true('visible');
  4178. expect(w.isFullScreen()).to.be.false('fullscreen');
  4179. });
  4180. it('should keep window hidden if already in hidden state', async () => {
  4181. const w = new BrowserWindow({ show: false });
  4182. await w.loadURL('about:blank');
  4183. const leftFullScreen = once(w, 'leave-full-screen');
  4184. w.setFullScreen(false);
  4185. await leftFullScreen;
  4186. expect(w.isVisible()).to.be.false('visible');
  4187. expect(w.isFullScreen()).to.be.false('fullscreen');
  4188. });
  4189. });
  4190. ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
  4191. it('exits HTML fullscreen when window leaves fullscreen', async () => {
  4192. const w = new BrowserWindow();
  4193. await w.loadURL('about:blank');
  4194. await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  4195. await once(w, 'enter-full-screen');
  4196. // Wait a tick for the full-screen state to 'stick'
  4197. await setTimeout();
  4198. w.setFullScreen(false);
  4199. await once(w, 'leave-html-full-screen');
  4200. });
  4201. });
  4202. });
  4203. describe('parent window', () => {
  4204. afterEach(closeAllWindows);
  4205. ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
  4206. const w = new BrowserWindow();
  4207. const sheetBegin = once(w, 'sheet-begin');
  4208. // eslint-disable-next-line no-new
  4209. new BrowserWindow({
  4210. modal: true,
  4211. parent: w
  4212. });
  4213. await sheetBegin;
  4214. });
  4215. ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
  4216. const w = new BrowserWindow();
  4217. const sheet = new BrowserWindow({
  4218. modal: true,
  4219. parent: w
  4220. });
  4221. const sheetEnd = once(w, 'sheet-end');
  4222. sheet.close();
  4223. await sheetEnd;
  4224. });
  4225. describe('parent option', () => {
  4226. it('sets parent window', () => {
  4227. const w = new BrowserWindow({ show: false });
  4228. const c = new BrowserWindow({ show: false, parent: w });
  4229. expect(c.getParentWindow()).to.equal(w);
  4230. });
  4231. it('adds window to child windows of parent', () => {
  4232. const w = new BrowserWindow({ show: false });
  4233. const c = new BrowserWindow({ show: false, parent: w });
  4234. expect(w.getChildWindows()).to.deep.equal([c]);
  4235. });
  4236. it('removes from child windows of parent when window is closed', async () => {
  4237. const w = new BrowserWindow({ show: false });
  4238. const c = new BrowserWindow({ show: false, parent: w });
  4239. const closed = once(c, 'closed');
  4240. c.close();
  4241. await closed;
  4242. // The child window list is not immediately cleared, so wait a tick until it's ready.
  4243. await setTimeout();
  4244. expect(w.getChildWindows().length).to.equal(0);
  4245. });
  4246. it('can handle child window close and reparent multiple times', async () => {
  4247. const w = new BrowserWindow({ show: false });
  4248. let c: BrowserWindow | null;
  4249. for (let i = 0; i < 5; i++) {
  4250. c = new BrowserWindow({ show: false, parent: w });
  4251. const closed = once(c, 'closed');
  4252. c.close();
  4253. await closed;
  4254. }
  4255. await setTimeout();
  4256. expect(w.getChildWindows().length).to.equal(0);
  4257. });
  4258. ifit(process.platform === 'darwin')('only shows the intended window when a child with siblings is shown', async () => {
  4259. const w = new BrowserWindow({ show: false });
  4260. const childOne = new BrowserWindow({ show: false, parent: w });
  4261. const childTwo = new BrowserWindow({ show: false, parent: w });
  4262. const parentShown = once(w, 'show');
  4263. w.show();
  4264. await parentShown;
  4265. expect(childOne.isVisible()).to.be.false('childOne is visible');
  4266. expect(childTwo.isVisible()).to.be.false('childTwo is visible');
  4267. const childOneShown = once(childOne, 'show');
  4268. childOne.show();
  4269. await childOneShown;
  4270. expect(childOne.isVisible()).to.be.true('childOne is not visible');
  4271. expect(childTwo.isVisible()).to.be.false('childTwo is visible');
  4272. });
  4273. ifit(process.platform === 'darwin')('child matches parent visibility when parent visibility changes', async () => {
  4274. const w = new BrowserWindow({ show: false });
  4275. const c = new BrowserWindow({ show: false, parent: w });
  4276. const wShow = once(w, 'show');
  4277. const cShow = once(c, 'show');
  4278. w.show();
  4279. c.show();
  4280. await Promise.all([wShow, cShow]);
  4281. const minimized = once(w, 'minimize');
  4282. w.minimize();
  4283. await minimized;
  4284. expect(w.isVisible()).to.be.false('parent is visible');
  4285. expect(c.isVisible()).to.be.false('child is visible');
  4286. const restored = once(w, 'restore');
  4287. w.restore();
  4288. await restored;
  4289. expect(w.isVisible()).to.be.true('parent is visible');
  4290. expect(c.isVisible()).to.be.true('child is visible');
  4291. });
  4292. ifit(process.platform === 'darwin')('parent matches child visibility when child visibility changes', async () => {
  4293. const w = new BrowserWindow({ show: false });
  4294. const c = new BrowserWindow({ show: false, parent: w });
  4295. const wShow = once(w, 'show');
  4296. const cShow = once(c, 'show');
  4297. w.show();
  4298. c.show();
  4299. await Promise.all([wShow, cShow]);
  4300. const minimized = once(c, 'minimize');
  4301. c.minimize();
  4302. await minimized;
  4303. expect(c.isVisible()).to.be.false('child is visible');
  4304. const restored = once(c, 'restore');
  4305. c.restore();
  4306. await restored;
  4307. expect(w.isVisible()).to.be.true('parent is visible');
  4308. expect(c.isVisible()).to.be.true('child is visible');
  4309. });
  4310. it('closes a grandchild window when a middle child window is destroyed', async () => {
  4311. const w = new BrowserWindow();
  4312. w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
  4313. w.webContents.executeJavaScript('window.open("")');
  4314. w.webContents.on('did-create-window', async (window) => {
  4315. const childWindow = new BrowserWindow({ parent: window });
  4316. await setTimeout();
  4317. const closed = once(childWindow, 'closed');
  4318. window.close();
  4319. await closed;
  4320. expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
  4321. });
  4322. });
  4323. it('should not affect the show option', () => {
  4324. const w = new BrowserWindow({ show: false });
  4325. const c = new BrowserWindow({ show: false, parent: w });
  4326. expect(c.isVisible()).to.be.false('child is visible');
  4327. expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
  4328. });
  4329. });
  4330. describe('win.setParentWindow(parent)', () => {
  4331. it('sets parent window', () => {
  4332. const w = new BrowserWindow({ show: false });
  4333. const c = new BrowserWindow({ show: false });
  4334. expect(w.getParentWindow()).to.be.null('w.parent');
  4335. expect(c.getParentWindow()).to.be.null('c.parent');
  4336. c.setParentWindow(w);
  4337. expect(c.getParentWindow()).to.equal(w);
  4338. c.setParentWindow(null);
  4339. expect(c.getParentWindow()).to.be.null('c.parent');
  4340. });
  4341. it('adds window to child windows of parent', () => {
  4342. const w = new BrowserWindow({ show: false });
  4343. const c = new BrowserWindow({ show: false });
  4344. expect(w.getChildWindows()).to.deep.equal([]);
  4345. c.setParentWindow(w);
  4346. expect(w.getChildWindows()).to.deep.equal([c]);
  4347. c.setParentWindow(null);
  4348. expect(w.getChildWindows()).to.deep.equal([]);
  4349. });
  4350. it('removes from child windows of parent when window is closed', async () => {
  4351. const w = new BrowserWindow({ show: false });
  4352. const c = new BrowserWindow({ show: false });
  4353. const closed = once(c, 'closed');
  4354. c.setParentWindow(w);
  4355. c.close();
  4356. await closed;
  4357. // The child window list is not immediately cleared, so wait a tick until it's ready.
  4358. await setTimeout();
  4359. expect(w.getChildWindows().length).to.equal(0);
  4360. });
  4361. ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => {
  4362. const w1 = new BrowserWindow({ show: false });
  4363. const w2 = new BrowserWindow({ show: false });
  4364. const c = new BrowserWindow({ show: false });
  4365. c.setParentWindow(w1);
  4366. expect(w1.getChildWindows().length).to.equal(1);
  4367. const closed = once(w1, 'closed');
  4368. w1.destroy();
  4369. await closed;
  4370. c.setParentWindow(w2);
  4371. await setTimeout();
  4372. const children = w2.getChildWindows();
  4373. expect(children[0]).to.equal(c);
  4374. });
  4375. });
  4376. describe('modal option', () => {
  4377. it('does not freeze or crash', async () => {
  4378. const parentWindow = new BrowserWindow();
  4379. const createTwo = async () => {
  4380. const two = new BrowserWindow({
  4381. width: 300,
  4382. height: 200,
  4383. parent: parentWindow,
  4384. modal: true,
  4385. show: false
  4386. });
  4387. const twoShown = once(two, 'show');
  4388. two.show();
  4389. await twoShown;
  4390. setTimeout(500).then(() => two.close());
  4391. await once(two, 'closed');
  4392. };
  4393. const one = new BrowserWindow({
  4394. width: 600,
  4395. height: 400,
  4396. parent: parentWindow,
  4397. modal: true,
  4398. show: false
  4399. });
  4400. const oneShown = once(one, 'show');
  4401. one.show();
  4402. await oneShown;
  4403. setTimeout(500).then(() => one.destroy());
  4404. await once(one, 'closed');
  4405. await createTwo();
  4406. });
  4407. ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
  4408. const w = new BrowserWindow({ show: false });
  4409. w.setEnabled(false);
  4410. expect(w.isEnabled()).to.be.false('w.isEnabled()');
  4411. w.setEnabled(true);
  4412. expect(w.isEnabled()).to.be.true('!w.isEnabled()');
  4413. });
  4414. ifit(process.platform !== 'darwin')('disables parent window', () => {
  4415. const w = new BrowserWindow({ show: false });
  4416. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  4417. expect(w.isEnabled()).to.be.true('w.isEnabled');
  4418. c.show();
  4419. expect(w.isEnabled()).to.be.false('w.isEnabled');
  4420. });
  4421. ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
  4422. const w = new BrowserWindow({ show: false });
  4423. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  4424. const closed = once(c, 'closed');
  4425. c.show();
  4426. c.close();
  4427. await closed;
  4428. expect(w.isEnabled()).to.be.true('w.isEnabled');
  4429. });
  4430. ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
  4431. const w = new BrowserWindow({ show: false });
  4432. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  4433. const closed = once(c, 'closed');
  4434. w.setEnabled(false);
  4435. c.show();
  4436. c.close();
  4437. await closed;
  4438. expect(w.isEnabled()).to.be.false('w.isEnabled');
  4439. });
  4440. ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
  4441. const w = new BrowserWindow({ show: false });
  4442. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  4443. const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
  4444. c.show();
  4445. expect(w.isEnabled()).to.be.false('w.isEnabled');
  4446. c2.show();
  4447. expect(w.isEnabled()).to.be.false('w.isEnabled');
  4448. c.destroy();
  4449. expect(w.isEnabled()).to.be.false('w.isEnabled');
  4450. c2.destroy();
  4451. expect(w.isEnabled()).to.be.true('w.isEnabled');
  4452. });
  4453. });
  4454. });
  4455. describe('window states', () => {
  4456. afterEach(closeAllWindows);
  4457. it('does not resize frameless windows when states change', () => {
  4458. const w = new BrowserWindow({
  4459. frame: false,
  4460. width: 300,
  4461. height: 200,
  4462. show: false
  4463. });
  4464. w.minimizable = false;
  4465. w.minimizable = true;
  4466. expect(w.getSize()).to.deep.equal([300, 200]);
  4467. w.resizable = false;
  4468. w.resizable = true;
  4469. expect(w.getSize()).to.deep.equal([300, 200]);
  4470. w.maximizable = false;
  4471. w.maximizable = true;
  4472. expect(w.getSize()).to.deep.equal([300, 200]);
  4473. w.fullScreenable = false;
  4474. w.fullScreenable = true;
  4475. expect(w.getSize()).to.deep.equal([300, 200]);
  4476. w.closable = false;
  4477. w.closable = true;
  4478. expect(w.getSize()).to.deep.equal([300, 200]);
  4479. });
  4480. describe('resizable state', () => {
  4481. it('with properties', () => {
  4482. it('can be set with resizable constructor option', () => {
  4483. const w = new BrowserWindow({ show: false, resizable: false });
  4484. expect(w.resizable).to.be.false('resizable');
  4485. if (process.platform === 'darwin') {
  4486. expect(w.maximizable).to.to.true('maximizable');
  4487. }
  4488. });
  4489. it('can be changed', () => {
  4490. const w = new BrowserWindow({ show: false });
  4491. expect(w.resizable).to.be.true('resizable');
  4492. w.resizable = false;
  4493. expect(w.resizable).to.be.false('resizable');
  4494. w.resizable = true;
  4495. expect(w.resizable).to.be.true('resizable');
  4496. });
  4497. });
  4498. it('with functions', () => {
  4499. it('can be set with resizable constructor option', () => {
  4500. const w = new BrowserWindow({ show: false, resizable: false });
  4501. expect(w.isResizable()).to.be.false('resizable');
  4502. if (process.platform === 'darwin') {
  4503. expect(w.isMaximizable()).to.to.true('maximizable');
  4504. }
  4505. });
  4506. it('can be changed', () => {
  4507. const w = new BrowserWindow({ show: false });
  4508. expect(w.isResizable()).to.be.true('resizable');
  4509. w.setResizable(false);
  4510. expect(w.isResizable()).to.be.false('resizable');
  4511. w.setResizable(true);
  4512. expect(w.isResizable()).to.be.true('resizable');
  4513. });
  4514. });
  4515. it('works for a frameless window', () => {
  4516. const w = new BrowserWindow({ show: false, frame: false });
  4517. expect(w.resizable).to.be.true('resizable');
  4518. if (process.platform === 'win32') {
  4519. const w = new BrowserWindow({ show: false, thickFrame: false });
  4520. expect(w.resizable).to.be.false('resizable');
  4521. }
  4522. });
  4523. // On Linux there is no "resizable" property of a window.
  4524. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
  4525. const w = new BrowserWindow({ show: false });
  4526. expect(w.resizable).to.be.true('resizable');
  4527. expect(w.maximizable).to.be.true('maximizable');
  4528. w.resizable = false;
  4529. expect(w.maximizable).to.be.false('not maximizable');
  4530. w.resizable = true;
  4531. expect(w.maximizable).to.be.true('maximizable');
  4532. });
  4533. ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
  4534. const w = new BrowserWindow({
  4535. show: false,
  4536. frame: false,
  4537. resizable: false,
  4538. transparent: true
  4539. });
  4540. w.setContentSize(60, 60);
  4541. expectBoundsEqual(w.getContentSize(), [60, 60]);
  4542. w.setContentSize(30, 30);
  4543. expectBoundsEqual(w.getContentSize(), [30, 30]);
  4544. w.setContentSize(10, 10);
  4545. expectBoundsEqual(w.getContentSize(), [10, 10]);
  4546. });
  4547. ifit(process.platform === 'win32')('do not change window with frame bounds when maximized', () => {
  4548. const w = new BrowserWindow({
  4549. show: true,
  4550. frame: true,
  4551. thickFrame: true
  4552. });
  4553. expect(w.isResizable()).to.be.true('resizable');
  4554. w.maximize();
  4555. expect(w.isMaximized()).to.be.true('maximized');
  4556. const bounds = w.getBounds();
  4557. w.setResizable(false);
  4558. expectBoundsEqual(w.getBounds(), bounds);
  4559. w.setResizable(true);
  4560. expectBoundsEqual(w.getBounds(), bounds);
  4561. });
  4562. ifit(process.platform === 'win32')('do not change window without frame bounds when maximized', () => {
  4563. const w = new BrowserWindow({
  4564. show: true,
  4565. frame: false,
  4566. thickFrame: true
  4567. });
  4568. expect(w.isResizable()).to.be.true('resizable');
  4569. w.maximize();
  4570. expect(w.isMaximized()).to.be.true('maximized');
  4571. const bounds = w.getBounds();
  4572. w.setResizable(false);
  4573. expectBoundsEqual(w.getBounds(), bounds);
  4574. w.setResizable(true);
  4575. expectBoundsEqual(w.getBounds(), bounds);
  4576. });
  4577. ifit(process.platform === 'win32')('do not change window transparent without frame bounds when maximized', () => {
  4578. const w = new BrowserWindow({
  4579. show: true,
  4580. frame: false,
  4581. thickFrame: true,
  4582. transparent: true
  4583. });
  4584. expect(w.isResizable()).to.be.true('resizable');
  4585. w.maximize();
  4586. expect(w.isMaximized()).to.be.true('maximized');
  4587. const bounds = w.getBounds();
  4588. w.setResizable(false);
  4589. expectBoundsEqual(w.getBounds(), bounds);
  4590. w.setResizable(true);
  4591. expectBoundsEqual(w.getBounds(), bounds);
  4592. });
  4593. });
  4594. describe('loading main frame state', () => {
  4595. let server: http.Server;
  4596. let serverUrl: string;
  4597. before(async () => {
  4598. server = http.createServer((request, response) => {
  4599. response.end();
  4600. });
  4601. serverUrl = (await listen(server)).url;
  4602. });
  4603. after(() => {
  4604. server.close();
  4605. });
  4606. it('is true when the main frame is loading', async () => {
  4607. const w = new BrowserWindow({ show: false });
  4608. const didStartLoading = once(w.webContents, 'did-start-loading');
  4609. w.webContents.loadURL(serverUrl);
  4610. await didStartLoading;
  4611. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  4612. });
  4613. it('is false when only a subframe is loading', async () => {
  4614. const w = new BrowserWindow({ show: false });
  4615. const didStopLoading = once(w.webContents, 'did-stop-loading');
  4616. w.webContents.loadURL(serverUrl);
  4617. await didStopLoading;
  4618. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  4619. const didStartLoading = once(w.webContents, 'did-start-loading');
  4620. w.webContents.executeJavaScript(`
  4621. var iframe = document.createElement('iframe')
  4622. iframe.src = '${serverUrl}/page2'
  4623. document.body.appendChild(iframe)
  4624. `);
  4625. await didStartLoading;
  4626. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  4627. });
  4628. it('is true when navigating to pages from the same origin', async () => {
  4629. const w = new BrowserWindow({ show: false });
  4630. const didStopLoading = once(w.webContents, 'did-stop-loading');
  4631. w.webContents.loadURL(serverUrl);
  4632. await didStopLoading;
  4633. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  4634. const didStartLoading = once(w.webContents, 'did-start-loading');
  4635. w.webContents.loadURL(`${serverUrl}/page2`);
  4636. await didStartLoading;
  4637. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  4638. });
  4639. });
  4640. });
  4641. ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
  4642. // Not implemented on Linux.
  4643. afterEach(closeAllWindows);
  4644. describe('movable state', () => {
  4645. it('with properties', () => {
  4646. it('can be set with movable constructor option', () => {
  4647. const w = new BrowserWindow({ show: false, movable: false });
  4648. expect(w.movable).to.be.false('movable');
  4649. });
  4650. it('can be changed', () => {
  4651. const w = new BrowserWindow({ show: false });
  4652. expect(w.movable).to.be.true('movable');
  4653. w.movable = false;
  4654. expect(w.movable).to.be.false('movable');
  4655. w.movable = true;
  4656. expect(w.movable).to.be.true('movable');
  4657. });
  4658. });
  4659. it('with functions', () => {
  4660. it('can be set with movable constructor option', () => {
  4661. const w = new BrowserWindow({ show: false, movable: false });
  4662. expect(w.isMovable()).to.be.false('movable');
  4663. });
  4664. it('can be changed', () => {
  4665. const w = new BrowserWindow({ show: false });
  4666. expect(w.isMovable()).to.be.true('movable');
  4667. w.setMovable(false);
  4668. expect(w.isMovable()).to.be.false('movable');
  4669. w.setMovable(true);
  4670. expect(w.isMovable()).to.be.true('movable');
  4671. });
  4672. });
  4673. });
  4674. describe('visibleOnAllWorkspaces state', () => {
  4675. it('with properties', () => {
  4676. it('can be changed', () => {
  4677. const w = new BrowserWindow({ show: false });
  4678. expect(w.visibleOnAllWorkspaces).to.be.false();
  4679. w.visibleOnAllWorkspaces = true;
  4680. expect(w.visibleOnAllWorkspaces).to.be.true();
  4681. });
  4682. });
  4683. it('with functions', () => {
  4684. it('can be changed', () => {
  4685. const w = new BrowserWindow({ show: false });
  4686. expect(w.isVisibleOnAllWorkspaces()).to.be.false();
  4687. w.setVisibleOnAllWorkspaces(true);
  4688. expect(w.isVisibleOnAllWorkspaces()).to.be.true();
  4689. });
  4690. });
  4691. });
  4692. ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
  4693. it('with properties', () => {
  4694. it('can be changed', () => {
  4695. const w = new BrowserWindow({ show: false });
  4696. expect(w.documentEdited).to.be.false();
  4697. w.documentEdited = true;
  4698. expect(w.documentEdited).to.be.true();
  4699. });
  4700. });
  4701. it('with functions', () => {
  4702. it('can be changed', () => {
  4703. const w = new BrowserWindow({ show: false });
  4704. expect(w.isDocumentEdited()).to.be.false();
  4705. w.setDocumentEdited(true);
  4706. expect(w.isDocumentEdited()).to.be.true();
  4707. });
  4708. });
  4709. });
  4710. ifdescribe(process.platform === 'darwin')('representedFilename', () => {
  4711. it('with properties', () => {
  4712. it('can be changed', () => {
  4713. const w = new BrowserWindow({ show: false });
  4714. expect(w.representedFilename).to.eql('');
  4715. w.representedFilename = 'a name';
  4716. expect(w.representedFilename).to.eql('a name');
  4717. });
  4718. });
  4719. it('with functions', () => {
  4720. it('can be changed', () => {
  4721. const w = new BrowserWindow({ show: false });
  4722. expect(w.getRepresentedFilename()).to.eql('');
  4723. w.setRepresentedFilename('a name');
  4724. expect(w.getRepresentedFilename()).to.eql('a name');
  4725. });
  4726. });
  4727. });
  4728. describe('native window title', () => {
  4729. it('with properties', () => {
  4730. it('can be set with title constructor option', () => {
  4731. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  4732. expect(w.title).to.eql('mYtItLe');
  4733. });
  4734. it('can be changed', () => {
  4735. const w = new BrowserWindow({ show: false });
  4736. expect(w.title).to.eql('Electron Test Main');
  4737. w.title = 'NEW TITLE';
  4738. expect(w.title).to.eql('NEW TITLE');
  4739. });
  4740. });
  4741. it('with functions', () => {
  4742. it('can be set with minimizable constructor option', () => {
  4743. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  4744. expect(w.getTitle()).to.eql('mYtItLe');
  4745. });
  4746. it('can be changed', () => {
  4747. const w = new BrowserWindow({ show: false });
  4748. expect(w.getTitle()).to.eql('Electron Test Main');
  4749. w.setTitle('NEW TITLE');
  4750. expect(w.getTitle()).to.eql('NEW TITLE');
  4751. });
  4752. });
  4753. });
  4754. describe('minimizable state', () => {
  4755. it('with properties', () => {
  4756. it('can be set with minimizable constructor option', () => {
  4757. const w = new BrowserWindow({ show: false, minimizable: false });
  4758. expect(w.minimizable).to.be.false('minimizable');
  4759. });
  4760. it('can be changed', () => {
  4761. const w = new BrowserWindow({ show: false });
  4762. expect(w.minimizable).to.be.true('minimizable');
  4763. w.minimizable = false;
  4764. expect(w.minimizable).to.be.false('minimizable');
  4765. w.minimizable = true;
  4766. expect(w.minimizable).to.be.true('minimizable');
  4767. });
  4768. });
  4769. it('with functions', () => {
  4770. it('can be set with minimizable constructor option', () => {
  4771. const w = new BrowserWindow({ show: false, minimizable: false });
  4772. expect(w.isMinimizable()).to.be.false('movable');
  4773. });
  4774. it('can be changed', () => {
  4775. const w = new BrowserWindow({ show: false });
  4776. expect(w.isMinimizable()).to.be.true('isMinimizable');
  4777. w.setMinimizable(false);
  4778. expect(w.isMinimizable()).to.be.false('isMinimizable');
  4779. w.setMinimizable(true);
  4780. expect(w.isMinimizable()).to.be.true('isMinimizable');
  4781. });
  4782. });
  4783. });
  4784. describe('maximizable state (property)', () => {
  4785. it('with properties', () => {
  4786. it('can be set with maximizable constructor option', () => {
  4787. const w = new BrowserWindow({ show: false, maximizable: false });
  4788. expect(w.maximizable).to.be.false('maximizable');
  4789. });
  4790. it('can be changed', () => {
  4791. const w = new BrowserWindow({ show: false });
  4792. expect(w.maximizable).to.be.true('maximizable');
  4793. w.maximizable = false;
  4794. expect(w.maximizable).to.be.false('maximizable');
  4795. w.maximizable = true;
  4796. expect(w.maximizable).to.be.true('maximizable');
  4797. });
  4798. it('is not affected when changing other states', () => {
  4799. const w = new BrowserWindow({ show: false });
  4800. w.maximizable = false;
  4801. expect(w.maximizable).to.be.false('maximizable');
  4802. w.minimizable = false;
  4803. expect(w.maximizable).to.be.false('maximizable');
  4804. w.closable = false;
  4805. expect(w.maximizable).to.be.false('maximizable');
  4806. w.maximizable = true;
  4807. expect(w.maximizable).to.be.true('maximizable');
  4808. w.closable = true;
  4809. expect(w.maximizable).to.be.true('maximizable');
  4810. w.fullScreenable = false;
  4811. expect(w.maximizable).to.be.true('maximizable');
  4812. });
  4813. });
  4814. it('with functions', () => {
  4815. it('can be set with maximizable constructor option', () => {
  4816. const w = new BrowserWindow({ show: false, maximizable: false });
  4817. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4818. });
  4819. it('can be changed', () => {
  4820. const w = new BrowserWindow({ show: false });
  4821. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4822. w.setMaximizable(false);
  4823. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4824. w.setMaximizable(true);
  4825. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4826. });
  4827. it('is not affected when changing other states', () => {
  4828. const w = new BrowserWindow({ show: false });
  4829. w.setMaximizable(false);
  4830. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4831. w.setMinimizable(false);
  4832. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4833. w.setClosable(false);
  4834. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4835. w.setMaximizable(true);
  4836. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4837. w.setClosable(true);
  4838. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4839. w.setFullScreenable(false);
  4840. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4841. });
  4842. });
  4843. });
  4844. ifdescribe(process.platform === 'win32')('maximizable state', () => {
  4845. it('with properties', () => {
  4846. it('is reset to its former state', () => {
  4847. const w = new BrowserWindow({ show: false });
  4848. w.maximizable = false;
  4849. w.resizable = false;
  4850. w.resizable = true;
  4851. expect(w.maximizable).to.be.false('maximizable');
  4852. w.maximizable = true;
  4853. w.resizable = false;
  4854. w.resizable = true;
  4855. expect(w.maximizable).to.be.true('maximizable');
  4856. });
  4857. });
  4858. it('with functions', () => {
  4859. it('is reset to its former state', () => {
  4860. const w = new BrowserWindow({ show: false });
  4861. w.setMaximizable(false);
  4862. w.setResizable(false);
  4863. w.setResizable(true);
  4864. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4865. w.setMaximizable(true);
  4866. w.setResizable(false);
  4867. w.setResizable(true);
  4868. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4869. });
  4870. });
  4871. });
  4872. ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
  4873. describe('with properties', () => {
  4874. it('can be changed', () => {
  4875. const w = new BrowserWindow({ show: false });
  4876. expect(w.menuBarVisible).to.be.true();
  4877. w.menuBarVisible = false;
  4878. expect(w.menuBarVisible).to.be.false();
  4879. w.menuBarVisible = true;
  4880. expect(w.menuBarVisible).to.be.true();
  4881. });
  4882. });
  4883. describe('with functions', () => {
  4884. it('can be changed', () => {
  4885. const w = new BrowserWindow({ show: false });
  4886. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4887. w.setMenuBarVisibility(false);
  4888. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4889. w.setMenuBarVisibility(true);
  4890. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4891. });
  4892. });
  4893. });
  4894. ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => {
  4895. it('correctly remembers state prior to fullscreen change', async () => {
  4896. const w = new BrowserWindow({ show: false });
  4897. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4898. w.setMenuBarVisibility(false);
  4899. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4900. const enterFS = once(w, 'enter-full-screen');
  4901. w.setFullScreen(true);
  4902. await enterFS;
  4903. expect(w.fullScreen).to.be.true('not fullscreen');
  4904. const exitFS = once(w, 'leave-full-screen');
  4905. w.setFullScreen(false);
  4906. await exitFS;
  4907. expect(w.fullScreen).to.be.false('not fullscreen');
  4908. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4909. });
  4910. it('correctly remembers state prior to fullscreen change with autoHide', async () => {
  4911. const w = new BrowserWindow({ show: false });
  4912. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  4913. w.autoHideMenuBar = true;
  4914. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  4915. w.setMenuBarVisibility(false);
  4916. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4917. const enterFS = once(w, 'enter-full-screen');
  4918. w.setFullScreen(true);
  4919. await enterFS;
  4920. expect(w.fullScreen).to.be.true('not fullscreen');
  4921. const exitFS = once(w, 'leave-full-screen');
  4922. w.setFullScreen(false);
  4923. await exitFS;
  4924. expect(w.fullScreen).to.be.false('not fullscreen');
  4925. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4926. });
  4927. });
  4928. ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
  4929. it('with functions', () => {
  4930. it('can be set with fullscreenable constructor option', () => {
  4931. const w = new BrowserWindow({ show: false, fullscreenable: false });
  4932. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4933. });
  4934. it('can be changed', () => {
  4935. const w = new BrowserWindow({ show: false });
  4936. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4937. w.setFullScreenable(false);
  4938. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4939. w.setFullScreenable(true);
  4940. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4941. });
  4942. });
  4943. it('does not open non-fullscreenable child windows in fullscreen if parent is fullscreen', async () => {
  4944. const w = new BrowserWindow();
  4945. const enterFS = once(w, 'enter-full-screen');
  4946. w.setFullScreen(true);
  4947. await enterFS;
  4948. const child = new BrowserWindow({ parent: w, resizable: false, fullscreenable: false });
  4949. const shown = once(child, 'show');
  4950. await shown;
  4951. expect(child.resizable).to.be.false('resizable');
  4952. expect(child.fullScreen).to.be.false('fullscreen');
  4953. expect(child.fullScreenable).to.be.false('fullscreenable');
  4954. });
  4955. it('is set correctly with different resizable values', async () => {
  4956. const w1 = new BrowserWindow({
  4957. resizable: false,
  4958. fullscreenable: false
  4959. });
  4960. const w2 = new BrowserWindow({
  4961. resizable: true,
  4962. fullscreenable: false
  4963. });
  4964. const w3 = new BrowserWindow({
  4965. fullscreenable: false
  4966. });
  4967. expect(w1.isFullScreenable()).to.be.false('isFullScreenable');
  4968. expect(w2.isFullScreenable()).to.be.false('isFullScreenable');
  4969. expect(w3.isFullScreenable()).to.be.false('isFullScreenable');
  4970. });
  4971. it('does not disable maximize button if window is resizable', () => {
  4972. const w = new BrowserWindow({
  4973. resizable: true,
  4974. fullscreenable: false
  4975. });
  4976. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4977. w.setResizable(false);
  4978. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4979. });
  4980. });
  4981. ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => {
  4982. it('with functions', () => {
  4983. it('can be set with ignoreMissionControl constructor option', () => {
  4984. const w = new BrowserWindow({ show: false, hiddenInMissionControl: true });
  4985. expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
  4986. });
  4987. it('can be changed', () => {
  4988. const w = new BrowserWindow({ show: false });
  4989. expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
  4990. w.setHiddenInMissionControl(true);
  4991. expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
  4992. w.setHiddenInMissionControl(false);
  4993. expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
  4994. });
  4995. });
  4996. });
  4997. // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
  4998. ifdescribe(process.platform === 'darwin')('kiosk state', () => {
  4999. it('with properties', () => {
  5000. it('can be set with a constructor property', () => {
  5001. const w = new BrowserWindow({ kiosk: true });
  5002. expect(w.kiosk).to.be.true();
  5003. });
  5004. it('can be changed ', async () => {
  5005. const w = new BrowserWindow();
  5006. const enterFullScreen = once(w, 'enter-full-screen');
  5007. w.kiosk = true;
  5008. expect(w.isKiosk()).to.be.true('isKiosk');
  5009. await enterFullScreen;
  5010. await setTimeout();
  5011. const leaveFullScreen = once(w, 'leave-full-screen');
  5012. w.kiosk = false;
  5013. expect(w.isKiosk()).to.be.false('isKiosk');
  5014. await leaveFullScreen;
  5015. });
  5016. });
  5017. it('with functions', () => {
  5018. it('can be set with a constructor property', () => {
  5019. const w = new BrowserWindow({ kiosk: true });
  5020. expect(w.isKiosk()).to.be.true();
  5021. });
  5022. it('can be changed ', async () => {
  5023. const w = new BrowserWindow();
  5024. const enterFullScreen = once(w, 'enter-full-screen');
  5025. w.setKiosk(true);
  5026. expect(w.isKiosk()).to.be.true('isKiosk');
  5027. await enterFullScreen;
  5028. await setTimeout();
  5029. const leaveFullScreen = once(w, 'leave-full-screen');
  5030. w.setKiosk(false);
  5031. expect(w.isKiosk()).to.be.false('isKiosk');
  5032. await leaveFullScreen;
  5033. });
  5034. });
  5035. });
  5036. ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
  5037. it('resizable flag should be set to false and restored', async () => {
  5038. const w = new BrowserWindow({ resizable: false });
  5039. const enterFullScreen = once(w, 'enter-full-screen');
  5040. w.setFullScreen(true);
  5041. await enterFullScreen;
  5042. expect(w.resizable).to.be.false('resizable');
  5043. await setTimeout();
  5044. const leaveFullScreen = once(w, 'leave-full-screen');
  5045. w.setFullScreen(false);
  5046. await leaveFullScreen;
  5047. expect(w.resizable).to.be.false('resizable');
  5048. });
  5049. it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
  5050. const w = new BrowserWindow();
  5051. const enterFullScreen = once(w, 'enter-full-screen');
  5052. w.setFullScreen(true);
  5053. await enterFullScreen;
  5054. expect(w.resizable).to.be.false('resizable');
  5055. await setTimeout();
  5056. const leaveFullScreen = once(w, 'leave-full-screen');
  5057. w.setFullScreen(false);
  5058. await leaveFullScreen;
  5059. expect(w.resizable).to.be.true('resizable');
  5060. });
  5061. });
  5062. ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
  5063. it('should not cause a crash if called when exiting fullscreen', async () => {
  5064. const w = new BrowserWindow();
  5065. const enterFullScreen = once(w, 'enter-full-screen');
  5066. w.setFullScreen(true);
  5067. await enterFullScreen;
  5068. await setTimeout();
  5069. const leaveFullScreen = once(w, 'leave-full-screen');
  5070. w.setFullScreen(false);
  5071. await leaveFullScreen;
  5072. });
  5073. it('should be able to load a URL while transitioning to fullscreen', async () => {
  5074. const w = new BrowserWindow({ fullscreen: true });
  5075. w.loadFile(path.join(fixtures, 'pages', 'c.html'));
  5076. const load = once(w.webContents, 'did-finish-load');
  5077. const enterFS = once(w, 'enter-full-screen');
  5078. await Promise.all([enterFS, load]);
  5079. expect(w.fullScreen).to.be.true();
  5080. await setTimeout();
  5081. const leaveFullScreen = once(w, 'leave-full-screen');
  5082. w.setFullScreen(false);
  5083. await leaveFullScreen;
  5084. });
  5085. it('can be changed with setFullScreen method', async () => {
  5086. const w = new BrowserWindow();
  5087. const enterFullScreen = once(w, 'enter-full-screen');
  5088. w.setFullScreen(true);
  5089. await enterFullScreen;
  5090. expect(w.isFullScreen()).to.be.true('isFullScreen');
  5091. await setTimeout();
  5092. const leaveFullScreen = once(w, 'leave-full-screen');
  5093. w.setFullScreen(false);
  5094. await leaveFullScreen;
  5095. expect(w.isFullScreen()).to.be.false('isFullScreen');
  5096. });
  5097. it('handles several transitions starting with fullscreen', async () => {
  5098. const w = new BrowserWindow({ fullscreen: true, show: true });
  5099. expect(w.isFullScreen()).to.be.true('not fullscreen');
  5100. w.setFullScreen(false);
  5101. w.setFullScreen(true);
  5102. const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
  5103. await enterFullScreen;
  5104. expect(w.isFullScreen()).to.be.true('not fullscreen');
  5105. await setTimeout();
  5106. const leaveFullScreen = once(w, 'leave-full-screen');
  5107. w.setFullScreen(false);
  5108. await leaveFullScreen;
  5109. expect(w.isFullScreen()).to.be.false('is fullscreen');
  5110. });
  5111. it('handles several HTML fullscreen transitions', async () => {
  5112. const w = new BrowserWindow();
  5113. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  5114. expect(w.isFullScreen()).to.be.false('is fullscreen');
  5115. const enterFullScreen = once(w, 'enter-full-screen');
  5116. const leaveFullScreen = once(w, 'leave-full-screen');
  5117. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  5118. await enterFullScreen;
  5119. await w.webContents.executeJavaScript('document.exitFullscreen()', true);
  5120. await leaveFullScreen;
  5121. expect(w.isFullScreen()).to.be.false('is fullscreen');
  5122. await setTimeout();
  5123. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  5124. await enterFullScreen;
  5125. await w.webContents.executeJavaScript('document.exitFullscreen()', true);
  5126. await leaveFullScreen;
  5127. expect(w.isFullScreen()).to.be.false('is fullscreen');
  5128. });
  5129. it('handles several transitions in close proximity', async () => {
  5130. const w = new BrowserWindow();
  5131. expect(w.isFullScreen()).to.be.false('is fullscreen');
  5132. const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
  5133. const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
  5134. w.setFullScreen(true);
  5135. w.setFullScreen(false);
  5136. w.setFullScreen(true);
  5137. w.setFullScreen(false);
  5138. await Promise.all([enterFS, leaveFS]);
  5139. expect(w.isFullScreen()).to.be.false('not fullscreen');
  5140. });
  5141. it('handles several chromium-initiated transitions in close proximity', async () => {
  5142. const w = new BrowserWindow();
  5143. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  5144. expect(w.isFullScreen()).to.be.false('is fullscreen');
  5145. let enterCount = 0;
  5146. let exitCount = 0;
  5147. const done = new Promise<void>(resolve => {
  5148. const checkDone = () => {
  5149. if (enterCount === 2 && exitCount === 2) resolve();
  5150. };
  5151. w.webContents.on('enter-html-full-screen', () => {
  5152. enterCount++;
  5153. checkDone();
  5154. });
  5155. w.webContents.on('leave-html-full-screen', () => {
  5156. exitCount++;
  5157. checkDone();
  5158. });
  5159. });
  5160. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  5161. await w.webContents.executeJavaScript('document.exitFullscreen()');
  5162. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  5163. await w.webContents.executeJavaScript('document.exitFullscreen()');
  5164. await done;
  5165. });
  5166. it('handles HTML fullscreen transitions when fullscreenable is false', async () => {
  5167. const w = new BrowserWindow({ fullscreenable: false });
  5168. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  5169. expect(w.isFullScreen()).to.be.false('is fullscreen');
  5170. let enterCount = 0;
  5171. let exitCount = 0;
  5172. const done = new Promise<void>((resolve, reject) => {
  5173. const checkDone = () => {
  5174. if (enterCount === 2 && exitCount === 2) resolve();
  5175. };
  5176. w.webContents.on('enter-html-full-screen', async () => {
  5177. enterCount++;
  5178. if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
  5179. const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement');
  5180. if (!isFS) reject(new Error('Document should have fullscreen element'));
  5181. checkDone();
  5182. });
  5183. w.webContents.on('leave-html-full-screen', () => {
  5184. exitCount++;
  5185. if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
  5186. checkDone();
  5187. });
  5188. });
  5189. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  5190. await w.webContents.executeJavaScript('document.exitFullscreen()');
  5191. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  5192. await w.webContents.executeJavaScript('document.exitFullscreen()');
  5193. await expect(done).to.eventually.be.fulfilled();
  5194. });
  5195. it('does not crash when exiting simpleFullScreen (properties)', async () => {
  5196. const w = new BrowserWindow();
  5197. w.setSimpleFullScreen(true);
  5198. await setTimeout(1000);
  5199. w.setFullScreen(!w.isFullScreen());
  5200. });
  5201. it('does not crash when exiting simpleFullScreen (functions)', async () => {
  5202. const w = new BrowserWindow();
  5203. w.simpleFullScreen = true;
  5204. await setTimeout(1000);
  5205. w.setFullScreen(!w.isFullScreen());
  5206. });
  5207. it('should not be changed by setKiosk method', async () => {
  5208. const w = new BrowserWindow();
  5209. const enterFullScreen = once(w, 'enter-full-screen');
  5210. w.setKiosk(true);
  5211. await enterFullScreen;
  5212. expect(w.isFullScreen()).to.be.true('isFullScreen');
  5213. const leaveFullScreen = once(w, 'leave-full-screen');
  5214. w.setKiosk(false);
  5215. await leaveFullScreen;
  5216. expect(w.isFullScreen()).to.be.false('isFullScreen');
  5217. });
  5218. it('should stay fullscreen if fullscreen before kiosk', async () => {
  5219. const w = new BrowserWindow();
  5220. const enterFullScreen = once(w, 'enter-full-screen');
  5221. w.setFullScreen(true);
  5222. await enterFullScreen;
  5223. expect(w.isFullScreen()).to.be.true('isFullScreen');
  5224. w.setKiosk(true);
  5225. w.setKiosk(false);
  5226. // Wait enough time for a fullscreen change to take effect.
  5227. await setTimeout(2000);
  5228. expect(w.isFullScreen()).to.be.true('isFullScreen');
  5229. });
  5230. it('multiple windows inherit correct fullscreen state', async () => {
  5231. const w = new BrowserWindow();
  5232. const enterFullScreen = once(w, 'enter-full-screen');
  5233. w.setFullScreen(true);
  5234. await enterFullScreen;
  5235. expect(w.isFullScreen()).to.be.true('isFullScreen');
  5236. await setTimeout(1000);
  5237. const w2 = new BrowserWindow({ show: false });
  5238. const enterFullScreen2 = once(w2, 'enter-full-screen');
  5239. w2.show();
  5240. await enterFullScreen2;
  5241. expect(w2.isFullScreen()).to.be.true('isFullScreen');
  5242. });
  5243. });
  5244. describe('closable state', () => {
  5245. it('with properties', () => {
  5246. it('can be set with closable constructor option', () => {
  5247. const w = new BrowserWindow({ show: false, closable: false });
  5248. expect(w.closable).to.be.false('closable');
  5249. });
  5250. it('can be changed', () => {
  5251. const w = new BrowserWindow({ show: false });
  5252. expect(w.closable).to.be.true('closable');
  5253. w.closable = false;
  5254. expect(w.closable).to.be.false('closable');
  5255. w.closable = true;
  5256. expect(w.closable).to.be.true('closable');
  5257. });
  5258. });
  5259. it('with functions', () => {
  5260. it('can be set with closable constructor option', () => {
  5261. const w = new BrowserWindow({ show: false, closable: false });
  5262. expect(w.isClosable()).to.be.false('isClosable');
  5263. });
  5264. it('can be changed', () => {
  5265. const w = new BrowserWindow({ show: false });
  5266. expect(w.isClosable()).to.be.true('isClosable');
  5267. w.setClosable(false);
  5268. expect(w.isClosable()).to.be.false('isClosable');
  5269. w.setClosable(true);
  5270. expect(w.isClosable()).to.be.true('isClosable');
  5271. });
  5272. });
  5273. });
  5274. describe('hasShadow state', () => {
  5275. it('with properties', () => {
  5276. it('returns a boolean on all platforms', () => {
  5277. const w = new BrowserWindow({ show: false });
  5278. expect(w.shadow).to.be.a('boolean');
  5279. });
  5280. // On Windows there's no shadow by default & it can't be changed dynamically.
  5281. it('can be changed with hasShadow option', () => {
  5282. const hasShadow = process.platform !== 'darwin';
  5283. const w = new BrowserWindow({ show: false, hasShadow });
  5284. expect(w.shadow).to.equal(hasShadow);
  5285. });
  5286. it('can be changed with setHasShadow method', () => {
  5287. const w = new BrowserWindow({ show: false });
  5288. w.shadow = false;
  5289. expect(w.shadow).to.be.false('hasShadow');
  5290. w.shadow = true;
  5291. expect(w.shadow).to.be.true('hasShadow');
  5292. w.shadow = false;
  5293. expect(w.shadow).to.be.false('hasShadow');
  5294. });
  5295. });
  5296. describe('with functions', () => {
  5297. it('returns a boolean on all platforms', () => {
  5298. const w = new BrowserWindow({ show: false });
  5299. const hasShadow = w.hasShadow();
  5300. expect(hasShadow).to.be.a('boolean');
  5301. });
  5302. // On Windows there's no shadow by default & it can't be changed dynamically.
  5303. it('can be changed with hasShadow option', () => {
  5304. const hasShadow = process.platform !== 'darwin';
  5305. const w = new BrowserWindow({ show: false, hasShadow });
  5306. expect(w.hasShadow()).to.equal(hasShadow);
  5307. });
  5308. it('can be changed with setHasShadow method', () => {
  5309. const w = new BrowserWindow({ show: false });
  5310. w.setHasShadow(false);
  5311. expect(w.hasShadow()).to.be.false('hasShadow');
  5312. w.setHasShadow(true);
  5313. expect(w.hasShadow()).to.be.true('hasShadow');
  5314. w.setHasShadow(false);
  5315. expect(w.hasShadow()).to.be.false('hasShadow');
  5316. });
  5317. });
  5318. });
  5319. });
  5320. describe('window.getMediaSourceId()', () => {
  5321. afterEach(closeAllWindows);
  5322. it('returns valid source id', async () => {
  5323. const w = new BrowserWindow({ show: false });
  5324. const shown = once(w, 'show');
  5325. w.show();
  5326. await shown;
  5327. // Check format 'window:1234:0'.
  5328. const sourceId = w.getMediaSourceId();
  5329. expect(sourceId).to.match(/^window:\d+:\d+$/);
  5330. });
  5331. });
  5332. ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
  5333. afterEach(closeAllWindows);
  5334. it('returns valid handle', () => {
  5335. const w = new BrowserWindow({ show: false });
  5336. const isValidWindow = require('@electron-ci/is-valid-window');
  5337. expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
  5338. });
  5339. });
  5340. ifdescribe(process.platform === 'darwin')('previewFile', () => {
  5341. afterEach(closeAllWindows);
  5342. it('opens the path in Quick Look on macOS', () => {
  5343. const w = new BrowserWindow({ show: false });
  5344. expect(() => {
  5345. w.previewFile(__filename);
  5346. w.closeFilePreview();
  5347. }).to.not.throw();
  5348. });
  5349. it('should not call BrowserWindow show event', async () => {
  5350. const w = new BrowserWindow({ show: false });
  5351. const shown = once(w, 'show');
  5352. w.show();
  5353. await shown;
  5354. let showCalled = false;
  5355. w.on('show', () => {
  5356. showCalled = true;
  5357. });
  5358. w.previewFile(__filename);
  5359. await setTimeout(500);
  5360. expect(showCalled).to.equal(false, 'should not have called show twice');
  5361. });
  5362. });
  5363. // TODO (jkleinsc) renable these tests on mas arm64
  5364. ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
  5365. const expectedContextData = {
  5366. preloadContext: {
  5367. preloadProperty: 'number',
  5368. pageProperty: 'undefined',
  5369. typeofRequire: 'function',
  5370. typeofProcess: 'object',
  5371. typeofArrayPush: 'function',
  5372. typeofFunctionApply: 'function',
  5373. typeofPreloadExecuteJavaScriptProperty: 'undefined'
  5374. },
  5375. pageContext: {
  5376. preloadProperty: 'undefined',
  5377. pageProperty: 'string',
  5378. typeofRequire: 'undefined',
  5379. typeofProcess: 'undefined',
  5380. typeofArrayPush: 'number',
  5381. typeofFunctionApply: 'boolean',
  5382. typeofPreloadExecuteJavaScriptProperty: 'number',
  5383. typeofOpenedWindow: 'object'
  5384. }
  5385. };
  5386. afterEach(closeAllWindows);
  5387. it('separates the page context from the Electron/preload context', async () => {
  5388. const iw = new BrowserWindow({
  5389. show: false,
  5390. webPreferences: {
  5391. contextIsolation: true,
  5392. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  5393. }
  5394. });
  5395. const p = once(ipcMain, 'isolated-world');
  5396. iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  5397. const [, data] = await p;
  5398. expect(data).to.deep.equal(expectedContextData);
  5399. });
  5400. it('recreates the contexts on reload', async () => {
  5401. const iw = new BrowserWindow({
  5402. show: false,
  5403. webPreferences: {
  5404. contextIsolation: true,
  5405. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  5406. }
  5407. });
  5408. await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  5409. const isolatedWorld = once(ipcMain, 'isolated-world');
  5410. iw.webContents.reload();
  5411. const [, data] = await isolatedWorld;
  5412. expect(data).to.deep.equal(expectedContextData);
  5413. });
  5414. it('enables context isolation on child windows', async () => {
  5415. const iw = new BrowserWindow({
  5416. show: false,
  5417. webPreferences: {
  5418. contextIsolation: true,
  5419. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  5420. }
  5421. });
  5422. const browserWindowCreated = once(app, 'browser-window-created') as Promise<[any, BrowserWindow]>;
  5423. iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  5424. const [, window] = await browserWindowCreated;
  5425. expect(window.webContents.getLastWebPreferences()!.contextIsolation).to.be.true('contextIsolation');
  5426. });
  5427. it('separates the page context from the Electron/preload context with sandbox on', async () => {
  5428. const ws = new BrowserWindow({
  5429. show: false,
  5430. webPreferences: {
  5431. sandbox: true,
  5432. contextIsolation: true,
  5433. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  5434. }
  5435. });
  5436. const p = once(ipcMain, 'isolated-world');
  5437. ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  5438. const [, data] = await p;
  5439. expect(data).to.deep.equal(expectedContextData);
  5440. });
  5441. it('recreates the contexts on reload with sandbox on', async () => {
  5442. const ws = new BrowserWindow({
  5443. show: false,
  5444. webPreferences: {
  5445. sandbox: true,
  5446. contextIsolation: true,
  5447. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  5448. }
  5449. });
  5450. await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  5451. const isolatedWorld = once(ipcMain, 'isolated-world');
  5452. ws.webContents.reload();
  5453. const [, data] = await isolatedWorld;
  5454. expect(data).to.deep.equal(expectedContextData);
  5455. });
  5456. it('supports fetch api', async () => {
  5457. const fetchWindow = new BrowserWindow({
  5458. show: false,
  5459. webPreferences: {
  5460. contextIsolation: true,
  5461. preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
  5462. }
  5463. });
  5464. const p = once(ipcMain, 'isolated-fetch-error');
  5465. fetchWindow.loadURL('about:blank');
  5466. const [, error] = await p;
  5467. expect(error).to.equal('Failed to fetch');
  5468. });
  5469. it('doesn\'t break ipc serialization', async () => {
  5470. const iw = new BrowserWindow({
  5471. show: false,
  5472. webPreferences: {
  5473. contextIsolation: true,
  5474. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  5475. }
  5476. });
  5477. const p = once(ipcMain, 'isolated-world');
  5478. iw.loadURL('about:blank');
  5479. iw.webContents.executeJavaScript(`
  5480. const opened = window.open()
  5481. openedLocation = opened.location.href
  5482. opened.close()
  5483. window.postMessage({openedLocation}, '*')
  5484. `);
  5485. const [, data] = await p;
  5486. expect(data.pageContext.openedLocation).to.equal('about:blank');
  5487. });
  5488. it('reports process.contextIsolated', async () => {
  5489. const iw = new BrowserWindow({
  5490. show: false,
  5491. webPreferences: {
  5492. contextIsolation: true,
  5493. preload: path.join(fixtures, 'api', 'isolated-process.js')
  5494. }
  5495. });
  5496. const p = once(ipcMain, 'context-isolation');
  5497. iw.loadURL('about:blank');
  5498. const [, contextIsolation] = await p;
  5499. expect(contextIsolation).to.be.true('contextIsolation');
  5500. });
  5501. });
  5502. it('reloading does not cause Node.js module API hangs after reload', (done) => {
  5503. const w = new BrowserWindow({
  5504. show: false,
  5505. webPreferences: {
  5506. nodeIntegration: true,
  5507. contextIsolation: false
  5508. }
  5509. });
  5510. let count = 0;
  5511. ipcMain.on('async-node-api-done', () => {
  5512. if (count === 3) {
  5513. ipcMain.removeAllListeners('async-node-api-done');
  5514. done();
  5515. } else {
  5516. count++;
  5517. w.reload();
  5518. }
  5519. });
  5520. w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
  5521. });
  5522. describe('window.webContents.focus()', () => {
  5523. afterEach(closeAllWindows);
  5524. it('focuses window', async () => {
  5525. const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
  5526. w1.loadURL('about:blank');
  5527. const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
  5528. w2.loadURL('about:blank');
  5529. const w1Focused = once(w1, 'focus');
  5530. w1.webContents.focus();
  5531. await w1Focused;
  5532. expect(w1.webContents.isFocused()).to.be.true('focuses window');
  5533. });
  5534. });
  5535. describe('offscreen rendering', () => {
  5536. let w: BrowserWindow;
  5537. beforeEach(function () {
  5538. w = new BrowserWindow({
  5539. width: 100,
  5540. height: 100,
  5541. show: false,
  5542. webPreferences: {
  5543. backgroundThrottling: false,
  5544. offscreen: true
  5545. }
  5546. });
  5547. });
  5548. afterEach(closeAllWindows);
  5549. it('creates offscreen window with correct size', async () => {
  5550. const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>;
  5551. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5552. const [,, data] = await paint;
  5553. expect(data.constructor.name).to.equal('NativeImage');
  5554. expect(data.isEmpty()).to.be.false('data is empty');
  5555. const size = data.getSize();
  5556. const { scaleFactor } = screen.getPrimaryDisplay();
  5557. expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
  5558. expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
  5559. });
  5560. it('does not crash after navigation', () => {
  5561. w.webContents.loadURL('about:blank');
  5562. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5563. });
  5564. describe('window.webContents.isOffscreen()', () => {
  5565. it('is true for offscreen type', () => {
  5566. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5567. expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
  5568. });
  5569. it('is false for regular window', () => {
  5570. const c = new BrowserWindow({ show: false });
  5571. expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
  5572. c.destroy();
  5573. });
  5574. });
  5575. describe('window.webContents.isPainting()', () => {
  5576. it('returns whether is currently painting', async () => {
  5577. const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>;
  5578. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5579. await paint;
  5580. expect(w.webContents.isPainting()).to.be.true('isPainting');
  5581. });
  5582. });
  5583. describe('window.webContents.stopPainting()', () => {
  5584. it('stops painting', async () => {
  5585. const domReady = once(w.webContents, 'dom-ready');
  5586. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5587. await domReady;
  5588. w.webContents.stopPainting();
  5589. expect(w.webContents.isPainting()).to.be.false('isPainting');
  5590. });
  5591. });
  5592. describe('window.webContents.startPainting()', () => {
  5593. it('starts painting', async () => {
  5594. const domReady = once(w.webContents, 'dom-ready');
  5595. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5596. await domReady;
  5597. w.webContents.stopPainting();
  5598. w.webContents.startPainting();
  5599. await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
  5600. expect(w.webContents.isPainting()).to.be.true('isPainting');
  5601. });
  5602. });
  5603. describe('frameRate APIs', () => {
  5604. it('has default frame rate (function)', async () => {
  5605. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5606. await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
  5607. expect(w.webContents.getFrameRate()).to.equal(60);
  5608. });
  5609. it('has default frame rate (property)', async () => {
  5610. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5611. await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
  5612. expect(w.webContents.frameRate).to.equal(60);
  5613. });
  5614. it('sets custom frame rate (function)', async () => {
  5615. const domReady = once(w.webContents, 'dom-ready');
  5616. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5617. await domReady;
  5618. w.webContents.setFrameRate(30);
  5619. await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
  5620. expect(w.webContents.getFrameRate()).to.equal(30);
  5621. });
  5622. it('sets custom frame rate (property)', async () => {
  5623. const domReady = once(w.webContents, 'dom-ready');
  5624. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5625. await domReady;
  5626. w.webContents.frameRate = 30;
  5627. await once(w.webContents, 'paint') as [any, Electron.Rectangle, Electron.NativeImage];
  5628. expect(w.webContents.frameRate).to.equal(30);
  5629. });
  5630. });
  5631. });
  5632. describe('"transparent" option', () => {
  5633. afterEach(closeAllWindows);
  5634. ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => {
  5635. const w = new BrowserWindow({
  5636. frame: false,
  5637. transparent: true
  5638. });
  5639. const maximize = once(w, 'maximize');
  5640. w.maximize();
  5641. await maximize;
  5642. const minimize = once(w, 'minimize');
  5643. w.minimize();
  5644. await minimize;
  5645. expect(w.isMaximized()).to.be.false();
  5646. expect(w.isMinimized()).to.be.true();
  5647. });
  5648. // Only applicable on Windows where transparent windows can't be maximized.
  5649. ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
  5650. const display = screen.getPrimaryDisplay();
  5651. const w = new BrowserWindow({
  5652. ...display.bounds,
  5653. frame: false,
  5654. transparent: true,
  5655. show: true
  5656. });
  5657. w.loadURL('about:blank');
  5658. await once(w, 'ready-to-show');
  5659. expect(w.isMaximized()).to.be.true();
  5660. // Fails when the transparent HWND is in an invalid maximized state.
  5661. expect(w.getBounds()).to.deep.equal(display.workArea);
  5662. const newBounds = { width: 256, height: 256, x: 0, y: 0 };
  5663. w.setBounds(newBounds);
  5664. expect(w.getBounds()).to.deep.equal(newBounds);
  5665. });
  5666. // FIXME(codebytere): figure out why these are failing on macOS arm64.
  5667. ifit(process.platform === 'darwin' && process.arch !== 'arm64')('should not display a visible background', async () => {
  5668. const display = screen.getPrimaryDisplay();
  5669. const backgroundWindow = new BrowserWindow({
  5670. ...display.bounds,
  5671. frame: false,
  5672. backgroundColor: HexColors.GREEN,
  5673. hasShadow: false
  5674. });
  5675. await backgroundWindow.loadURL('about:blank');
  5676. const foregroundWindow = new BrowserWindow({
  5677. ...display.bounds,
  5678. show: true,
  5679. transparent: true,
  5680. frame: false,
  5681. hasShadow: false
  5682. });
  5683. const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html');
  5684. await foregroundWindow.loadFile(colorFile);
  5685. await setTimeout(1000);
  5686. const screenCapture = await ScreenCapture.createForDisplay(display);
  5687. await screenCapture.expectColorAtPointOnDisplayMatches(
  5688. HexColors.GREEN,
  5689. (size) => ({
  5690. x: size.width / 4,
  5691. y: size.height / 2
  5692. })
  5693. );
  5694. await screenCapture.expectColorAtPointOnDisplayMatches(
  5695. HexColors.RED,
  5696. (size) => ({
  5697. x: size.width * 3 / 4,
  5698. y: size.height / 2
  5699. })
  5700. );
  5701. });
  5702. // FIXME(codebytere): figure out why these are failing on macOS arm64.
  5703. ifit(process.platform === 'darwin' && process.arch !== 'arm64')('Allows setting a transparent window via CSS', async () => {
  5704. const display = screen.getPrimaryDisplay();
  5705. const backgroundWindow = new BrowserWindow({
  5706. ...display.bounds,
  5707. frame: false,
  5708. backgroundColor: HexColors.PURPLE,
  5709. hasShadow: false
  5710. });
  5711. await backgroundWindow.loadURL('about:blank');
  5712. const foregroundWindow = new BrowserWindow({
  5713. ...display.bounds,
  5714. frame: false,
  5715. transparent: true,
  5716. hasShadow: false,
  5717. webPreferences: {
  5718. contextIsolation: false,
  5719. nodeIntegration: true
  5720. }
  5721. });
  5722. foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html'));
  5723. await once(ipcMain, 'set-transparent');
  5724. await setTimeout(1000);
  5725. const screenCapture = await ScreenCapture.createForDisplay(display);
  5726. await screenCapture.expectColorAtCenterMatches(HexColors.PURPLE);
  5727. });
  5728. // Linux and arm64 platforms (WOA and macOS) do not return any capture sources
  5729. ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => {
  5730. const display = screen.getPrimaryDisplay();
  5731. for (const transparent of [false, undefined]) {
  5732. const window = new BrowserWindow({
  5733. ...display.bounds,
  5734. transparent
  5735. });
  5736. await once(window, 'show');
  5737. await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>');
  5738. await setTimeout(1000);
  5739. const screenCapture = await ScreenCapture.createForDisplay(display);
  5740. // color-scheme is set to dark so background should not be white
  5741. await screenCapture.expectColorAtCenterDoesNotMatch(HexColors.WHITE);
  5742. window.close();
  5743. }
  5744. });
  5745. });
  5746. describe('"backgroundColor" option', () => {
  5747. afterEach(closeAllWindows);
  5748. // Linux/WOA doesn't return any capture sources.
  5749. ifit(process.platform === 'darwin')('should display the set color', async () => {
  5750. const display = screen.getPrimaryDisplay();
  5751. const w = new BrowserWindow({
  5752. ...display.bounds,
  5753. show: true,
  5754. backgroundColor: HexColors.BLUE
  5755. });
  5756. w.loadURL('about:blank');
  5757. await once(w, 'ready-to-show');
  5758. await setTimeout(1000);
  5759. const screenCapture = await ScreenCapture.createForDisplay(display);
  5760. await screenCapture.expectColorAtCenterMatches(HexColors.BLUE);
  5761. });
  5762. });
  5763. describe('draggable regions', () => {
  5764. afterEach(closeAllWindows);
  5765. ifit(hasCapturableScreen())('should allow the window to be dragged when enabled', async () => {
  5766. // FIXME: nut-js has been removed from npm; we need to find a replacement
  5767. // WOA fails to load libnut so we're using require to defer loading only
  5768. // on supported platforms.
  5769. // "@nut-tree\libnut-win32\build\Release\libnut.node is not a valid Win32 application."
  5770. // @ts-ignore: nut-js is an optional dependency so it may not be installed
  5771. const { mouse, straightTo, centerOf, Region, Button } = require('@nut-tree/nut-js') as typeof import('@nut-tree/nut-js');
  5772. const display = screen.getPrimaryDisplay();
  5773. const w = new BrowserWindow({
  5774. x: 0,
  5775. y: 0,
  5776. width: display.bounds.width / 2,
  5777. height: display.bounds.height / 2,
  5778. frame: false,
  5779. titleBarStyle: 'hidden'
  5780. });
  5781. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  5782. w.loadFile(overlayHTML);
  5783. await once(w, 'ready-to-show');
  5784. const winBounds = w.getBounds();
  5785. const titleBarHeight = 30;
  5786. const titleBarRegion = new Region(winBounds.x, winBounds.y, winBounds.width, titleBarHeight);
  5787. const screenRegion = new Region(display.bounds.x, display.bounds.y, display.bounds.width, display.bounds.height);
  5788. const startPos = w.getPosition();
  5789. await mouse.setPosition(await centerOf(titleBarRegion));
  5790. await mouse.pressButton(Button.LEFT);
  5791. await mouse.drag(straightTo(centerOf(screenRegion)));
  5792. // Wait for move to complete
  5793. await Promise.race([
  5794. once(w, 'move'),
  5795. setTimeout(100) // fallback for possible race condition
  5796. ]);
  5797. const endPos = w.getPosition();
  5798. expect(startPos).to.not.deep.equal(endPos);
  5799. });
  5800. ifit(hasCapturableScreen())('should allow the window to be dragged when no WCO and --webkit-app-region: drag enabled', async () => {
  5801. // FIXME: nut-js has been removed from npm; we need to find a replacement
  5802. // @ts-ignore: nut-js is an optional dependency so it may not be installed
  5803. const { mouse, straightTo, centerOf, Region, Button } = require('@nut-tree/nut-js') as typeof import('@nut-tree/nut-js');
  5804. const display = screen.getPrimaryDisplay();
  5805. const w = new BrowserWindow({
  5806. x: 0,
  5807. y: 0,
  5808. width: display.bounds.width / 2,
  5809. height: display.bounds.height / 2,
  5810. frame: false
  5811. });
  5812. const basePageHTML = path.join(__dirname, 'fixtures', 'pages', 'base-page.html');
  5813. w.loadFile(basePageHTML);
  5814. await once(w, 'ready-to-show');
  5815. await w.webContents.executeJavaScript(`
  5816. const style = document.createElement('style');
  5817. style.innerHTML = \`
  5818. #titlebar {
  5819. background-color: red;
  5820. height: 30px;
  5821. width: 100%;
  5822. -webkit-user-select: none;
  5823. -webkit-app-region: drag;
  5824. position: fixed;
  5825. top: 0;
  5826. left: 0;
  5827. z-index: 1000000000000;
  5828. }
  5829. \`;
  5830. const titleBar = document.createElement('title-bar');
  5831. titleBar.id = 'titlebar';
  5832. titleBar.textContent = 'test-titlebar';
  5833. document.body.append(style);
  5834. document.body.append(titleBar);
  5835. `);
  5836. // allow time for titlebar to finish loading
  5837. await setTimeout(2000);
  5838. const winBounds = w.getBounds();
  5839. const titleBarHeight = 30;
  5840. const titleBarRegion = new Region(winBounds.x, winBounds.y, winBounds.width, titleBarHeight);
  5841. const screenRegion = new Region(display.bounds.x, display.bounds.y, display.bounds.width, display.bounds.height);
  5842. const startPos = w.getPosition();
  5843. await mouse.setPosition(await centerOf(titleBarRegion));
  5844. await mouse.pressButton(Button.LEFT);
  5845. await mouse.drag(straightTo(centerOf(screenRegion)));
  5846. // Wait for move to complete
  5847. await Promise.race([
  5848. once(w, 'move'),
  5849. setTimeout(1000) // fallback for possible race condition
  5850. ]);
  5851. const endPos = w.getPosition();
  5852. expect(startPos).to.not.deep.equal(endPos);
  5853. });
  5854. });
  5855. });