api-browser-window-spec.ts 228 KB

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