api-browser-window-spec.ts 237 KB

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