api-browser-window-spec.ts 238 KB

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