api-browser-window-spec.ts 239 KB

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