api-browser-window-spec.ts 223 KB

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