api-browser-window-spec.ts 198 KB

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