api-browser-window-spec.ts 233 KB

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