api-browser-window-spec.ts 239 KB

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