api-browser-window-spec.ts 234 KB

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