api-browser-window-spec.ts 194 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532
  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 } 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, '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(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 = { ...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, 'maximize');
  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('can be changed', () => {
  1302. w.fullScreen = false;
  1303. expect(w.fullScreen).to.be.false();
  1304. w.fullScreen = true;
  1305. expect(w.fullScreen).to.be.true();
  1306. });
  1307. it('checks normal bounds when fullscreen\'ed', async () => {
  1308. const bounds = w.getBounds();
  1309. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1310. w.show();
  1311. w.fullScreen = true;
  1312. await enterFullScreen;
  1313. expectBoundsEqual(w.getNormalBounds(), bounds);
  1314. });
  1315. it('updates normal bounds after resize and fullscreen', async () => {
  1316. const size = [300, 400];
  1317. const resize = emittedOnce(w, 'resize');
  1318. w.setSize(size[0], size[1]);
  1319. await resize;
  1320. const original = w.getBounds();
  1321. const fsc = emittedOnce(w, 'enter-full-screen');
  1322. w.fullScreen = true;
  1323. await fsc;
  1324. const normal = w.getNormalBounds();
  1325. const bounds = w.getBounds();
  1326. expect(normal).to.deep.equal(original);
  1327. expect(normal).to.not.deep.equal(bounds);
  1328. const close = emittedOnce(w, 'close');
  1329. w.close();
  1330. await close;
  1331. });
  1332. it('updates normal bounds after move and fullscreen', async () => {
  1333. const pos = [10, 10];
  1334. const move = emittedOnce(w, 'move');
  1335. w.setPosition(pos[0], pos[1]);
  1336. await move;
  1337. const original = w.getBounds();
  1338. const fsc = emittedOnce(w, 'enter-full-screen');
  1339. w.fullScreen = true;
  1340. await fsc;
  1341. const normal = w.getNormalBounds();
  1342. const bounds = w.getBounds();
  1343. expect(normal).to.deep.equal(original);
  1344. expect(normal).to.not.deep.equal(bounds);
  1345. const close = emittedOnce(w, 'close');
  1346. w.close();
  1347. await close;
  1348. });
  1349. it('checks normal bounds when unfullscreen\'ed', async () => {
  1350. const bounds = w.getBounds();
  1351. w.once('enter-full-screen', () => {
  1352. w.fullScreen = false;
  1353. });
  1354. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1355. w.show();
  1356. w.fullScreen = true;
  1357. await leaveFullScreen;
  1358. expectBoundsEqual(w.getNormalBounds(), bounds);
  1359. });
  1360. });
  1361. it('with functions', () => {
  1362. it('can be set with the fullscreen constructor option', () => {
  1363. w = new BrowserWindow({ fullscreen: true });
  1364. expect(w.isFullScreen()).to.be.true();
  1365. });
  1366. it('can be changed', () => {
  1367. w.setFullScreen(false);
  1368. expect(w.isFullScreen()).to.be.false();
  1369. w.setFullScreen(true);
  1370. expect(w.isFullScreen()).to.be.true();
  1371. });
  1372. it('checks normal bounds when fullscreen\'ed', async () => {
  1373. const bounds = w.getBounds();
  1374. w.show();
  1375. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1376. w.setFullScreen(true);
  1377. await enterFullScreen;
  1378. expectBoundsEqual(w.getNormalBounds(), bounds);
  1379. });
  1380. it('updates normal bounds after resize and fullscreen', async () => {
  1381. const size = [300, 400];
  1382. const resize = emittedOnce(w, 'resize');
  1383. w.setSize(size[0], size[1]);
  1384. await resize;
  1385. const original = w.getBounds();
  1386. const fsc = emittedOnce(w, 'enter-full-screen');
  1387. w.setFullScreen(true);
  1388. await fsc;
  1389. const normal = w.getNormalBounds();
  1390. const bounds = w.getBounds();
  1391. expect(normal).to.deep.equal(original);
  1392. expect(normal).to.not.deep.equal(bounds);
  1393. const close = emittedOnce(w, 'close');
  1394. w.close();
  1395. await close;
  1396. });
  1397. it('updates normal bounds after move and fullscreen', async () => {
  1398. const pos = [10, 10];
  1399. const move = emittedOnce(w, 'move');
  1400. w.setPosition(pos[0], pos[1]);
  1401. await move;
  1402. const original = w.getBounds();
  1403. const fsc = emittedOnce(w, 'enter-full-screen');
  1404. w.setFullScreen(true);
  1405. await fsc;
  1406. const normal = w.getNormalBounds();
  1407. const bounds = w.getBounds();
  1408. expect(normal).to.deep.equal(original);
  1409. expect(normal).to.not.deep.equal(bounds);
  1410. const close = emittedOnce(w, 'close');
  1411. w.close();
  1412. await close;
  1413. });
  1414. it('checks normal bounds when unfullscreen\'ed', async () => {
  1415. const bounds = w.getBounds();
  1416. w.show();
  1417. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1418. w.setFullScreen(true);
  1419. await enterFullScreen;
  1420. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1421. w.setFullScreen(false);
  1422. await leaveFullScreen;
  1423. expectBoundsEqual(w.getNormalBounds(), bounds);
  1424. });
  1425. });
  1426. });
  1427. });
  1428. });
  1429. ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
  1430. let w = null as unknown as BrowserWindow;
  1431. beforeEach(() => {
  1432. w = new BrowserWindow({ show: false });
  1433. });
  1434. afterEach(async () => {
  1435. await closeWindow(w);
  1436. w = null as unknown as BrowserWindow;
  1437. });
  1438. describe('BrowserWindow.selectPreviousTab()', () => {
  1439. it('does not throw', () => {
  1440. expect(() => {
  1441. w.selectPreviousTab();
  1442. }).to.not.throw();
  1443. });
  1444. });
  1445. describe('BrowserWindow.selectNextTab()', () => {
  1446. it('does not throw', () => {
  1447. expect(() => {
  1448. w.selectNextTab();
  1449. }).to.not.throw();
  1450. });
  1451. });
  1452. describe('BrowserWindow.mergeAllWindows()', () => {
  1453. it('does not throw', () => {
  1454. expect(() => {
  1455. w.mergeAllWindows();
  1456. }).to.not.throw();
  1457. });
  1458. });
  1459. describe('BrowserWindow.moveTabToNewWindow()', () => {
  1460. it('does not throw', () => {
  1461. expect(() => {
  1462. w.moveTabToNewWindow();
  1463. }).to.not.throw();
  1464. });
  1465. });
  1466. describe('BrowserWindow.toggleTabBar()', () => {
  1467. it('does not throw', () => {
  1468. expect(() => {
  1469. w.toggleTabBar();
  1470. }).to.not.throw();
  1471. });
  1472. });
  1473. describe('BrowserWindow.addTabbedWindow()', () => {
  1474. it('does not throw', async () => {
  1475. const tabbedWindow = new BrowserWindow({});
  1476. expect(() => {
  1477. w.addTabbedWindow(tabbedWindow);
  1478. }).to.not.throw();
  1479. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
  1480. await closeWindow(tabbedWindow, { assertNotWindows: false });
  1481. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
  1482. });
  1483. it('throws when called on itself', () => {
  1484. expect(() => {
  1485. w.addTabbedWindow(w);
  1486. }).to.throw('AddTabbedWindow cannot be called by a window on itself.');
  1487. });
  1488. });
  1489. });
  1490. describe('autoHideMenuBar state', () => {
  1491. afterEach(closeAllWindows);
  1492. it('for properties', () => {
  1493. it('can be set with autoHideMenuBar constructor option', () => {
  1494. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1495. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1496. });
  1497. it('can be changed', () => {
  1498. const w = new BrowserWindow({ show: false });
  1499. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1500. w.autoHideMenuBar = true;
  1501. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1502. w.autoHideMenuBar = false;
  1503. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1504. });
  1505. });
  1506. it('for functions', () => {
  1507. it('can be set with autoHideMenuBar constructor option', () => {
  1508. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1509. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1510. });
  1511. it('can be changed', () => {
  1512. const w = new BrowserWindow({ show: false });
  1513. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1514. w.setAutoHideMenuBar(true);
  1515. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1516. w.setAutoHideMenuBar(false);
  1517. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1518. });
  1519. });
  1520. });
  1521. describe('BrowserWindow.capturePage(rect)', () => {
  1522. afterEach(closeAllWindows);
  1523. it('returns a Promise with a Buffer', async () => {
  1524. const w = new BrowserWindow({ show: false });
  1525. const image = await w.capturePage({
  1526. x: 0,
  1527. y: 0,
  1528. width: 100,
  1529. height: 100
  1530. });
  1531. expect(image.isEmpty()).to.equal(true);
  1532. });
  1533. it('resolves after the window is hidden', async () => {
  1534. const w = new BrowserWindow({ show: false });
  1535. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  1536. await emittedOnce(w, 'ready-to-show');
  1537. w.show();
  1538. const visibleImage = await w.capturePage();
  1539. expect(visibleImage.isEmpty()).to.equal(false);
  1540. w.hide();
  1541. const hiddenImage = await w.capturePage();
  1542. const isEmpty = process.platform !== 'darwin';
  1543. expect(hiddenImage.isEmpty()).to.equal(isEmpty);
  1544. });
  1545. it('resolves after the window is hidden and capturer count is non-zero', async () => {
  1546. const w = new BrowserWindow({ show: false });
  1547. w.webContents.setBackgroundThrottling(false);
  1548. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  1549. await emittedOnce(w, 'ready-to-show');
  1550. w.webContents.incrementCapturerCount();
  1551. const image = await w.capturePage();
  1552. expect(image.isEmpty()).to.equal(false);
  1553. });
  1554. it('preserves transparency', async () => {
  1555. const w = new BrowserWindow({ show: false, transparent: true });
  1556. w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
  1557. await emittedOnce(w, 'ready-to-show');
  1558. w.show();
  1559. const image = await w.capturePage();
  1560. const imgBuffer = image.toPNG();
  1561. // Check the 25th byte in the PNG.
  1562. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  1563. expect(imgBuffer[25]).to.equal(6);
  1564. });
  1565. it('should increase the capturer count', () => {
  1566. const w = new BrowserWindow({ show: false });
  1567. w.webContents.incrementCapturerCount();
  1568. expect(w.webContents.isBeingCaptured()).to.be.true();
  1569. w.webContents.decrementCapturerCount();
  1570. expect(w.webContents.isBeingCaptured()).to.be.false();
  1571. });
  1572. });
  1573. describe('BrowserWindow.setProgressBar(progress)', () => {
  1574. let w = null as unknown as BrowserWindow;
  1575. before(() => {
  1576. w = new BrowserWindow({ show: false });
  1577. });
  1578. after(async () => {
  1579. await closeWindow(w);
  1580. w = null as unknown as BrowserWindow;
  1581. });
  1582. it('sets the progress', () => {
  1583. expect(() => {
  1584. if (process.platform === 'darwin') {
  1585. app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
  1586. }
  1587. w.setProgressBar(0.5);
  1588. if (process.platform === 'darwin') {
  1589. app.dock.setIcon(null as any);
  1590. }
  1591. w.setProgressBar(-1);
  1592. }).to.not.throw();
  1593. });
  1594. it('sets the progress using "paused" mode', () => {
  1595. expect(() => {
  1596. w.setProgressBar(0.5, { mode: 'paused' });
  1597. }).to.not.throw();
  1598. });
  1599. it('sets the progress using "error" mode', () => {
  1600. expect(() => {
  1601. w.setProgressBar(0.5, { mode: 'error' });
  1602. }).to.not.throw();
  1603. });
  1604. it('sets the progress using "normal" mode', () => {
  1605. expect(() => {
  1606. w.setProgressBar(0.5, { mode: 'normal' });
  1607. }).to.not.throw();
  1608. });
  1609. });
  1610. describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
  1611. let w = null as unknown as BrowserWindow;
  1612. afterEach(closeAllWindows);
  1613. beforeEach(() => {
  1614. w = new BrowserWindow({ show: true });
  1615. });
  1616. it('sets the window as always on top', () => {
  1617. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1618. w.setAlwaysOnTop(true, 'screen-saver');
  1619. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1620. w.setAlwaysOnTop(false);
  1621. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1622. w.setAlwaysOnTop(true);
  1623. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1624. });
  1625. ifit(process.platform === 'darwin')('resets the windows level on minimize', () => {
  1626. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1627. w.setAlwaysOnTop(true, 'screen-saver');
  1628. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1629. w.minimize();
  1630. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1631. w.restore();
  1632. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1633. });
  1634. it('causes the right value to be emitted on `always-on-top-changed`', async () => {
  1635. const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed');
  1636. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1637. w.setAlwaysOnTop(true);
  1638. const [, alwaysOnTop] = await alwaysOnTopChanged;
  1639. expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
  1640. });
  1641. ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
  1642. w = new BrowserWindow({ show: false });
  1643. const c = new BrowserWindow({ parent: w });
  1644. c.setAlwaysOnTop(true, 'screen-saver');
  1645. expect(w.isAlwaysOnTop()).to.be.false();
  1646. expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
  1647. expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver');
  1648. });
  1649. });
  1650. describe('preconnect feature', () => {
  1651. let w = null as unknown as BrowserWindow;
  1652. let server = null as unknown as http.Server;
  1653. let url = null as unknown as string;
  1654. let connections = 0;
  1655. beforeEach(async () => {
  1656. connections = 0;
  1657. server = http.createServer((req, res) => {
  1658. if (req.url === '/link') {
  1659. res.setHeader('Content-type', 'text/html');
  1660. res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
  1661. return;
  1662. }
  1663. res.end();
  1664. });
  1665. server.on('connection', () => { connections++; });
  1666. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()));
  1667. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1668. });
  1669. afterEach(async () => {
  1670. server.close();
  1671. await closeWindow(w);
  1672. w = null as unknown as BrowserWindow;
  1673. server = null as unknown as http.Server;
  1674. });
  1675. it('calling preconnect() connects to the server', async () => {
  1676. w = new BrowserWindow({ show: false });
  1677. w.webContents.on('did-start-navigation', (event, url) => {
  1678. w.webContents.session.preconnect({ url, numSockets: 4 });
  1679. });
  1680. await w.loadURL(url);
  1681. expect(connections).to.equal(4);
  1682. });
  1683. it('does not preconnect unless requested', async () => {
  1684. w = new BrowserWindow({ show: false });
  1685. await w.loadURL(url);
  1686. expect(connections).to.equal(1);
  1687. });
  1688. it('parses <link rel=preconnect>', async () => {
  1689. w = new BrowserWindow({ show: true });
  1690. const p = emittedOnce(w.webContents.session, 'preconnect');
  1691. w.loadURL(url + '/link');
  1692. const [, preconnectUrl, allowCredentials] = await p;
  1693. expect(preconnectUrl).to.equal('http://example.com/');
  1694. expect(allowCredentials).to.be.true('allowCredentials');
  1695. });
  1696. });
  1697. describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
  1698. let w = null as unknown as BrowserWindow;
  1699. beforeEach(() => {
  1700. w = new BrowserWindow({ show: false });
  1701. });
  1702. afterEach(async () => {
  1703. await closeWindow(w);
  1704. w = null as unknown as BrowserWindow;
  1705. });
  1706. ifit(process.platform === 'darwin')('on macOS', () => {
  1707. it('allows changing cursor auto-hiding', () => {
  1708. expect(() => {
  1709. w.setAutoHideCursor(false);
  1710. w.setAutoHideCursor(true);
  1711. }).to.not.throw();
  1712. });
  1713. });
  1714. ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
  1715. it('is not available', () => {
  1716. expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
  1717. });
  1718. });
  1719. });
  1720. ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
  1721. afterEach(closeAllWindows);
  1722. it('does not throw', () => {
  1723. const w = new BrowserWindow({ show: false });
  1724. expect(() => {
  1725. w.setWindowButtonVisibility(true);
  1726. w.setWindowButtonVisibility(false);
  1727. }).to.not.throw();
  1728. });
  1729. it('changes window button visibility for normal window', () => {
  1730. const w = new BrowserWindow({ show: false });
  1731. expect(w._getWindowButtonVisibility()).to.equal(true);
  1732. w.setWindowButtonVisibility(false);
  1733. expect(w._getWindowButtonVisibility()).to.equal(false);
  1734. w.setWindowButtonVisibility(true);
  1735. expect(w._getWindowButtonVisibility()).to.equal(true);
  1736. });
  1737. it('changes window button visibility for frameless window', () => {
  1738. const w = new BrowserWindow({ show: false, frame: false });
  1739. expect(w._getWindowButtonVisibility()).to.equal(false);
  1740. w.setWindowButtonVisibility(true);
  1741. expect(w._getWindowButtonVisibility()).to.equal(true);
  1742. w.setWindowButtonVisibility(false);
  1743. expect(w._getWindowButtonVisibility()).to.equal(false);
  1744. });
  1745. it('changes window button visibility for hiddenInset window', () => {
  1746. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  1747. expect(w._getWindowButtonVisibility()).to.equal(true);
  1748. w.setWindowButtonVisibility(false);
  1749. expect(w._getWindowButtonVisibility()).to.equal(false);
  1750. w.setWindowButtonVisibility(true);
  1751. expect(w._getWindowButtonVisibility()).to.equal(true);
  1752. });
  1753. // Buttons of customButtonsOnHover are always hidden unless hovered.
  1754. it('does not change window button visibility for customButtonsOnHover window', () => {
  1755. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
  1756. expect(w._getWindowButtonVisibility()).to.equal(false);
  1757. w.setWindowButtonVisibility(true);
  1758. expect(w._getWindowButtonVisibility()).to.equal(false);
  1759. w.setWindowButtonVisibility(false);
  1760. expect(w._getWindowButtonVisibility()).to.equal(false);
  1761. });
  1762. it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
  1763. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
  1764. expect(w._getWindowButtonVisibility()).to.equal(true);
  1765. w.setWindowButtonVisibility(false);
  1766. expect(w._getWindowButtonVisibility()).to.equal(false);
  1767. const enterFS = emittedOnce(w, 'enter-full-screen');
  1768. w.setFullScreen(true);
  1769. await enterFS;
  1770. const leaveFS = emittedOnce(w, 'leave-full-screen');
  1771. w.setFullScreen(false);
  1772. await leaveFS;
  1773. w.setWindowButtonVisibility(true);
  1774. expect(w._getWindowButtonVisibility()).to.equal(true);
  1775. });
  1776. it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
  1777. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  1778. expect(w._getWindowButtonVisibility()).to.equal(true);
  1779. w.setWindowButtonVisibility(false);
  1780. expect(w._getWindowButtonVisibility()).to.equal(false);
  1781. const enterFS = emittedOnce(w, 'enter-full-screen');
  1782. w.setFullScreen(true);
  1783. await enterFS;
  1784. const leaveFS = emittedOnce(w, 'leave-full-screen');
  1785. w.setFullScreen(false);
  1786. await leaveFS;
  1787. w.setWindowButtonVisibility(true);
  1788. expect(w._getWindowButtonVisibility()).to.equal(true);
  1789. });
  1790. });
  1791. ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
  1792. let appProcess: childProcess.ChildProcessWithoutNullStreams | childProcess.ChildProcess | undefined;
  1793. afterEach(() => {
  1794. if (appProcess && !appProcess.killed) {
  1795. appProcess.kill();
  1796. appProcess = undefined;
  1797. }
  1798. closeAllWindows();
  1799. });
  1800. it('allows setting, changing, and removing the vibrancy', () => {
  1801. const w = new BrowserWindow({ show: false });
  1802. expect(() => {
  1803. w.setVibrancy('light');
  1804. w.setVibrancy('dark');
  1805. w.setVibrancy(null);
  1806. w.setVibrancy('ultra-dark');
  1807. w.setVibrancy('' as any);
  1808. }).to.not.throw();
  1809. });
  1810. it('does not crash if vibrancy is set to an invalid value', () => {
  1811. const w = new BrowserWindow({ show: false });
  1812. expect(() => {
  1813. w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
  1814. }).to.not.throw();
  1815. });
  1816. // TODO(nornagon): disabled due to flakiness.
  1817. it.skip('Allows setting a transparent window via CSS', async () => {
  1818. const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent');
  1819. appProcess = childProcess.spawn(process.execPath, [appPath], {
  1820. stdio: 'inherit'
  1821. });
  1822. const [code] = await emittedOnce(appProcess, 'exit');
  1823. expect(code).to.equal(0);
  1824. });
  1825. });
  1826. ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
  1827. const pos = { x: 10, y: 10 };
  1828. afterEach(closeAllWindows);
  1829. describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
  1830. it('gets position property for "hidden" titleBarStyle', () => {
  1831. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1832. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1833. });
  1834. it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
  1835. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1836. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1837. });
  1838. });
  1839. describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
  1840. it('sets position property for "hidden" titleBarStyle', () => {
  1841. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1842. const newPos = { x: 20, y: 20 };
  1843. w.setTrafficLightPosition(newPos);
  1844. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1845. });
  1846. it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
  1847. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1848. const newPos = { x: 20, y: 20 };
  1849. w.setTrafficLightPosition(newPos);
  1850. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1851. });
  1852. });
  1853. });
  1854. ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
  1855. afterEach(closeAllWindows);
  1856. it('supports setting the app details', () => {
  1857. const w = new BrowserWindow({ show: false });
  1858. const iconPath = path.join(fixtures, 'assets', 'icon.ico');
  1859. expect(() => {
  1860. w.setAppDetails({ appId: 'my.app.id' });
  1861. w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
  1862. w.setAppDetails({ appIconPath: iconPath });
  1863. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
  1864. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
  1865. w.setAppDetails({ relaunchDisplayName: 'My app name' });
  1866. w.setAppDetails({
  1867. appId: 'my.app.id',
  1868. appIconPath: iconPath,
  1869. appIconIndex: 0,
  1870. relaunchCommand: 'my-app.exe arg1 arg2',
  1871. relaunchDisplayName: 'My app name'
  1872. });
  1873. w.setAppDetails({});
  1874. }).to.not.throw();
  1875. expect(() => {
  1876. (w.setAppDetails as any)();
  1877. }).to.throw('Insufficient number of arguments.');
  1878. });
  1879. });
  1880. describe('BrowserWindow.fromId(id)', () => {
  1881. afterEach(closeAllWindows);
  1882. it('returns the window with id', () => {
  1883. const w = new BrowserWindow({ show: false });
  1884. expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
  1885. });
  1886. });
  1887. describe('Opening a BrowserWindow from a link', () => {
  1888. let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
  1889. afterEach(() => {
  1890. if (appProcess && !appProcess.killed) {
  1891. appProcess.kill();
  1892. appProcess = undefined;
  1893. }
  1894. });
  1895. it('can properly open and load a new window from a link', async () => {
  1896. const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
  1897. appProcess = childProcess.spawn(process.execPath, [appPath]);
  1898. const [code] = await emittedOnce(appProcess, 'exit');
  1899. expect(code).to.equal(0);
  1900. });
  1901. });
  1902. describe('BrowserWindow.fromWebContents(webContents)', () => {
  1903. afterEach(closeAllWindows);
  1904. it('returns the window with the webContents', () => {
  1905. const w = new BrowserWindow({ show: false });
  1906. const found = BrowserWindow.fromWebContents(w.webContents);
  1907. expect(found!.id).to.equal(w.id);
  1908. });
  1909. it('returns null for webContents without a BrowserWindow', () => {
  1910. const contents = (webContents as any).create({});
  1911. try {
  1912. expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
  1913. } finally {
  1914. contents.destroy();
  1915. }
  1916. });
  1917. it('returns the correct window for a BrowserView webcontents', async () => {
  1918. const w = new BrowserWindow({ show: false });
  1919. const bv = new BrowserView();
  1920. w.setBrowserView(bv);
  1921. defer(() => {
  1922. w.removeBrowserView(bv);
  1923. (bv.webContents as any).destroy();
  1924. });
  1925. await bv.webContents.loadURL('about:blank');
  1926. expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
  1927. });
  1928. it('returns the correct window for a WebView webcontents', async () => {
  1929. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  1930. w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
  1931. // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
  1932. // https://github.com/electron/electron/issues/25413, and is not integral
  1933. // to the test.
  1934. const p = emittedOnce(w.webContents, 'did-attach-webview');
  1935. const [, webviewContents] = await emittedOnce(app, 'web-contents-created');
  1936. expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
  1937. await p;
  1938. });
  1939. it('is usable immediately on browser-window-created', async () => {
  1940. const w = new BrowserWindow({ show: false });
  1941. w.loadURL('about:blank');
  1942. w.webContents.executeJavaScript('window.open(""); null');
  1943. const [win, winFromWebContents] = await new Promise((resolve) => {
  1944. app.once('browser-window-created', (e, win) => {
  1945. resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
  1946. });
  1947. });
  1948. expect(winFromWebContents).to.equal(win);
  1949. });
  1950. });
  1951. describe('BrowserWindow.openDevTools()', () => {
  1952. afterEach(closeAllWindows);
  1953. it('does not crash for frameless window', () => {
  1954. const w = new BrowserWindow({ show: false, frame: false });
  1955. w.webContents.openDevTools();
  1956. });
  1957. });
  1958. describe('BrowserWindow.fromBrowserView(browserView)', () => {
  1959. afterEach(closeAllWindows);
  1960. it('returns the window with the BrowserView', () => {
  1961. const w = new BrowserWindow({ show: false });
  1962. const bv = new BrowserView();
  1963. w.setBrowserView(bv);
  1964. defer(() => {
  1965. w.removeBrowserView(bv);
  1966. (bv.webContents as any).destroy();
  1967. });
  1968. expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
  1969. });
  1970. it('returns the window when there are multiple BrowserViews', () => {
  1971. const w = new BrowserWindow({ show: false });
  1972. const bv1 = new BrowserView();
  1973. w.addBrowserView(bv1);
  1974. const bv2 = new BrowserView();
  1975. w.addBrowserView(bv2);
  1976. defer(() => {
  1977. w.removeBrowserView(bv1);
  1978. w.removeBrowserView(bv2);
  1979. (bv1.webContents as any).destroy();
  1980. (bv2.webContents as any).destroy();
  1981. });
  1982. expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
  1983. expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
  1984. });
  1985. it('returns undefined if not attached', () => {
  1986. const bv = new BrowserView();
  1987. defer(() => {
  1988. (bv.webContents as any).destroy();
  1989. });
  1990. expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
  1991. });
  1992. });
  1993. describe('BrowserWindow.setOpacity(opacity)', () => {
  1994. afterEach(closeAllWindows);
  1995. ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
  1996. it('make window with initial opacity', () => {
  1997. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  1998. expect(w.getOpacity()).to.equal(0.5);
  1999. });
  2000. it('allows setting the opacity', () => {
  2001. const w = new BrowserWindow({ show: false });
  2002. expect(() => {
  2003. w.setOpacity(0.0);
  2004. expect(w.getOpacity()).to.equal(0.0);
  2005. w.setOpacity(0.5);
  2006. expect(w.getOpacity()).to.equal(0.5);
  2007. w.setOpacity(1.0);
  2008. expect(w.getOpacity()).to.equal(1.0);
  2009. }).to.not.throw();
  2010. });
  2011. it('clamps opacity to [0.0...1.0]', () => {
  2012. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  2013. w.setOpacity(100);
  2014. expect(w.getOpacity()).to.equal(1.0);
  2015. w.setOpacity(-100);
  2016. expect(w.getOpacity()).to.equal(0.0);
  2017. });
  2018. });
  2019. ifdescribe(process.platform === 'linux')(('Linux'), () => {
  2020. it('sets 1 regardless of parameter', () => {
  2021. const w = new BrowserWindow({ show: false });
  2022. w.setOpacity(0);
  2023. expect(w.getOpacity()).to.equal(1.0);
  2024. w.setOpacity(0.5);
  2025. expect(w.getOpacity()).to.equal(1.0);
  2026. });
  2027. });
  2028. });
  2029. describe('BrowserWindow.setShape(rects)', () => {
  2030. afterEach(closeAllWindows);
  2031. it('allows setting shape', () => {
  2032. const w = new BrowserWindow({ show: false });
  2033. expect(() => {
  2034. w.setShape([]);
  2035. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
  2036. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
  2037. w.setShape([]);
  2038. }).to.not.throw();
  2039. });
  2040. });
  2041. describe('"useContentSize" option', () => {
  2042. afterEach(closeAllWindows);
  2043. it('make window created with content size when used', () => {
  2044. const w = new BrowserWindow({
  2045. show: false,
  2046. width: 400,
  2047. height: 400,
  2048. useContentSize: true
  2049. });
  2050. const contentSize = w.getContentSize();
  2051. expect(contentSize).to.deep.equal([400, 400]);
  2052. });
  2053. it('make window created with window size when not used', () => {
  2054. const w = new BrowserWindow({
  2055. show: false,
  2056. width: 400,
  2057. height: 400
  2058. });
  2059. const size = w.getSize();
  2060. expect(size).to.deep.equal([400, 400]);
  2061. });
  2062. it('works for a frameless window', () => {
  2063. const w = new BrowserWindow({
  2064. show: false,
  2065. frame: false,
  2066. width: 400,
  2067. height: 400,
  2068. useContentSize: true
  2069. });
  2070. const contentSize = w.getContentSize();
  2071. expect(contentSize).to.deep.equal([400, 400]);
  2072. const size = w.getSize();
  2073. expect(size).to.deep.equal([400, 400]);
  2074. });
  2075. });
  2076. ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => {
  2077. const testWindowsOverlay = async (style: any) => {
  2078. const w = new BrowserWindow({
  2079. show: false,
  2080. width: 400,
  2081. height: 400,
  2082. titleBarStyle: style,
  2083. webPreferences: {
  2084. nodeIntegration: true,
  2085. contextIsolation: false
  2086. },
  2087. titleBarOverlay: true
  2088. });
  2089. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2090. if (process.platform === 'darwin') {
  2091. await w.loadFile(overlayHTML);
  2092. } else {
  2093. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  2094. await w.loadFile(overlayHTML);
  2095. await overlayReady;
  2096. }
  2097. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2098. expect(overlayEnabled).to.be.true('overlayEnabled');
  2099. const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2100. expect(overlayRect.y).to.equal(0);
  2101. if (process.platform === 'darwin') {
  2102. expect(overlayRect.x).to.be.greaterThan(0);
  2103. } else {
  2104. expect(overlayRect.x).to.equal(0);
  2105. }
  2106. expect(overlayRect.width).to.be.greaterThan(0);
  2107. expect(overlayRect.height).to.be.greaterThan(0);
  2108. const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
  2109. expect(cssOverlayRect).to.deep.equal(overlayRect);
  2110. const geometryChange = emittedOnce(ipcMain, 'geometrychange');
  2111. w.setBounds({ width: 800 });
  2112. const [, newOverlayRect] = await geometryChange;
  2113. expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
  2114. };
  2115. afterEach(async () => {
  2116. await closeAllWindows();
  2117. ipcMain.removeAllListeners('geometrychange');
  2118. });
  2119. it('creates browser window with hidden title bar', () => {
  2120. const w = new BrowserWindow({
  2121. show: false,
  2122. width: 400,
  2123. height: 400,
  2124. titleBarStyle: 'hidden'
  2125. });
  2126. const contentSize = w.getContentSize();
  2127. expect(contentSize).to.deep.equal([400, 400]);
  2128. });
  2129. ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
  2130. const w = new BrowserWindow({
  2131. show: false,
  2132. width: 400,
  2133. height: 400,
  2134. titleBarStyle: 'hiddenInset'
  2135. });
  2136. const contentSize = w.getContentSize();
  2137. expect(contentSize).to.deep.equal([400, 400]);
  2138. });
  2139. it('sets Window Control Overlay with hidden title bar', async () => {
  2140. await testWindowsOverlay('hidden');
  2141. });
  2142. ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
  2143. await testWindowsOverlay('hiddenInset');
  2144. });
  2145. ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
  2146. let w: BrowserWindow;
  2147. beforeEach(() => {
  2148. w = new BrowserWindow({
  2149. show: false,
  2150. webPreferences: {
  2151. nodeIntegration: true,
  2152. contextIsolation: false
  2153. },
  2154. titleBarOverlay: {
  2155. color: '#0000f0',
  2156. symbolColor: '#ffffff'
  2157. },
  2158. titleBarStyle: 'hiddenInset'
  2159. });
  2160. });
  2161. afterEach(async () => {
  2162. await closeAllWindows();
  2163. });
  2164. it('does not crash changing minimizability ', () => {
  2165. expect(() => {
  2166. w.setMinimizable(false);
  2167. }).to.not.throw();
  2168. });
  2169. it('does not crash changing maximizability', () => {
  2170. expect(() => {
  2171. w.setMaximizable(false);
  2172. }).to.not.throw();
  2173. });
  2174. });
  2175. });
  2176. ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => {
  2177. const testWindowsOverlayHeight = async (size: any) => {
  2178. const w = new BrowserWindow({
  2179. show: false,
  2180. width: 400,
  2181. height: 400,
  2182. titleBarStyle: 'hidden',
  2183. webPreferences: {
  2184. nodeIntegration: true,
  2185. contextIsolation: false
  2186. },
  2187. titleBarOverlay: {
  2188. height: size
  2189. }
  2190. });
  2191. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2192. if (process.platform === 'darwin') {
  2193. await w.loadFile(overlayHTML);
  2194. } else {
  2195. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  2196. await w.loadFile(overlayHTML);
  2197. await overlayReady;
  2198. }
  2199. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2200. expect(overlayEnabled).to.be.true('overlayEnabled');
  2201. const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2202. if (!w.isMaximized()) {
  2203. const maximize = emittedOnce(w, 'maximize');
  2204. w.show();
  2205. w.maximize();
  2206. await maximize;
  2207. }
  2208. expect(w.isMaximized()).to.be.true('not maximized');
  2209. const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2210. expect(overlayRectPreMax.y).to.equal(0);
  2211. if (process.platform === 'darwin') {
  2212. expect(overlayRectPreMax.x).to.be.greaterThan(0);
  2213. } else {
  2214. expect(overlayRectPreMax.x).to.equal(0);
  2215. }
  2216. expect(overlayRectPreMax.width).to.be.greaterThan(0);
  2217. expect(overlayRectPreMax.height).to.equal(size);
  2218. // Confirm that maximization only affected the height of the buttons and not the title bar
  2219. expect(overlayRectPostMax.height).to.equal(size);
  2220. };
  2221. afterEach(async () => {
  2222. await closeAllWindows();
  2223. ipcMain.removeAllListeners('geometrychange');
  2224. });
  2225. it('sets Window Control Overlay with title bar height of 40', async () => {
  2226. await testWindowsOverlayHeight(40);
  2227. });
  2228. });
  2229. ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => {
  2230. afterEach(async () => {
  2231. await closeAllWindows();
  2232. ipcMain.removeAllListeners('geometrychange');
  2233. });
  2234. it('does not crash when an invalid titleBarStyle was initially set', () => {
  2235. const win = new BrowserWindow({
  2236. show: false,
  2237. webPreferences: {
  2238. nodeIntegration: true,
  2239. contextIsolation: false
  2240. },
  2241. titleBarOverlay: {
  2242. color: '#0000f0',
  2243. symbolColor: '#ffffff'
  2244. },
  2245. titleBarStyle: 'hiddenInset'
  2246. });
  2247. expect(() => {
  2248. win.setTitleBarOverlay({
  2249. color: '#000000'
  2250. });
  2251. }).to.not.throw();
  2252. });
  2253. it('correctly updates the height of the overlay', async () => {
  2254. const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
  2255. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2256. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  2257. await w.loadFile(overlayHTML);
  2258. if (firstRun) {
  2259. await overlayReady;
  2260. }
  2261. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2262. expect(overlayEnabled).to.be.true('overlayEnabled');
  2263. const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2264. if (!w.isMaximized()) {
  2265. const maximize = emittedOnce(w, 'maximize');
  2266. w.show();
  2267. w.maximize();
  2268. await maximize;
  2269. }
  2270. expect(w.isMaximized()).to.be.true('not maximized');
  2271. const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2272. expect(x).to.equal(0);
  2273. expect(y).to.equal(0);
  2274. expect(width).to.be.greaterThan(0);
  2275. expect(height).to.equal(size);
  2276. expect(preMaxHeight).to.equal(size);
  2277. };
  2278. const INITIAL_SIZE = 40;
  2279. const w = new BrowserWindow({
  2280. show: false,
  2281. width: 400,
  2282. height: 400,
  2283. titleBarStyle: 'hidden',
  2284. webPreferences: {
  2285. nodeIntegration: true,
  2286. contextIsolation: false
  2287. },
  2288. titleBarOverlay: {
  2289. height: INITIAL_SIZE
  2290. }
  2291. });
  2292. await testOverlay(w, INITIAL_SIZE, true);
  2293. w.setTitleBarOverlay({
  2294. height: INITIAL_SIZE + 10
  2295. });
  2296. await testOverlay(w, INITIAL_SIZE + 10, false);
  2297. });
  2298. });
  2299. ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
  2300. afterEach(closeAllWindows);
  2301. it('can move the window out of screen', () => {
  2302. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2303. w.setPosition(-10, 50);
  2304. const after = w.getPosition();
  2305. expect(after).to.deep.equal([-10, 50]);
  2306. });
  2307. it('cannot move the window behind menu bar', () => {
  2308. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2309. w.setPosition(-10, -10);
  2310. const after = w.getPosition();
  2311. expect(after[1]).to.be.at.least(0);
  2312. });
  2313. it('can move the window behind menu bar if it has no frame', () => {
  2314. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
  2315. w.setPosition(-10, -10);
  2316. const after = w.getPosition();
  2317. expect(after[0]).to.be.equal(-10);
  2318. expect(after[1]).to.be.equal(-10);
  2319. });
  2320. it('without it, cannot move the window out of screen', () => {
  2321. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2322. w.setPosition(-10, -10);
  2323. const after = w.getPosition();
  2324. expect(after[1]).to.be.at.least(0);
  2325. });
  2326. it('can set the window larger than screen', () => {
  2327. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2328. const size = screen.getPrimaryDisplay().size;
  2329. size.width += 100;
  2330. size.height += 100;
  2331. w.setSize(size.width, size.height);
  2332. expectBoundsEqual(w.getSize(), [size.width, size.height]);
  2333. });
  2334. it('without it, cannot set the window larger than screen', () => {
  2335. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2336. const size = screen.getPrimaryDisplay().size;
  2337. size.width += 100;
  2338. size.height += 100;
  2339. w.setSize(size.width, size.height);
  2340. expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
  2341. });
  2342. });
  2343. ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
  2344. afterEach(closeAllWindows);
  2345. it('sets the window width to the page width when used', () => {
  2346. const w = new BrowserWindow({
  2347. show: false,
  2348. width: 500,
  2349. height: 400,
  2350. zoomToPageWidth: true
  2351. });
  2352. w.maximize();
  2353. expect(w.getSize()[0]).to.equal(500);
  2354. });
  2355. });
  2356. describe('"tabbingIdentifier" option', () => {
  2357. afterEach(closeAllWindows);
  2358. it('can be set on a window', () => {
  2359. expect(() => {
  2360. /* eslint-disable no-new */
  2361. new BrowserWindow({
  2362. tabbingIdentifier: 'group1'
  2363. });
  2364. new BrowserWindow({
  2365. tabbingIdentifier: 'group2',
  2366. frame: false
  2367. });
  2368. /* eslint-enable no-new */
  2369. }).not.to.throw();
  2370. });
  2371. });
  2372. describe('"webPreferences" option', () => {
  2373. afterEach(() => { ipcMain.removeAllListeners('answer'); });
  2374. afterEach(closeAllWindows);
  2375. describe('"preload" option', () => {
  2376. const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
  2377. it(name, async () => {
  2378. const w = new BrowserWindow({
  2379. webPreferences: {
  2380. ...webPrefs,
  2381. preload: path.resolve(fixtures, 'module', 'empty.js')
  2382. },
  2383. show: false
  2384. });
  2385. w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
  2386. const [, result] = await emittedOnce(ipcMain, 'leak-result');
  2387. expect(result).to.have.property('require', 'undefined');
  2388. expect(result).to.have.property('exports', 'undefined');
  2389. expect(result).to.have.property('windowExports', 'undefined');
  2390. expect(result).to.have.property('windowPreload', 'undefined');
  2391. expect(result).to.have.property('windowRequire', 'undefined');
  2392. });
  2393. };
  2394. doesNotLeakSpec('does not leak require', {
  2395. nodeIntegration: false,
  2396. sandbox: false,
  2397. contextIsolation: false
  2398. });
  2399. doesNotLeakSpec('does not leak require when sandbox is enabled', {
  2400. nodeIntegration: false,
  2401. sandbox: true,
  2402. contextIsolation: false
  2403. });
  2404. doesNotLeakSpec('does not leak require when context isolation is enabled', {
  2405. nodeIntegration: false,
  2406. sandbox: false,
  2407. contextIsolation: true
  2408. });
  2409. doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
  2410. nodeIntegration: false,
  2411. sandbox: true,
  2412. contextIsolation: true
  2413. });
  2414. it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
  2415. let w = new BrowserWindow({
  2416. webPreferences: {
  2417. contextIsolation: false,
  2418. nodeIntegration: false,
  2419. preload: path.resolve(fixtures, 'module', 'empty.js')
  2420. },
  2421. show: false
  2422. });
  2423. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2424. const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result');
  2425. expect(notIsolated).to.have.property('globals');
  2426. w.destroy();
  2427. w = new BrowserWindow({
  2428. webPreferences: {
  2429. contextIsolation: true,
  2430. nodeIntegration: false,
  2431. preload: path.resolve(fixtures, 'module', 'empty.js')
  2432. },
  2433. show: false
  2434. });
  2435. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2436. const [, isolated] = await emittedOnce(ipcMain, 'leak-result');
  2437. expect(isolated).to.have.property('globals');
  2438. const notIsolatedGlobals = new Set(notIsolated.globals);
  2439. for (const isolatedGlobal of isolated.globals) {
  2440. notIsolatedGlobals.delete(isolatedGlobal);
  2441. }
  2442. expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
  2443. });
  2444. it('loads the script before other scripts in window', async () => {
  2445. const preload = path.join(fixtures, 'module', 'set-global.js');
  2446. const w = new BrowserWindow({
  2447. show: false,
  2448. webPreferences: {
  2449. nodeIntegration: true,
  2450. contextIsolation: false,
  2451. preload
  2452. }
  2453. });
  2454. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2455. const [, test] = await emittedOnce(ipcMain, 'answer');
  2456. expect(test).to.eql('preload');
  2457. });
  2458. it('has synchronous access to all eventual window APIs', async () => {
  2459. const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
  2460. const w = new BrowserWindow({
  2461. show: false,
  2462. webPreferences: {
  2463. nodeIntegration: true,
  2464. contextIsolation: false,
  2465. preload
  2466. }
  2467. });
  2468. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2469. const [, test] = await emittedOnce(ipcMain, 'answer');
  2470. expect(test).to.be.an('object');
  2471. expect(test.atPreload).to.be.an('array');
  2472. expect(test.atLoad).to.be.an('array');
  2473. expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
  2474. });
  2475. });
  2476. describe('session preload scripts', function () {
  2477. const preloads = [
  2478. path.join(fixtures, 'module', 'set-global-preload-1.js'),
  2479. path.join(fixtures, 'module', 'set-global-preload-2.js'),
  2480. path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
  2481. ];
  2482. const defaultSession = session.defaultSession;
  2483. beforeEach(() => {
  2484. expect(defaultSession.getPreloads()).to.deep.equal([]);
  2485. defaultSession.setPreloads(preloads);
  2486. });
  2487. afterEach(() => {
  2488. defaultSession.setPreloads([]);
  2489. });
  2490. it('can set multiple session preload script', () => {
  2491. expect(defaultSession.getPreloads()).to.deep.equal(preloads);
  2492. });
  2493. const generateSpecs = (description: string, sandbox: boolean) => {
  2494. describe(description, () => {
  2495. it('loads the script before other scripts in window including normal preloads', async () => {
  2496. const w = new BrowserWindow({
  2497. show: false,
  2498. webPreferences: {
  2499. sandbox,
  2500. preload: path.join(fixtures, 'module', 'get-global-preload.js'),
  2501. contextIsolation: false
  2502. }
  2503. });
  2504. w.loadURL('about:blank');
  2505. const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars');
  2506. expect(preload1).to.equal('preload-1');
  2507. expect(preload2).to.equal('preload-1-2');
  2508. expect(preload3).to.be.undefined('preload 3');
  2509. });
  2510. });
  2511. };
  2512. generateSpecs('without sandbox', false);
  2513. generateSpecs('with sandbox', true);
  2514. });
  2515. describe('"additionalArguments" option', () => {
  2516. it('adds extra args to process.argv in the renderer process', async () => {
  2517. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  2518. const w = new BrowserWindow({
  2519. show: false,
  2520. webPreferences: {
  2521. nodeIntegration: true,
  2522. preload,
  2523. additionalArguments: ['--my-magic-arg']
  2524. }
  2525. });
  2526. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2527. const [, argv] = await emittedOnce(ipcMain, 'answer');
  2528. expect(argv).to.include('--my-magic-arg');
  2529. });
  2530. it('adds extra value args to process.argv in the renderer process', async () => {
  2531. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  2532. const w = new BrowserWindow({
  2533. show: false,
  2534. webPreferences: {
  2535. nodeIntegration: true,
  2536. preload,
  2537. additionalArguments: ['--my-magic-arg=foo']
  2538. }
  2539. });
  2540. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2541. const [, argv] = await emittedOnce(ipcMain, 'answer');
  2542. expect(argv).to.include('--my-magic-arg=foo');
  2543. });
  2544. });
  2545. describe('"node-integration" option', () => {
  2546. it('disables node integration by default', async () => {
  2547. const preload = path.join(fixtures, 'module', 'send-later.js');
  2548. const w = new BrowserWindow({
  2549. show: false,
  2550. webPreferences: {
  2551. preload,
  2552. contextIsolation: false
  2553. }
  2554. });
  2555. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2556. const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer');
  2557. expect(typeofProcess).to.equal('undefined');
  2558. expect(typeofBuffer).to.equal('undefined');
  2559. });
  2560. });
  2561. describe('"sandbox" option', () => {
  2562. const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
  2563. let server: http.Server = null as unknown as http.Server;
  2564. let serverUrl: string = null as unknown as string;
  2565. before((done) => {
  2566. server = http.createServer((request, response) => {
  2567. switch (request.url) {
  2568. case '/cross-site':
  2569. response.end(`<html><body><h1>${request.url}</h1></body></html>`);
  2570. break;
  2571. default:
  2572. throw new Error(`unsupported endpoint: ${request.url}`);
  2573. }
  2574. }).listen(0, '127.0.0.1', () => {
  2575. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  2576. done();
  2577. });
  2578. });
  2579. after(() => {
  2580. server.close();
  2581. });
  2582. it('exposes ipcRenderer to preload script', async () => {
  2583. const w = new BrowserWindow({
  2584. show: false,
  2585. webPreferences: {
  2586. sandbox: true,
  2587. preload,
  2588. contextIsolation: false
  2589. }
  2590. });
  2591. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2592. const [, test] = await emittedOnce(ipcMain, 'answer');
  2593. expect(test).to.equal('preload');
  2594. });
  2595. it('exposes ipcRenderer to preload script (path has special chars)', async () => {
  2596. const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
  2597. const w = new BrowserWindow({
  2598. show: false,
  2599. webPreferences: {
  2600. sandbox: true,
  2601. preload: preloadSpecialChars,
  2602. contextIsolation: false
  2603. }
  2604. });
  2605. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2606. const [, test] = await emittedOnce(ipcMain, 'answer');
  2607. expect(test).to.equal('preload');
  2608. });
  2609. it('exposes "loaded" event to preload script', async () => {
  2610. const w = new BrowserWindow({
  2611. show: false,
  2612. webPreferences: {
  2613. sandbox: true,
  2614. preload
  2615. }
  2616. });
  2617. w.loadURL('about:blank');
  2618. await emittedOnce(ipcMain, 'process-loaded');
  2619. });
  2620. it('exposes "exit" event to preload script', async () => {
  2621. const w = new BrowserWindow({
  2622. show: false,
  2623. webPreferences: {
  2624. sandbox: true,
  2625. preload,
  2626. contextIsolation: false
  2627. }
  2628. });
  2629. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
  2630. const pageUrl = 'file://' + htmlPath;
  2631. w.loadURL(pageUrl);
  2632. const [, url] = await emittedOnce(ipcMain, 'answer');
  2633. const expectedUrl = process.platform === 'win32'
  2634. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2635. : pageUrl;
  2636. expect(url).to.equal(expectedUrl);
  2637. });
  2638. it('should open windows in same domain with cross-scripting enabled', async () => {
  2639. const w = new BrowserWindow({
  2640. show: true,
  2641. webPreferences: {
  2642. sandbox: true,
  2643. preload,
  2644. contextIsolation: false
  2645. }
  2646. });
  2647. w.webContents.setWindowOpenHandler(() => ({
  2648. action: 'allow',
  2649. overrideBrowserWindowOptions: {
  2650. webPreferences: {
  2651. preload
  2652. }
  2653. }
  2654. }));
  2655. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
  2656. const pageUrl = 'file://' + htmlPath;
  2657. const answer = emittedOnce(ipcMain, 'answer');
  2658. w.loadURL(pageUrl);
  2659. const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window');
  2660. const expectedUrl = process.platform === 'win32'
  2661. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2662. : pageUrl;
  2663. expect(url).to.equal(expectedUrl);
  2664. expect(frameName).to.equal('popup!');
  2665. expect(options.width).to.equal(500);
  2666. expect(options.height).to.equal(600);
  2667. const [, html] = await answer;
  2668. expect(html).to.equal('<h1>scripting from opener</h1>');
  2669. });
  2670. it('should open windows in another domain with cross-scripting disabled', async () => {
  2671. const w = new BrowserWindow({
  2672. show: true,
  2673. webPreferences: {
  2674. sandbox: true,
  2675. preload,
  2676. contextIsolation: false
  2677. }
  2678. });
  2679. w.webContents.setWindowOpenHandler(() => ({
  2680. action: 'allow',
  2681. overrideBrowserWindowOptions: {
  2682. webPreferences: {
  2683. preload
  2684. }
  2685. }
  2686. }));
  2687. w.loadFile(
  2688. path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
  2689. { search: 'window-open-external' }
  2690. );
  2691. // Wait for a message from the main window saying that it's ready.
  2692. await emittedOnce(ipcMain, 'opener-loaded');
  2693. // Ask the opener to open a popup with window.opener.
  2694. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
  2695. w.webContents.send('open-the-popup', expectedPopupUrl);
  2696. // The page is going to open a popup that it won't be able to close.
  2697. // We have to close it from here later.
  2698. const [, popupWindow] = await emittedOnce(app, 'browser-window-created');
  2699. // Ask the popup window for details.
  2700. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded');
  2701. popupWindow.webContents.send('provide-details');
  2702. const [, openerIsNull, , locationHref] = await detailsAnswer;
  2703. expect(openerIsNull).to.be.false('window.opener is null');
  2704. expect(locationHref).to.equal(expectedPopupUrl);
  2705. // Ask the page to access the popup.
  2706. const touchPopupResult = emittedOnce(ipcMain, 'answer');
  2707. w.webContents.send('touch-the-popup');
  2708. const [, popupAccessMessage] = await touchPopupResult;
  2709. // Ask the popup to access the opener.
  2710. const touchOpenerResult = emittedOnce(ipcMain, 'answer');
  2711. popupWindow.webContents.send('touch-the-opener');
  2712. const [, openerAccessMessage] = await touchOpenerResult;
  2713. // We don't need the popup anymore, and its parent page can't close it,
  2714. // so let's close it from here before we run any checks.
  2715. await closeWindow(popupWindow, { assertNotWindows: false });
  2716. expect(popupAccessMessage).to.be.a('string',
  2717. 'child\'s .document is accessible from its parent window');
  2718. expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
  2719. expect(openerAccessMessage).to.be.a('string',
  2720. 'opener .document is accessible from a popup window');
  2721. expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
  2722. });
  2723. it('should inherit the sandbox setting in opened windows', async () => {
  2724. const w = new BrowserWindow({
  2725. show: false,
  2726. webPreferences: {
  2727. sandbox: true
  2728. }
  2729. });
  2730. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  2731. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
  2732. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2733. const [, { argv }] = await emittedOnce(ipcMain, 'answer');
  2734. expect(argv).to.include('--enable-sandbox');
  2735. });
  2736. it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
  2737. const w = new BrowserWindow({
  2738. show: false,
  2739. webPreferences: {
  2740. sandbox: true
  2741. }
  2742. });
  2743. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  2744. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
  2745. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2746. const [[, childWebContents]] = await Promise.all([
  2747. emittedOnce(app, 'web-contents-created'),
  2748. emittedOnce(ipcMain, 'answer')
  2749. ]);
  2750. const webPreferences = childWebContents.getLastWebPreferences();
  2751. expect(webPreferences.contextIsolation).to.equal(false);
  2752. });
  2753. it('should set ipc event sender correctly', async () => {
  2754. const w = new BrowserWindow({
  2755. show: false,
  2756. webPreferences: {
  2757. sandbox: true,
  2758. preload,
  2759. contextIsolation: false
  2760. }
  2761. });
  2762. let childWc: WebContents | null = null;
  2763. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
  2764. w.webContents.on('did-create-window', (win) => {
  2765. childWc = win.webContents;
  2766. expect(w.webContents).to.not.equal(childWc);
  2767. });
  2768. ipcMain.once('parent-ready', function (event) {
  2769. expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
  2770. event.sender.send('verified');
  2771. });
  2772. ipcMain.once('child-ready', function (event) {
  2773. expect(childWc).to.not.be.null('child webcontents should be available');
  2774. expect(event.sender).to.equal(childWc, 'sender should be the child');
  2775. event.sender.send('verified');
  2776. });
  2777. const done = Promise.all([
  2778. 'parent-answer',
  2779. 'child-answer'
  2780. ].map(name => emittedOnce(ipcMain, name)));
  2781. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
  2782. await done;
  2783. });
  2784. describe('event handling', () => {
  2785. let w: BrowserWindow = null as unknown as BrowserWindow;
  2786. beforeEach(() => {
  2787. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  2788. });
  2789. it('works for window events', async () => {
  2790. const pageTitleUpdated = emittedOnce(w, 'page-title-updated');
  2791. w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
  2792. await pageTitleUpdated;
  2793. });
  2794. it('works for stop events', async () => {
  2795. const done = Promise.all([
  2796. 'did-navigate',
  2797. 'did-fail-load',
  2798. 'did-stop-loading'
  2799. ].map(name => emittedOnce(w.webContents, name)));
  2800. w.loadURL('data:text/html,<script>stop()</script>');
  2801. await done;
  2802. });
  2803. it('works for web contents events', async () => {
  2804. const done = Promise.all([
  2805. 'did-finish-load',
  2806. 'did-frame-finish-load',
  2807. 'did-navigate-in-page',
  2808. 'will-navigate',
  2809. 'did-start-loading',
  2810. 'did-stop-loading',
  2811. 'did-frame-finish-load',
  2812. 'dom-ready'
  2813. ].map(name => emittedOnce(w.webContents, name)));
  2814. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
  2815. await done;
  2816. });
  2817. });
  2818. it('validates process APIs access in sandboxed renderer', async () => {
  2819. const w = new BrowserWindow({
  2820. show: false,
  2821. webPreferences: {
  2822. sandbox: true,
  2823. preload,
  2824. contextIsolation: false
  2825. }
  2826. });
  2827. w.webContents.once('preload-error', (event, preloadPath, error) => {
  2828. throw error;
  2829. });
  2830. process.env.sandboxmain = 'foo';
  2831. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2832. const [, test] = await emittedOnce(ipcMain, 'answer');
  2833. expect(test.hasCrash).to.be.true('has crash');
  2834. expect(test.hasHang).to.be.true('has hang');
  2835. expect(test.heapStatistics).to.be.an('object');
  2836. expect(test.blinkMemoryInfo).to.be.an('object');
  2837. expect(test.processMemoryInfo).to.be.an('object');
  2838. expect(test.systemVersion).to.be.a('string');
  2839. expect(test.cpuUsage).to.be.an('object');
  2840. expect(test.ioCounters).to.be.an('object');
  2841. expect(test.uptime).to.be.a('number');
  2842. expect(test.arch).to.equal(process.arch);
  2843. expect(test.platform).to.equal(process.platform);
  2844. expect(test.env).to.deep.equal(process.env);
  2845. expect(test.execPath).to.equal(process.helperExecPath);
  2846. expect(test.sandboxed).to.be.true('sandboxed');
  2847. expect(test.contextIsolated).to.be.false('contextIsolated');
  2848. expect(test.type).to.equal('renderer');
  2849. expect(test.version).to.equal(process.version);
  2850. expect(test.versions).to.deep.equal(process.versions);
  2851. expect(test.contextId).to.be.a('string');
  2852. if (process.platform === 'linux' && test.osSandbox) {
  2853. expect(test.creationTime).to.be.null('creation time');
  2854. expect(test.systemMemoryInfo).to.be.null('system memory info');
  2855. } else {
  2856. expect(test.creationTime).to.be.a('number');
  2857. expect(test.systemMemoryInfo).to.be.an('object');
  2858. }
  2859. });
  2860. it('webview in sandbox renderer', async () => {
  2861. const w = new BrowserWindow({
  2862. show: false,
  2863. webPreferences: {
  2864. sandbox: true,
  2865. preload,
  2866. webviewTag: true,
  2867. contextIsolation: false
  2868. }
  2869. });
  2870. const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
  2871. const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready');
  2872. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  2873. const [, webContents] = await didAttachWebview;
  2874. const [, id] = await webviewDomReady;
  2875. expect(webContents.id).to.equal(id);
  2876. });
  2877. });
  2878. describe('child windows', () => {
  2879. let w: BrowserWindow = null as unknown as BrowserWindow;
  2880. beforeEach(() => {
  2881. w = new BrowserWindow({
  2882. show: false,
  2883. webPreferences: {
  2884. nodeIntegration: true,
  2885. // tests relies on preloads in opened windows
  2886. nodeIntegrationInSubFrames: true,
  2887. contextIsolation: false
  2888. }
  2889. });
  2890. });
  2891. it('opens window of about:blank with cross-scripting enabled', async () => {
  2892. const answer = emittedOnce(ipcMain, 'answer');
  2893. w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
  2894. const [, content] = await answer;
  2895. expect(content).to.equal('Hello');
  2896. });
  2897. it('opens window of same domain with cross-scripting enabled', async () => {
  2898. const answer = emittedOnce(ipcMain, 'answer');
  2899. w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
  2900. const [, content] = await answer;
  2901. expect(content).to.equal('Hello');
  2902. });
  2903. it('blocks accessing cross-origin frames', async () => {
  2904. const answer = emittedOnce(ipcMain, 'answer');
  2905. w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
  2906. const [, content] = await answer;
  2907. expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
  2908. });
  2909. it('opens window from <iframe> tags', async () => {
  2910. const answer = emittedOnce(ipcMain, 'answer');
  2911. w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
  2912. const [, content] = await answer;
  2913. expect(content).to.equal('Hello');
  2914. });
  2915. it('opens window with cross-scripting enabled from isolated context', async () => {
  2916. const w = new BrowserWindow({
  2917. show: false,
  2918. webPreferences: {
  2919. preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
  2920. }
  2921. });
  2922. w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
  2923. const [, content] = await emittedOnce(ipcMain, 'answer');
  2924. expect(content).to.equal('Hello');
  2925. });
  2926. ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
  2927. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
  2928. {
  2929. const [, content] = await emittedOnce(ipcMain, 'answer');
  2930. expect(content).to.equal('function');
  2931. }
  2932. w.reload();
  2933. {
  2934. const [, content] = await emittedOnce(ipcMain, 'answer');
  2935. expect(content).to.equal('function');
  2936. }
  2937. });
  2938. it('<webview> works in a scriptable popup', async () => {
  2939. const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
  2940. const w = new BrowserWindow({
  2941. show: false,
  2942. webPreferences: {
  2943. nodeIntegrationInSubFrames: true,
  2944. webviewTag: true,
  2945. contextIsolation: false,
  2946. preload
  2947. }
  2948. });
  2949. w.webContents.setWindowOpenHandler(() => ({
  2950. action: 'allow',
  2951. overrideBrowserWindowOptions: {
  2952. show: false,
  2953. webPreferences: {
  2954. contextIsolation: false,
  2955. webviewTag: true,
  2956. nodeIntegrationInSubFrames: true,
  2957. preload
  2958. }
  2959. }
  2960. }));
  2961. const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded');
  2962. w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
  2963. await webviewLoaded;
  2964. });
  2965. it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
  2966. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  2967. w.webContents.setWindowOpenHandler(() => ({
  2968. action: 'allow',
  2969. overrideBrowserWindowOptions: {
  2970. webPreferences: {
  2971. preload: preloadPath,
  2972. contextIsolation: false
  2973. }
  2974. }
  2975. }));
  2976. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2977. const [[, childWebContents]] = await Promise.all([
  2978. emittedOnce(app, 'web-contents-created'),
  2979. emittedOnce(ipcMain, 'answer')
  2980. ]);
  2981. const webPreferences = childWebContents.getLastWebPreferences();
  2982. expect(webPreferences.contextIsolation).to.equal(false);
  2983. });
  2984. describe('window.location', () => {
  2985. const protocols = [
  2986. ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
  2987. ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
  2988. ];
  2989. beforeEach(() => {
  2990. for (const [scheme, path] of protocols) {
  2991. protocol.registerBufferProtocol(scheme, (request, callback) => {
  2992. callback({
  2993. mimeType: 'text/html',
  2994. data: fs.readFileSync(path)
  2995. });
  2996. });
  2997. }
  2998. });
  2999. afterEach(() => {
  3000. for (const [scheme] of protocols) {
  3001. protocol.unregisterProtocol(scheme);
  3002. }
  3003. });
  3004. it('retains the original web preferences when window.location is changed to a new origin', async () => {
  3005. const w = new BrowserWindow({
  3006. show: false,
  3007. webPreferences: {
  3008. // test relies on preloads in opened window
  3009. nodeIntegrationInSubFrames: true,
  3010. contextIsolation: false
  3011. }
  3012. });
  3013. w.webContents.setWindowOpenHandler(() => ({
  3014. action: 'allow',
  3015. overrideBrowserWindowOptions: {
  3016. webPreferences: {
  3017. preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
  3018. contextIsolation: false,
  3019. nodeIntegrationInSubFrames: true
  3020. }
  3021. }
  3022. }));
  3023. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  3024. const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer');
  3025. expect(nodeIntegration).to.be.false();
  3026. expect(typeofProcess).to.eql('undefined');
  3027. });
  3028. it('window.opener is not null when window.location is changed to a new origin', async () => {
  3029. const w = new BrowserWindow({
  3030. show: false,
  3031. webPreferences: {
  3032. // test relies on preloads in opened window
  3033. nodeIntegrationInSubFrames: true
  3034. }
  3035. });
  3036. w.webContents.setWindowOpenHandler(() => ({
  3037. action: 'allow',
  3038. overrideBrowserWindowOptions: {
  3039. webPreferences: {
  3040. preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
  3041. }
  3042. }
  3043. }));
  3044. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  3045. const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer');
  3046. expect(windowOpenerIsNull).to.be.false('window.opener is null');
  3047. });
  3048. });
  3049. });
  3050. describe('"disableHtmlFullscreenWindowResize" option', () => {
  3051. it('prevents window from resizing when set', async () => {
  3052. const w = new BrowserWindow({
  3053. show: false,
  3054. webPreferences: {
  3055. disableHtmlFullscreenWindowResize: true
  3056. }
  3057. });
  3058. await w.loadURL('about:blank');
  3059. const size = w.getSize();
  3060. const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen');
  3061. w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  3062. await enterHtmlFullScreen;
  3063. expect(w.getSize()).to.deep.equal(size);
  3064. });
  3065. });
  3066. });
  3067. describe('beforeunload handler', function () {
  3068. let w: BrowserWindow = null as unknown as BrowserWindow;
  3069. beforeEach(() => {
  3070. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  3071. });
  3072. afterEach(closeAllWindows);
  3073. it('returning undefined would not prevent close', async () => {
  3074. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  3075. const wait = emittedOnce(w, 'closed');
  3076. w.close();
  3077. await wait;
  3078. });
  3079. it('returning false would prevent close', async () => {
  3080. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  3081. w.close();
  3082. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  3083. expect(proceed).to.equal(false);
  3084. });
  3085. it('returning empty string would prevent close', async () => {
  3086. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
  3087. w.close();
  3088. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  3089. expect(proceed).to.equal(false);
  3090. });
  3091. it('emits for each close attempt', async () => {
  3092. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3093. const destroyListener = () => { expect.fail('Close was not prevented'); };
  3094. w.webContents.once('destroyed', destroyListener);
  3095. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3096. // The renderer needs to report the status of beforeunload handler
  3097. // back to main process, so wait for next console message, which means
  3098. // the SuddenTerminationStatus message have been flushed.
  3099. await emittedOnce(w.webContents, 'console-message');
  3100. w.close();
  3101. await emittedOnce(w.webContents, 'before-unload-fired');
  3102. w.close();
  3103. await emittedOnce(w.webContents, 'before-unload-fired');
  3104. w.webContents.removeListener('destroyed', destroyListener);
  3105. const wait = emittedOnce(w, 'closed');
  3106. w.close();
  3107. await wait;
  3108. });
  3109. it('emits for each reload attempt', async () => {
  3110. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3111. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  3112. w.webContents.once('did-start-navigation', navigationListener);
  3113. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3114. // The renderer needs to report the status of beforeunload handler
  3115. // back to main process, so wait for next console message, which means
  3116. // the SuddenTerminationStatus message have been flushed.
  3117. await emittedOnce(w.webContents, 'console-message');
  3118. w.reload();
  3119. // Chromium does not emit 'before-unload-fired' on WebContents for
  3120. // navigations, so we have to use other ways to know if beforeunload
  3121. // is fired.
  3122. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3123. w.reload();
  3124. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3125. w.webContents.removeListener('did-start-navigation', navigationListener);
  3126. w.reload();
  3127. await emittedOnce(w.webContents, 'did-finish-load');
  3128. });
  3129. it('emits for each navigation 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.loadURL('about:blank');
  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.loadURL('about:blank');
  3144. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3145. w.webContents.removeListener('did-start-navigation', navigationListener);
  3146. await w.loadURL('about:blank');
  3147. });
  3148. });
  3149. describe('document.visibilityState/hidden', () => {
  3150. afterEach(closeAllWindows);
  3151. it('visibilityState is initially visible despite window being hidden', async () => {
  3152. const w = new BrowserWindow({
  3153. show: false,
  3154. width: 100,
  3155. height: 100,
  3156. webPreferences: {
  3157. nodeIntegration: true,
  3158. contextIsolation: false
  3159. }
  3160. });
  3161. let readyToShow = false;
  3162. w.once('ready-to-show', () => {
  3163. readyToShow = true;
  3164. });
  3165. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3166. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3167. expect(readyToShow).to.be.false('ready to show');
  3168. expect(visibilityState).to.equal('visible');
  3169. expect(hidden).to.be.false('hidden');
  3170. });
  3171. // TODO(nornagon): figure out why this is failing on windows
  3172. ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
  3173. const w = new BrowserWindow({
  3174. width: 100,
  3175. height: 100,
  3176. webPreferences: {
  3177. nodeIntegration: true,
  3178. contextIsolation: false
  3179. }
  3180. });
  3181. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3182. {
  3183. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3184. expect(visibilityState).to.equal('visible');
  3185. expect(hidden).to.be.false('hidden');
  3186. }
  3187. w.hide();
  3188. {
  3189. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3190. expect(visibilityState).to.equal('hidden');
  3191. expect(hidden).to.be.true('hidden');
  3192. }
  3193. });
  3194. // TODO(nornagon): figure out why this is failing on windows
  3195. ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
  3196. const w = new BrowserWindow({
  3197. width: 100,
  3198. height: 100,
  3199. webPreferences: {
  3200. nodeIntegration: true,
  3201. contextIsolation: false
  3202. }
  3203. });
  3204. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3205. if (process.platform === 'darwin') {
  3206. // See https://github.com/electron/electron/issues/8664
  3207. await emittedOnce(w, 'show');
  3208. }
  3209. w.hide();
  3210. w.show();
  3211. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  3212. expect(visibilityState).to.equal('visible');
  3213. });
  3214. ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
  3215. const w = new BrowserWindow({
  3216. width: 100,
  3217. height: 100,
  3218. webPreferences: {
  3219. nodeIntegration: true,
  3220. contextIsolation: false
  3221. }
  3222. });
  3223. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3224. if (process.platform === 'darwin') {
  3225. // See https://github.com/electron/electron/issues/8664
  3226. await emittedOnce(w, 'show');
  3227. }
  3228. w.hide();
  3229. w.showInactive();
  3230. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  3231. expect(visibilityState).to.equal('visible');
  3232. });
  3233. // TODO(nornagon): figure out why this is failing on windows
  3234. ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', 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. {
  3245. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3246. expect(visibilityState).to.equal('visible');
  3247. expect(hidden).to.be.false('hidden');
  3248. }
  3249. w.minimize();
  3250. {
  3251. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3252. expect(visibilityState).to.equal('hidden');
  3253. expect(hidden).to.be.true('hidden');
  3254. }
  3255. });
  3256. // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
  3257. // when we introduced the compositor recycling patch. Should figure out how to fix this
  3258. it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => {
  3259. const w = new BrowserWindow({
  3260. show: false,
  3261. width: 100,
  3262. height: 100,
  3263. webPreferences: {
  3264. backgroundThrottling: false,
  3265. nodeIntegration: true
  3266. }
  3267. });
  3268. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3269. {
  3270. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3271. expect(visibilityState).to.equal('visible');
  3272. expect(hidden).to.be.false('hidden');
  3273. }
  3274. ipcMain.once('pong', (event, visibilityState, hidden) => {
  3275. throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
  3276. });
  3277. try {
  3278. const shown1 = emittedOnce(w, 'show');
  3279. w.show();
  3280. await shown1;
  3281. const hidden = emittedOnce(w, 'hide');
  3282. w.hide();
  3283. await hidden;
  3284. const shown2 = emittedOnce(w, 'show');
  3285. w.show();
  3286. await shown2;
  3287. } finally {
  3288. ipcMain.removeAllListeners('pong');
  3289. }
  3290. });
  3291. });
  3292. ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
  3293. afterEach(closeAllWindows);
  3294. it('emits an event when window is maximized', async () => {
  3295. const w = new BrowserWindow({ show: false });
  3296. const maximize = emittedOnce(w, 'maximize');
  3297. w.show();
  3298. w.maximize();
  3299. await maximize;
  3300. });
  3301. it('emits an event when a transparent window is maximized', async () => {
  3302. const w = new BrowserWindow({
  3303. show: false,
  3304. frame: false,
  3305. transparent: true
  3306. });
  3307. const maximize = emittedOnce(w, 'maximize');
  3308. w.show();
  3309. w.maximize();
  3310. await maximize;
  3311. });
  3312. it('emits only one event when frameless window is maximized', () => {
  3313. const w = new BrowserWindow({ show: false, frame: false });
  3314. let emitted = 0;
  3315. w.on('maximize', () => emitted++);
  3316. w.show();
  3317. w.maximize();
  3318. expect(emitted).to.equal(1);
  3319. });
  3320. it('emits an event when window is unmaximized', async () => {
  3321. const w = new BrowserWindow({ show: false });
  3322. const unmaximize = emittedOnce(w, 'unmaximize');
  3323. w.show();
  3324. w.maximize();
  3325. w.unmaximize();
  3326. await unmaximize;
  3327. });
  3328. it('emits an event when a transparent window is unmaximized', async () => {
  3329. const w = new BrowserWindow({
  3330. show: false,
  3331. frame: false,
  3332. transparent: true
  3333. });
  3334. const maximize = emittedOnce(w, 'maximize');
  3335. const unmaximize = emittedOnce(w, 'unmaximize');
  3336. w.show();
  3337. w.maximize();
  3338. await maximize;
  3339. w.unmaximize();
  3340. await unmaximize;
  3341. });
  3342. it('emits an event when window is minimized', async () => {
  3343. const w = new BrowserWindow({ show: false });
  3344. const minimize = emittedOnce(w, 'minimize');
  3345. w.show();
  3346. w.minimize();
  3347. await minimize;
  3348. });
  3349. });
  3350. describe('beginFrameSubscription method', () => {
  3351. it('does not crash when callback returns nothing', (done) => {
  3352. const w = new BrowserWindow({ show: false });
  3353. let called = false;
  3354. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3355. w.webContents.on('dom-ready', () => {
  3356. w.webContents.beginFrameSubscription(function () {
  3357. // This callback might be called twice.
  3358. if (called) return;
  3359. called = true;
  3360. // Pending endFrameSubscription to next tick can reliably reproduce
  3361. // a crash which happens when nothing is returned in the callback.
  3362. setTimeout(() => {
  3363. w.webContents.endFrameSubscription();
  3364. done();
  3365. });
  3366. });
  3367. });
  3368. });
  3369. it('subscribes to frame updates', (done) => {
  3370. const w = new BrowserWindow({ show: false });
  3371. let called = false;
  3372. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3373. w.webContents.on('dom-ready', () => {
  3374. w.webContents.beginFrameSubscription(function (data) {
  3375. // This callback might be called twice.
  3376. if (called) return;
  3377. called = true;
  3378. try {
  3379. expect(data.constructor.name).to.equal('NativeImage');
  3380. expect(data.isEmpty()).to.be.false('data is empty');
  3381. done();
  3382. } catch (e) {
  3383. done(e);
  3384. } finally {
  3385. w.webContents.endFrameSubscription();
  3386. }
  3387. });
  3388. });
  3389. });
  3390. it('subscribes to frame updates (only dirty rectangle)', (done) => {
  3391. const w = new BrowserWindow({ show: false });
  3392. let called = false;
  3393. let gotInitialFullSizeFrame = false;
  3394. const [contentWidth, contentHeight] = w.getContentSize();
  3395. w.webContents.on('did-finish-load', () => {
  3396. w.webContents.beginFrameSubscription(true, (image, rect) => {
  3397. if (image.isEmpty()) {
  3398. // Chromium sometimes sends a 0x0 frame at the beginning of the
  3399. // page load.
  3400. return;
  3401. }
  3402. if (rect.height === contentHeight && rect.width === contentWidth &&
  3403. !gotInitialFullSizeFrame) {
  3404. // The initial frame is full-size, but we're looking for a call
  3405. // with just the dirty-rect. The next frame should be a smaller
  3406. // rect.
  3407. gotInitialFullSizeFrame = true;
  3408. return;
  3409. }
  3410. // This callback might be called twice.
  3411. if (called) return;
  3412. // We asked for just the dirty rectangle, so we expect to receive a
  3413. // rect smaller than the full size.
  3414. // TODO(jeremy): this is failing on windows currently; investigate.
  3415. // assert(rect.width < contentWidth || rect.height < contentHeight)
  3416. called = true;
  3417. try {
  3418. const expectedSize = rect.width * rect.height * 4;
  3419. expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
  3420. done();
  3421. } catch (e) {
  3422. done(e);
  3423. } finally {
  3424. w.webContents.endFrameSubscription();
  3425. }
  3426. });
  3427. });
  3428. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3429. });
  3430. it('throws error when subscriber is not well defined', () => {
  3431. const w = new BrowserWindow({ show: false });
  3432. expect(() => {
  3433. w.webContents.beginFrameSubscription(true, true as any);
  3434. // TODO(zcbenz): gin is weak at guessing parameter types, we should
  3435. // upstream native_mate's implementation to gin.
  3436. }).to.throw('Error processing argument at index 1, conversion failure from ');
  3437. });
  3438. });
  3439. describe('savePage method', () => {
  3440. const savePageDir = path.join(fixtures, 'save_page');
  3441. const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
  3442. const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
  3443. const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
  3444. afterEach(() => {
  3445. closeAllWindows();
  3446. try {
  3447. fs.unlinkSync(savePageCssPath);
  3448. fs.unlinkSync(savePageJsPath);
  3449. fs.unlinkSync(savePageHtmlPath);
  3450. fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
  3451. fs.rmdirSync(savePageDir);
  3452. } catch {}
  3453. });
  3454. it('should throw when passing relative paths', async () => {
  3455. const w = new BrowserWindow({ show: false });
  3456. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3457. await expect(
  3458. w.webContents.savePage('save_page.html', 'HTMLComplete')
  3459. ).to.eventually.be.rejectedWith('Path must be absolute');
  3460. await expect(
  3461. w.webContents.savePage('save_page.html', 'HTMLOnly')
  3462. ).to.eventually.be.rejectedWith('Path must be absolute');
  3463. await expect(
  3464. w.webContents.savePage('save_page.html', 'MHTML')
  3465. ).to.eventually.be.rejectedWith('Path must be absolute');
  3466. });
  3467. it('should save page to disk with HTMLOnly', async () => {
  3468. const w = new BrowserWindow({ show: false });
  3469. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3470. await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
  3471. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3472. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  3473. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  3474. });
  3475. it('should save page to disk with MHTML', async () => {
  3476. const w = new BrowserWindow({ show: false });
  3477. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3478. await w.webContents.savePage(savePageHtmlPath, 'MHTML');
  3479. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3480. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  3481. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  3482. });
  3483. it('should save page to disk with HTMLComplete', async () => {
  3484. const w = new BrowserWindow({ show: false });
  3485. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3486. await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
  3487. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3488. expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
  3489. expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
  3490. });
  3491. });
  3492. describe('BrowserWindow options argument is optional', () => {
  3493. afterEach(closeAllWindows);
  3494. it('should create a window with default size (800x600)', () => {
  3495. const w = new BrowserWindow();
  3496. expect(w.getSize()).to.deep.equal([800, 600]);
  3497. });
  3498. });
  3499. describe('BrowserWindow.restore()', () => {
  3500. afterEach(closeAllWindows);
  3501. it('should restore the previous window size', () => {
  3502. const w = new BrowserWindow({
  3503. minWidth: 800,
  3504. width: 800
  3505. });
  3506. const initialSize = w.getSize();
  3507. w.minimize();
  3508. w.restore();
  3509. expectBoundsEqual(w.getSize(), initialSize);
  3510. });
  3511. it('does not crash when restoring hidden minimized window', () => {
  3512. const w = new BrowserWindow({});
  3513. w.minimize();
  3514. w.hide();
  3515. w.show();
  3516. });
  3517. });
  3518. // TODO(dsanders11): Enable once maximize event works on Linux again on CI
  3519. ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
  3520. afterEach(closeAllWindows);
  3521. it('should show the window if it is not currently shown', async () => {
  3522. const w = new BrowserWindow({ show: false });
  3523. const hidden = emittedOnce(w, 'hide');
  3524. let shown = emittedOnce(w, 'show');
  3525. const maximize = emittedOnce(w, 'maximize');
  3526. expect(w.isVisible()).to.be.false('visible');
  3527. w.maximize();
  3528. await maximize;
  3529. await shown;
  3530. expect(w.isMaximized()).to.be.true('maximized');
  3531. expect(w.isVisible()).to.be.true('visible');
  3532. // Even if the window is already maximized
  3533. w.hide();
  3534. await hidden;
  3535. expect(w.isVisible()).to.be.false('visible');
  3536. shown = emittedOnce(w, 'show');
  3537. w.maximize();
  3538. await shown;
  3539. expect(w.isVisible()).to.be.true('visible');
  3540. });
  3541. });
  3542. describe('BrowserWindow.unmaximize()', () => {
  3543. afterEach(closeAllWindows);
  3544. it('should restore the previous window position', () => {
  3545. const w = new BrowserWindow();
  3546. const initialPosition = w.getPosition();
  3547. w.maximize();
  3548. w.unmaximize();
  3549. expectBoundsEqual(w.getPosition(), initialPosition);
  3550. });
  3551. // TODO(dsanders11): Enable once minimize event works on Linux again.
  3552. // See https://github.com/electron/electron/issues/28699
  3553. ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
  3554. const w = new BrowserWindow();
  3555. const minimize = emittedOnce(w, 'minimize');
  3556. w.minimize();
  3557. await minimize;
  3558. w.unmaximize();
  3559. await delay(1000);
  3560. expect(w.isMinimized()).to.be.true();
  3561. });
  3562. it('should not change the size or position of a normal window', async () => {
  3563. const w = new BrowserWindow();
  3564. const initialSize = w.getSize();
  3565. const initialPosition = w.getPosition();
  3566. w.unmaximize();
  3567. await delay(1000);
  3568. expectBoundsEqual(w.getSize(), initialSize);
  3569. expectBoundsEqual(w.getPosition(), initialPosition);
  3570. });
  3571. ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
  3572. const { workArea } = screen.getPrimaryDisplay();
  3573. const bounds = {
  3574. x: workArea.x,
  3575. y: workArea.y,
  3576. width: workArea.width,
  3577. height: workArea.height
  3578. };
  3579. const w = new BrowserWindow(bounds);
  3580. w.unmaximize();
  3581. await delay(1000);
  3582. expectBoundsEqual(w.getBounds(), bounds);
  3583. });
  3584. });
  3585. describe('setFullScreen(false)', () => {
  3586. afterEach(closeAllWindows);
  3587. // only applicable to windows: https://github.com/electron/electron/issues/6036
  3588. ifdescribe(process.platform === 'win32')('on windows', () => {
  3589. it('should restore a normal visible window from a fullscreen startup state', async () => {
  3590. const w = new BrowserWindow({ show: false });
  3591. await w.loadURL('about:blank');
  3592. const shown = emittedOnce(w, 'show');
  3593. // start fullscreen and hidden
  3594. w.setFullScreen(true);
  3595. w.show();
  3596. await shown;
  3597. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3598. w.setFullScreen(false);
  3599. await leftFullScreen;
  3600. expect(w.isVisible()).to.be.true('visible');
  3601. expect(w.isFullScreen()).to.be.false('fullscreen');
  3602. });
  3603. it('should keep window hidden if already in hidden state', async () => {
  3604. const w = new BrowserWindow({ show: false });
  3605. await w.loadURL('about:blank');
  3606. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3607. w.setFullScreen(false);
  3608. await leftFullScreen;
  3609. expect(w.isVisible()).to.be.false('visible');
  3610. expect(w.isFullScreen()).to.be.false('fullscreen');
  3611. });
  3612. });
  3613. ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
  3614. it('exits HTML fullscreen when window leaves fullscreen', async () => {
  3615. const w = new BrowserWindow();
  3616. await w.loadURL('about:blank');
  3617. await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  3618. await emittedOnce(w, 'enter-full-screen');
  3619. // Wait a tick for the full-screen state to 'stick'
  3620. await delay();
  3621. w.setFullScreen(false);
  3622. await emittedOnce(w, 'leave-html-full-screen');
  3623. });
  3624. });
  3625. });
  3626. describe('parent window', () => {
  3627. afterEach(closeAllWindows);
  3628. ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
  3629. const w = new BrowserWindow();
  3630. const sheetBegin = emittedOnce(w, 'sheet-begin');
  3631. // eslint-disable-next-line no-new
  3632. new BrowserWindow({
  3633. modal: true,
  3634. parent: w
  3635. });
  3636. await sheetBegin;
  3637. });
  3638. ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
  3639. const w = new BrowserWindow();
  3640. const sheet = new BrowserWindow({
  3641. modal: true,
  3642. parent: w
  3643. });
  3644. const sheetEnd = emittedOnce(w, 'sheet-end');
  3645. sheet.close();
  3646. await sheetEnd;
  3647. });
  3648. describe('parent option', () => {
  3649. it('sets parent window', () => {
  3650. const w = new BrowserWindow({ show: false });
  3651. const c = new BrowserWindow({ show: false, parent: w });
  3652. expect(c.getParentWindow()).to.equal(w);
  3653. });
  3654. it('adds window to child windows of parent', () => {
  3655. const w = new BrowserWindow({ show: false });
  3656. const c = new BrowserWindow({ show: false, parent: w });
  3657. expect(w.getChildWindows()).to.deep.equal([c]);
  3658. });
  3659. it('removes from child windows of parent when window is closed', async () => {
  3660. const w = new BrowserWindow({ show: false });
  3661. const c = new BrowserWindow({ show: false, parent: w });
  3662. const closed = emittedOnce(c, 'closed');
  3663. c.close();
  3664. await closed;
  3665. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3666. await delay();
  3667. expect(w.getChildWindows().length).to.equal(0);
  3668. });
  3669. it('closes a grandchild window when a middle child window is destroyed', (done) => {
  3670. const w = new BrowserWindow();
  3671. w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
  3672. w.webContents.executeJavaScript('window.open("")');
  3673. w.webContents.on('did-create-window', async (window) => {
  3674. const childWindow = new BrowserWindow({ parent: window });
  3675. await delay();
  3676. window.close();
  3677. childWindow.on('closed', () => {
  3678. expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
  3679. done();
  3680. });
  3681. });
  3682. });
  3683. it('should not affect the show option', () => {
  3684. const w = new BrowserWindow({ show: false });
  3685. const c = new BrowserWindow({ show: false, parent: w });
  3686. expect(c.isVisible()).to.be.false('child is visible');
  3687. expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
  3688. });
  3689. });
  3690. describe('win.setParentWindow(parent)', () => {
  3691. it('sets parent window', () => {
  3692. const w = new BrowserWindow({ show: false });
  3693. const c = new BrowserWindow({ show: false });
  3694. expect(w.getParentWindow()).to.be.null('w.parent');
  3695. expect(c.getParentWindow()).to.be.null('c.parent');
  3696. c.setParentWindow(w);
  3697. expect(c.getParentWindow()).to.equal(w);
  3698. c.setParentWindow(null);
  3699. expect(c.getParentWindow()).to.be.null('c.parent');
  3700. });
  3701. it('adds window to child windows of parent', () => {
  3702. const w = new BrowserWindow({ show: false });
  3703. const c = new BrowserWindow({ show: false });
  3704. expect(w.getChildWindows()).to.deep.equal([]);
  3705. c.setParentWindow(w);
  3706. expect(w.getChildWindows()).to.deep.equal([c]);
  3707. c.setParentWindow(null);
  3708. expect(w.getChildWindows()).to.deep.equal([]);
  3709. });
  3710. it('removes from child windows of parent when window is closed', async () => {
  3711. const w = new BrowserWindow({ show: false });
  3712. const c = new BrowserWindow({ show: false });
  3713. const closed = emittedOnce(c, 'closed');
  3714. c.setParentWindow(w);
  3715. c.close();
  3716. await closed;
  3717. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3718. await delay();
  3719. expect(w.getChildWindows().length).to.equal(0);
  3720. });
  3721. });
  3722. describe('modal option', () => {
  3723. it('does not freeze or crash', async () => {
  3724. const parentWindow = new BrowserWindow();
  3725. const createTwo = async () => {
  3726. const two = new BrowserWindow({
  3727. width: 300,
  3728. height: 200,
  3729. parent: parentWindow,
  3730. modal: true,
  3731. show: false
  3732. });
  3733. const twoShown = emittedOnce(two, 'show');
  3734. two.show();
  3735. await twoShown;
  3736. setTimeout(() => two.close(), 500);
  3737. await emittedOnce(two, 'closed');
  3738. };
  3739. const one = new BrowserWindow({
  3740. width: 600,
  3741. height: 400,
  3742. parent: parentWindow,
  3743. modal: true,
  3744. show: false
  3745. });
  3746. const oneShown = emittedOnce(one, 'show');
  3747. one.show();
  3748. await oneShown;
  3749. setTimeout(() => one.destroy(), 500);
  3750. await emittedOnce(one, 'closed');
  3751. await createTwo();
  3752. });
  3753. ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
  3754. const w = new BrowserWindow({ show: false });
  3755. w.setEnabled(false);
  3756. expect(w.isEnabled()).to.be.false('w.isEnabled()');
  3757. w.setEnabled(true);
  3758. expect(w.isEnabled()).to.be.true('!w.isEnabled()');
  3759. });
  3760. ifit(process.platform !== 'darwin')('disables parent window', () => {
  3761. const w = new BrowserWindow({ show: false });
  3762. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3763. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3764. c.show();
  3765. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3766. });
  3767. ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
  3768. const w = new BrowserWindow({ show: false });
  3769. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3770. const closed = emittedOnce(c, 'closed');
  3771. c.show();
  3772. c.close();
  3773. await closed;
  3774. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3775. });
  3776. ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
  3777. const w = new BrowserWindow({ show: false });
  3778. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3779. const closed = emittedOnce(c, 'closed');
  3780. w.setEnabled(false);
  3781. c.show();
  3782. c.close();
  3783. await closed;
  3784. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3785. });
  3786. ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
  3787. const w = new BrowserWindow({ show: false });
  3788. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3789. const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
  3790. c.show();
  3791. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3792. c2.show();
  3793. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3794. c.destroy();
  3795. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3796. c2.destroy();
  3797. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3798. });
  3799. });
  3800. });
  3801. describe('window states', () => {
  3802. afterEach(closeAllWindows);
  3803. it('does not resize frameless windows when states change', () => {
  3804. const w = new BrowserWindow({
  3805. frame: false,
  3806. width: 300,
  3807. height: 200,
  3808. show: false
  3809. });
  3810. w.minimizable = false;
  3811. w.minimizable = true;
  3812. expect(w.getSize()).to.deep.equal([300, 200]);
  3813. w.resizable = false;
  3814. w.resizable = true;
  3815. expect(w.getSize()).to.deep.equal([300, 200]);
  3816. w.maximizable = false;
  3817. w.maximizable = true;
  3818. expect(w.getSize()).to.deep.equal([300, 200]);
  3819. w.fullScreenable = false;
  3820. w.fullScreenable = true;
  3821. expect(w.getSize()).to.deep.equal([300, 200]);
  3822. w.closable = false;
  3823. w.closable = true;
  3824. expect(w.getSize()).to.deep.equal([300, 200]);
  3825. });
  3826. describe('resizable state', () => {
  3827. it('with properties', () => {
  3828. it('can be set with resizable constructor option', () => {
  3829. const w = new BrowserWindow({ show: false, resizable: false });
  3830. expect(w.resizable).to.be.false('resizable');
  3831. if (process.platform === 'darwin') {
  3832. expect(w.maximizable).to.to.true('maximizable');
  3833. }
  3834. });
  3835. it('can be changed', () => {
  3836. const w = new BrowserWindow({ show: false });
  3837. expect(w.resizable).to.be.true('resizable');
  3838. w.resizable = false;
  3839. expect(w.resizable).to.be.false('resizable');
  3840. w.resizable = true;
  3841. expect(w.resizable).to.be.true('resizable');
  3842. });
  3843. });
  3844. it('with functions', () => {
  3845. it('can be set with resizable constructor option', () => {
  3846. const w = new BrowserWindow({ show: false, resizable: false });
  3847. expect(w.isResizable()).to.be.false('resizable');
  3848. if (process.platform === 'darwin') {
  3849. expect(w.isMaximizable()).to.to.true('maximizable');
  3850. }
  3851. });
  3852. it('can be changed', () => {
  3853. const w = new BrowserWindow({ show: false });
  3854. expect(w.isResizable()).to.be.true('resizable');
  3855. w.setResizable(false);
  3856. expect(w.isResizable()).to.be.false('resizable');
  3857. w.setResizable(true);
  3858. expect(w.isResizable()).to.be.true('resizable');
  3859. });
  3860. });
  3861. it('works for a frameless window', () => {
  3862. const w = new BrowserWindow({ show: false, frame: false });
  3863. expect(w.resizable).to.be.true('resizable');
  3864. if (process.platform === 'win32') {
  3865. const w = new BrowserWindow({ show: false, thickFrame: false });
  3866. expect(w.resizable).to.be.false('resizable');
  3867. }
  3868. });
  3869. // On Linux there is no "resizable" property of a window.
  3870. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
  3871. const w = new BrowserWindow({ show: false });
  3872. expect(w.resizable).to.be.true('resizable');
  3873. expect(w.maximizable).to.be.true('maximizable');
  3874. w.resizable = false;
  3875. expect(w.maximizable).to.be.false('not maximizable');
  3876. w.resizable = true;
  3877. expect(w.maximizable).to.be.true('maximizable');
  3878. });
  3879. ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
  3880. const w = new BrowserWindow({
  3881. show: false,
  3882. frame: false,
  3883. resizable: false,
  3884. transparent: true
  3885. });
  3886. w.setContentSize(60, 60);
  3887. expectBoundsEqual(w.getContentSize(), [60, 60]);
  3888. w.setContentSize(30, 30);
  3889. expectBoundsEqual(w.getContentSize(), [30, 30]);
  3890. w.setContentSize(10, 10);
  3891. expectBoundsEqual(w.getContentSize(), [10, 10]);
  3892. });
  3893. });
  3894. describe('loading main frame state', () => {
  3895. let server: http.Server = null as unknown as http.Server;
  3896. let serverUrl: string = null as unknown as string;
  3897. before((done) => {
  3898. server = http.createServer((request, response) => {
  3899. response.end();
  3900. }).listen(0, '127.0.0.1', () => {
  3901. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  3902. done();
  3903. });
  3904. });
  3905. after(() => {
  3906. server.close();
  3907. });
  3908. it('is true when the main frame is loading', async () => {
  3909. const w = new BrowserWindow({ show: false });
  3910. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3911. w.webContents.loadURL(serverUrl);
  3912. await didStartLoading;
  3913. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3914. });
  3915. it('is false when only a subframe is loading', async () => {
  3916. const w = new BrowserWindow({ show: false });
  3917. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3918. w.webContents.loadURL(serverUrl);
  3919. await didStopLoading;
  3920. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3921. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3922. w.webContents.executeJavaScript(`
  3923. var iframe = document.createElement('iframe')
  3924. iframe.src = '${serverUrl}/page2'
  3925. document.body.appendChild(iframe)
  3926. `);
  3927. await didStartLoading;
  3928. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3929. });
  3930. it('is true when navigating to pages from the same origin', async () => {
  3931. const w = new BrowserWindow({ show: false });
  3932. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3933. w.webContents.loadURL(serverUrl);
  3934. await didStopLoading;
  3935. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3936. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3937. w.webContents.loadURL(`${serverUrl}/page2`);
  3938. await didStartLoading;
  3939. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3940. });
  3941. });
  3942. });
  3943. ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
  3944. // Not implemented on Linux.
  3945. afterEach(closeAllWindows);
  3946. describe('movable state', () => {
  3947. it('with properties', () => {
  3948. it('can be set with movable constructor option', () => {
  3949. const w = new BrowserWindow({ show: false, movable: false });
  3950. expect(w.movable).to.be.false('movable');
  3951. });
  3952. it('can be changed', () => {
  3953. const w = new BrowserWindow({ show: false });
  3954. expect(w.movable).to.be.true('movable');
  3955. w.movable = false;
  3956. expect(w.movable).to.be.false('movable');
  3957. w.movable = true;
  3958. expect(w.movable).to.be.true('movable');
  3959. });
  3960. });
  3961. it('with functions', () => {
  3962. it('can be set with movable constructor option', () => {
  3963. const w = new BrowserWindow({ show: false, movable: false });
  3964. expect(w.isMovable()).to.be.false('movable');
  3965. });
  3966. it('can be changed', () => {
  3967. const w = new BrowserWindow({ show: false });
  3968. expect(w.isMovable()).to.be.true('movable');
  3969. w.setMovable(false);
  3970. expect(w.isMovable()).to.be.false('movable');
  3971. w.setMovable(true);
  3972. expect(w.isMovable()).to.be.true('movable');
  3973. });
  3974. });
  3975. });
  3976. describe('visibleOnAllWorkspaces state', () => {
  3977. it('with properties', () => {
  3978. it('can be changed', () => {
  3979. const w = new BrowserWindow({ show: false });
  3980. expect(w.visibleOnAllWorkspaces).to.be.false();
  3981. w.visibleOnAllWorkspaces = true;
  3982. expect(w.visibleOnAllWorkspaces).to.be.true();
  3983. });
  3984. });
  3985. it('with functions', () => {
  3986. it('can be changed', () => {
  3987. const w = new BrowserWindow({ show: false });
  3988. expect(w.isVisibleOnAllWorkspaces()).to.be.false();
  3989. w.setVisibleOnAllWorkspaces(true);
  3990. expect(w.isVisibleOnAllWorkspaces()).to.be.true();
  3991. });
  3992. });
  3993. });
  3994. ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
  3995. it('with properties', () => {
  3996. it('can be changed', () => {
  3997. const w = new BrowserWindow({ show: false });
  3998. expect(w.documentEdited).to.be.false();
  3999. w.documentEdited = true;
  4000. expect(w.documentEdited).to.be.true();
  4001. });
  4002. });
  4003. it('with functions', () => {
  4004. it('can be changed', () => {
  4005. const w = new BrowserWindow({ show: false });
  4006. expect(w.isDocumentEdited()).to.be.false();
  4007. w.setDocumentEdited(true);
  4008. expect(w.isDocumentEdited()).to.be.true();
  4009. });
  4010. });
  4011. });
  4012. ifdescribe(process.platform === 'darwin')('representedFilename', () => {
  4013. it('with properties', () => {
  4014. it('can be changed', () => {
  4015. const w = new BrowserWindow({ show: false });
  4016. expect(w.representedFilename).to.eql('');
  4017. w.representedFilename = 'a name';
  4018. expect(w.representedFilename).to.eql('a name');
  4019. });
  4020. });
  4021. it('with functions', () => {
  4022. it('can be changed', () => {
  4023. const w = new BrowserWindow({ show: false });
  4024. expect(w.getRepresentedFilename()).to.eql('');
  4025. w.setRepresentedFilename('a name');
  4026. expect(w.getRepresentedFilename()).to.eql('a name');
  4027. });
  4028. });
  4029. });
  4030. describe('native window title', () => {
  4031. it('with properties', () => {
  4032. it('can be set with title constructor option', () => {
  4033. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  4034. expect(w.title).to.eql('mYtItLe');
  4035. });
  4036. it('can be changed', () => {
  4037. const w = new BrowserWindow({ show: false });
  4038. expect(w.title).to.eql('Electron Test Main');
  4039. w.title = 'NEW TITLE';
  4040. expect(w.title).to.eql('NEW TITLE');
  4041. });
  4042. });
  4043. it('with functions', () => {
  4044. it('can be set with minimizable constructor option', () => {
  4045. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  4046. expect(w.getTitle()).to.eql('mYtItLe');
  4047. });
  4048. it('can be changed', () => {
  4049. const w = new BrowserWindow({ show: false });
  4050. expect(w.getTitle()).to.eql('Electron Test Main');
  4051. w.setTitle('NEW TITLE');
  4052. expect(w.getTitle()).to.eql('NEW TITLE');
  4053. });
  4054. });
  4055. });
  4056. describe('minimizable state', () => {
  4057. it('with properties', () => {
  4058. it('can be set with minimizable constructor option', () => {
  4059. const w = new BrowserWindow({ show: false, minimizable: false });
  4060. expect(w.minimizable).to.be.false('minimizable');
  4061. });
  4062. it('can be changed', () => {
  4063. const w = new BrowserWindow({ show: false });
  4064. expect(w.minimizable).to.be.true('minimizable');
  4065. w.minimizable = false;
  4066. expect(w.minimizable).to.be.false('minimizable');
  4067. w.minimizable = true;
  4068. expect(w.minimizable).to.be.true('minimizable');
  4069. });
  4070. });
  4071. it('with functions', () => {
  4072. it('can be set with minimizable constructor option', () => {
  4073. const w = new BrowserWindow({ show: false, minimizable: false });
  4074. expect(w.isMinimizable()).to.be.false('movable');
  4075. });
  4076. it('can be changed', () => {
  4077. const w = new BrowserWindow({ show: false });
  4078. expect(w.isMinimizable()).to.be.true('isMinimizable');
  4079. w.setMinimizable(false);
  4080. expect(w.isMinimizable()).to.be.false('isMinimizable');
  4081. w.setMinimizable(true);
  4082. expect(w.isMinimizable()).to.be.true('isMinimizable');
  4083. });
  4084. });
  4085. });
  4086. describe('maximizable state (property)', () => {
  4087. it('with properties', () => {
  4088. it('can be set with maximizable constructor option', () => {
  4089. const w = new BrowserWindow({ show: false, maximizable: false });
  4090. expect(w.maximizable).to.be.false('maximizable');
  4091. });
  4092. it('can be changed', () => {
  4093. const w = new BrowserWindow({ show: false });
  4094. expect(w.maximizable).to.be.true('maximizable');
  4095. w.maximizable = false;
  4096. expect(w.maximizable).to.be.false('maximizable');
  4097. w.maximizable = true;
  4098. expect(w.maximizable).to.be.true('maximizable');
  4099. });
  4100. it('is not affected when changing other states', () => {
  4101. const w = new BrowserWindow({ show: false });
  4102. w.maximizable = false;
  4103. expect(w.maximizable).to.be.false('maximizable');
  4104. w.minimizable = false;
  4105. expect(w.maximizable).to.be.false('maximizable');
  4106. w.closable = false;
  4107. expect(w.maximizable).to.be.false('maximizable');
  4108. w.maximizable = true;
  4109. expect(w.maximizable).to.be.true('maximizable');
  4110. w.closable = true;
  4111. expect(w.maximizable).to.be.true('maximizable');
  4112. w.fullScreenable = false;
  4113. expect(w.maximizable).to.be.true('maximizable');
  4114. });
  4115. });
  4116. it('with functions', () => {
  4117. it('can be set with maximizable constructor option', () => {
  4118. const w = new BrowserWindow({ show: false, maximizable: false });
  4119. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4120. });
  4121. it('can be changed', () => {
  4122. const w = new BrowserWindow({ show: false });
  4123. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4124. w.setMaximizable(false);
  4125. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4126. w.setMaximizable(true);
  4127. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4128. });
  4129. it('is not affected when changing other states', () => {
  4130. const w = new BrowserWindow({ show: false });
  4131. w.setMaximizable(false);
  4132. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4133. w.setMinimizable(false);
  4134. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4135. w.setClosable(false);
  4136. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4137. w.setMaximizable(true);
  4138. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4139. w.setClosable(true);
  4140. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4141. w.setFullScreenable(false);
  4142. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4143. });
  4144. });
  4145. });
  4146. ifdescribe(process.platform === 'win32')('maximizable state', () => {
  4147. it('with properties', () => {
  4148. it('is reset to its former state', () => {
  4149. const w = new BrowserWindow({ show: false });
  4150. w.maximizable = false;
  4151. w.resizable = false;
  4152. w.resizable = true;
  4153. expect(w.maximizable).to.be.false('maximizable');
  4154. w.maximizable = true;
  4155. w.resizable = false;
  4156. w.resizable = true;
  4157. expect(w.maximizable).to.be.true('maximizable');
  4158. });
  4159. });
  4160. it('with functions', () => {
  4161. it('is reset to its former state', () => {
  4162. const w = new BrowserWindow({ show: false });
  4163. w.setMaximizable(false);
  4164. w.setResizable(false);
  4165. w.setResizable(true);
  4166. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4167. w.setMaximizable(true);
  4168. w.setResizable(false);
  4169. w.setResizable(true);
  4170. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4171. });
  4172. });
  4173. });
  4174. ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
  4175. describe('with properties', () => {
  4176. it('can be changed', () => {
  4177. const w = new BrowserWindow({ show: false });
  4178. expect(w.menuBarVisible).to.be.true();
  4179. w.menuBarVisible = false;
  4180. expect(w.menuBarVisible).to.be.false();
  4181. w.menuBarVisible = true;
  4182. expect(w.menuBarVisible).to.be.true();
  4183. });
  4184. });
  4185. describe('with functions', () => {
  4186. it('can be changed', () => {
  4187. const w = new BrowserWindow({ show: false });
  4188. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4189. w.setMenuBarVisibility(false);
  4190. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4191. w.setMenuBarVisibility(true);
  4192. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4193. });
  4194. });
  4195. });
  4196. ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
  4197. it('with functions', () => {
  4198. it('can be set with fullscreenable constructor option', () => {
  4199. const w = new BrowserWindow({ show: false, fullscreenable: false });
  4200. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4201. });
  4202. it('can be changed', () => {
  4203. const w = new BrowserWindow({ show: false });
  4204. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4205. w.setFullScreenable(false);
  4206. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4207. w.setFullScreenable(true);
  4208. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4209. });
  4210. });
  4211. });
  4212. // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
  4213. ifdescribe(process.platform === 'darwin')('kiosk state', () => {
  4214. it('with properties', () => {
  4215. it('can be set with a constructor property', () => {
  4216. const w = new BrowserWindow({ kiosk: true });
  4217. expect(w.kiosk).to.be.true();
  4218. });
  4219. it('can be changed ', async () => {
  4220. const w = new BrowserWindow();
  4221. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4222. w.kiosk = true;
  4223. expect(w.isKiosk()).to.be.true('isKiosk');
  4224. await enterFullScreen;
  4225. await delay();
  4226. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4227. w.kiosk = false;
  4228. expect(w.isKiosk()).to.be.false('isKiosk');
  4229. await leaveFullScreen;
  4230. });
  4231. });
  4232. it('with functions', () => {
  4233. it('can be set with a constructor property', () => {
  4234. const w = new BrowserWindow({ kiosk: true });
  4235. expect(w.isKiosk()).to.be.true();
  4236. });
  4237. it('can be changed ', async () => {
  4238. const w = new BrowserWindow();
  4239. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4240. w.setKiosk(true);
  4241. expect(w.isKiosk()).to.be.true('isKiosk');
  4242. await enterFullScreen;
  4243. await delay();
  4244. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4245. w.setKiosk(false);
  4246. expect(w.isKiosk()).to.be.false('isKiosk');
  4247. await leaveFullScreen;
  4248. });
  4249. });
  4250. });
  4251. ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
  4252. it('resizable flag should be set to false and restored', async () => {
  4253. const w = new BrowserWindow({ resizable: false });
  4254. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4255. w.setFullScreen(true);
  4256. await enterFullScreen;
  4257. expect(w.resizable).to.be.false('resizable');
  4258. await delay();
  4259. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4260. w.setFullScreen(false);
  4261. await leaveFullScreen;
  4262. expect(w.resizable).to.be.false('resizable');
  4263. });
  4264. it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
  4265. const w = new BrowserWindow();
  4266. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4267. w.setFullScreen(true);
  4268. await enterFullScreen;
  4269. expect(w.resizable).to.be.false('resizable');
  4270. await delay();
  4271. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4272. w.setFullScreen(false);
  4273. await leaveFullScreen;
  4274. expect(w.resizable).to.be.true('resizable');
  4275. });
  4276. });
  4277. ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
  4278. it('should not cause a crash if called when exiting fullscreen', async () => {
  4279. const w = new BrowserWindow();
  4280. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4281. w.setFullScreen(true);
  4282. await enterFullScreen;
  4283. await delay();
  4284. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4285. w.setFullScreen(false);
  4286. await leaveFullScreen;
  4287. });
  4288. it('should be able to load a URL while transitioning to fullscreen', async () => {
  4289. const w = new BrowserWindow({ fullscreen: true });
  4290. w.loadFile(path.join(fixtures, 'pages', 'c.html'));
  4291. const load = emittedOnce(w.webContents, 'did-finish-load');
  4292. const enterFS = emittedOnce(w, 'enter-full-screen');
  4293. await Promise.all([enterFS, load]);
  4294. expect(w.fullScreen).to.be.true();
  4295. await delay();
  4296. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4297. w.setFullScreen(false);
  4298. await leaveFullScreen;
  4299. });
  4300. it('can be changed with setFullScreen method', async () => {
  4301. const w = new BrowserWindow();
  4302. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4303. w.setFullScreen(true);
  4304. await enterFullScreen;
  4305. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4306. await delay();
  4307. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4308. w.setFullScreen(false);
  4309. await leaveFullScreen;
  4310. expect(w.isFullScreen()).to.be.false('isFullScreen');
  4311. });
  4312. it('handles several transitions starting with fullscreen', async () => {
  4313. const w = new BrowserWindow({ fullscreen: true, show: true });
  4314. expect(w.isFullScreen()).to.be.true('not fullscreen');
  4315. w.setFullScreen(false);
  4316. w.setFullScreen(true);
  4317. const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
  4318. await enterFullScreen;
  4319. expect(w.isFullScreen()).to.be.true('not fullscreen');
  4320. await delay();
  4321. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4322. w.setFullScreen(false);
  4323. await leaveFullScreen;
  4324. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4325. });
  4326. it('handles several HTML fullscreen transitions', async () => {
  4327. const w = new BrowserWindow();
  4328. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  4329. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4330. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4331. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4332. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4333. await enterFullScreen;
  4334. await w.webContents.executeJavaScript('document.exitFullscreen()', true);
  4335. await leaveFullScreen;
  4336. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4337. await delay();
  4338. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4339. await enterFullScreen;
  4340. await w.webContents.executeJavaScript('document.exitFullscreen()', true);
  4341. await leaveFullScreen;
  4342. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4343. });
  4344. it('handles several transitions in close proximity', async () => {
  4345. const w = new BrowserWindow();
  4346. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4347. const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
  4348. const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
  4349. w.setFullScreen(true);
  4350. w.setFullScreen(false);
  4351. w.setFullScreen(true);
  4352. w.setFullScreen(false);
  4353. await Promise.all([enterFS, leaveFS]);
  4354. expect(w.isFullScreen()).to.be.false('not fullscreen');
  4355. });
  4356. it('handles several chromium-initiated transitions in close proximity', async () => {
  4357. const w = new BrowserWindow();
  4358. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  4359. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4360. let enterCount = 0;
  4361. let exitCount = 0;
  4362. const done = new Promise<void>(resolve => {
  4363. const checkDone = () => {
  4364. if (enterCount === 2 && exitCount === 2) resolve();
  4365. };
  4366. w.webContents.on('enter-html-full-screen', () => {
  4367. enterCount++;
  4368. checkDone();
  4369. });
  4370. w.webContents.on('leave-html-full-screen', () => {
  4371. exitCount++;
  4372. checkDone();
  4373. });
  4374. });
  4375. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4376. await w.webContents.executeJavaScript('document.exitFullscreen()');
  4377. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4378. await w.webContents.executeJavaScript('document.exitFullscreen()');
  4379. await done;
  4380. });
  4381. it('does not crash when exiting simpleFullScreen (properties)', async () => {
  4382. const w = new BrowserWindow();
  4383. w.setSimpleFullScreen(true);
  4384. await delay(1000);
  4385. w.setFullScreen(!w.isFullScreen());
  4386. });
  4387. it('does not crash when exiting simpleFullScreen (functions)', async () => {
  4388. const w = new BrowserWindow();
  4389. w.simpleFullScreen = true;
  4390. await delay(1000);
  4391. w.setFullScreen(!w.isFullScreen());
  4392. });
  4393. it('should not be changed by setKiosk method', async () => {
  4394. const w = new BrowserWindow();
  4395. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4396. w.setFullScreen(true);
  4397. await enterFullScreen;
  4398. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4399. await delay();
  4400. w.setKiosk(true);
  4401. await delay();
  4402. w.setKiosk(false);
  4403. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4404. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4405. w.setFullScreen(false);
  4406. await leaveFullScreen;
  4407. expect(w.isFullScreen()).to.be.false('isFullScreen');
  4408. });
  4409. // FIXME: https://github.com/electron/electron/issues/30140
  4410. xit('multiple windows inherit correct fullscreen state', async () => {
  4411. const w = new BrowserWindow();
  4412. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4413. w.setFullScreen(true);
  4414. await enterFullScreen;
  4415. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4416. await delay();
  4417. const w2 = new BrowserWindow({ show: false });
  4418. const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen');
  4419. w2.show();
  4420. await enterFullScreen2;
  4421. expect(w2.isFullScreen()).to.be.true('isFullScreen');
  4422. });
  4423. });
  4424. describe('closable state', () => {
  4425. it('with properties', () => {
  4426. it('can be set with closable constructor option', () => {
  4427. const w = new BrowserWindow({ show: false, closable: false });
  4428. expect(w.closable).to.be.false('closable');
  4429. });
  4430. it('can be changed', () => {
  4431. const w = new BrowserWindow({ show: false });
  4432. expect(w.closable).to.be.true('closable');
  4433. w.closable = false;
  4434. expect(w.closable).to.be.false('closable');
  4435. w.closable = true;
  4436. expect(w.closable).to.be.true('closable');
  4437. });
  4438. });
  4439. it('with functions', () => {
  4440. it('can be set with closable constructor option', () => {
  4441. const w = new BrowserWindow({ show: false, closable: false });
  4442. expect(w.isClosable()).to.be.false('isClosable');
  4443. });
  4444. it('can be changed', () => {
  4445. const w = new BrowserWindow({ show: false });
  4446. expect(w.isClosable()).to.be.true('isClosable');
  4447. w.setClosable(false);
  4448. expect(w.isClosable()).to.be.false('isClosable');
  4449. w.setClosable(true);
  4450. expect(w.isClosable()).to.be.true('isClosable');
  4451. });
  4452. });
  4453. });
  4454. describe('hasShadow state', () => {
  4455. it('with properties', () => {
  4456. it('returns a boolean on all platforms', () => {
  4457. const w = new BrowserWindow({ show: false });
  4458. expect(w.shadow).to.be.a('boolean');
  4459. });
  4460. // On Windows there's no shadow by default & it can't be changed dynamically.
  4461. it('can be changed with hasShadow option', () => {
  4462. const hasShadow = process.platform !== 'darwin';
  4463. const w = new BrowserWindow({ show: false, hasShadow });
  4464. expect(w.shadow).to.equal(hasShadow);
  4465. });
  4466. it('can be changed with setHasShadow method', () => {
  4467. const w = new BrowserWindow({ show: false });
  4468. w.shadow = false;
  4469. expect(w.shadow).to.be.false('hasShadow');
  4470. w.shadow = true;
  4471. expect(w.shadow).to.be.true('hasShadow');
  4472. w.shadow = false;
  4473. expect(w.shadow).to.be.false('hasShadow');
  4474. });
  4475. });
  4476. describe('with functions', () => {
  4477. it('returns a boolean on all platforms', () => {
  4478. const w = new BrowserWindow({ show: false });
  4479. const hasShadow = w.hasShadow();
  4480. expect(hasShadow).to.be.a('boolean');
  4481. });
  4482. // On Windows there's no shadow by default & it can't be changed dynamically.
  4483. it('can be changed with hasShadow option', () => {
  4484. const hasShadow = process.platform !== 'darwin';
  4485. const w = new BrowserWindow({ show: false, hasShadow });
  4486. expect(w.hasShadow()).to.equal(hasShadow);
  4487. });
  4488. it('can be changed with setHasShadow method', () => {
  4489. const w = new BrowserWindow({ show: false });
  4490. w.setHasShadow(false);
  4491. expect(w.hasShadow()).to.be.false('hasShadow');
  4492. w.setHasShadow(true);
  4493. expect(w.hasShadow()).to.be.true('hasShadow');
  4494. w.setHasShadow(false);
  4495. expect(w.hasShadow()).to.be.false('hasShadow');
  4496. });
  4497. });
  4498. });
  4499. });
  4500. describe('window.getMediaSourceId()', () => {
  4501. afterEach(closeAllWindows);
  4502. it('returns valid source id', async () => {
  4503. const w = new BrowserWindow({ show: false });
  4504. const shown = emittedOnce(w, 'show');
  4505. w.show();
  4506. await shown;
  4507. // Check format 'window:1234:0'.
  4508. const sourceId = w.getMediaSourceId();
  4509. expect(sourceId).to.match(/^window:\d+:\d+$/);
  4510. });
  4511. });
  4512. ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
  4513. afterEach(closeAllWindows);
  4514. it('returns valid handle', () => {
  4515. const w = new BrowserWindow({ show: false });
  4516. // The module's source code is hosted at
  4517. // https://github.com/electron/node-is-valid-window
  4518. const isValidWindow = require('is-valid-window');
  4519. expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
  4520. });
  4521. });
  4522. ifdescribe(process.platform === 'darwin')('previewFile', () => {
  4523. afterEach(closeAllWindows);
  4524. it('opens the path in Quick Look on macOS', () => {
  4525. const w = new BrowserWindow({ show: false });
  4526. expect(() => {
  4527. w.previewFile(__filename);
  4528. w.closeFilePreview();
  4529. }).to.not.throw();
  4530. });
  4531. });
  4532. // TODO (jkleinsc) renable these tests on mas arm64
  4533. ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
  4534. const expectedContextData = {
  4535. preloadContext: {
  4536. preloadProperty: 'number',
  4537. pageProperty: 'undefined',
  4538. typeofRequire: 'function',
  4539. typeofProcess: 'object',
  4540. typeofArrayPush: 'function',
  4541. typeofFunctionApply: 'function',
  4542. typeofPreloadExecuteJavaScriptProperty: 'undefined'
  4543. },
  4544. pageContext: {
  4545. preloadProperty: 'undefined',
  4546. pageProperty: 'string',
  4547. typeofRequire: 'undefined',
  4548. typeofProcess: 'undefined',
  4549. typeofArrayPush: 'number',
  4550. typeofFunctionApply: 'boolean',
  4551. typeofPreloadExecuteJavaScriptProperty: 'number',
  4552. typeofOpenedWindow: 'object'
  4553. }
  4554. };
  4555. afterEach(closeAllWindows);
  4556. it('separates the page context from the Electron/preload context', async () => {
  4557. const iw = new BrowserWindow({
  4558. show: false,
  4559. webPreferences: {
  4560. contextIsolation: true,
  4561. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4562. }
  4563. });
  4564. const p = emittedOnce(ipcMain, 'isolated-world');
  4565. iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4566. const [, data] = await p;
  4567. expect(data).to.deep.equal(expectedContextData);
  4568. });
  4569. it('recreates the contexts on reload', async () => {
  4570. const iw = new BrowserWindow({
  4571. show: false,
  4572. webPreferences: {
  4573. contextIsolation: true,
  4574. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4575. }
  4576. });
  4577. await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4578. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  4579. iw.webContents.reload();
  4580. const [, data] = await isolatedWorld;
  4581. expect(data).to.deep.equal(expectedContextData);
  4582. });
  4583. it('enables context isolation on child windows', async () => {
  4584. const iw = new BrowserWindow({
  4585. show: false,
  4586. webPreferences: {
  4587. contextIsolation: true,
  4588. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4589. }
  4590. });
  4591. const browserWindowCreated = emittedOnce(app, 'browser-window-created');
  4592. iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  4593. const [, window] = await browserWindowCreated;
  4594. expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
  4595. });
  4596. it('separates the page context from the Electron/preload context with sandbox on', async () => {
  4597. const ws = new BrowserWindow({
  4598. show: false,
  4599. webPreferences: {
  4600. sandbox: true,
  4601. contextIsolation: true,
  4602. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4603. }
  4604. });
  4605. const p = emittedOnce(ipcMain, 'isolated-world');
  4606. ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4607. const [, data] = await p;
  4608. expect(data).to.deep.equal(expectedContextData);
  4609. });
  4610. it('recreates the contexts on reload with sandbox on', async () => {
  4611. const ws = new BrowserWindow({
  4612. show: false,
  4613. webPreferences: {
  4614. sandbox: true,
  4615. contextIsolation: true,
  4616. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4617. }
  4618. });
  4619. await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4620. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  4621. ws.webContents.reload();
  4622. const [, data] = await isolatedWorld;
  4623. expect(data).to.deep.equal(expectedContextData);
  4624. });
  4625. it('supports fetch api', async () => {
  4626. const fetchWindow = new BrowserWindow({
  4627. show: false,
  4628. webPreferences: {
  4629. contextIsolation: true,
  4630. preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
  4631. }
  4632. });
  4633. const p = emittedOnce(ipcMain, 'isolated-fetch-error');
  4634. fetchWindow.loadURL('about:blank');
  4635. const [, error] = await p;
  4636. expect(error).to.equal('Failed to fetch');
  4637. });
  4638. it('doesn\'t break ipc serialization', async () => {
  4639. const iw = new BrowserWindow({
  4640. show: false,
  4641. webPreferences: {
  4642. contextIsolation: true,
  4643. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4644. }
  4645. });
  4646. const p = emittedOnce(ipcMain, 'isolated-world');
  4647. iw.loadURL('about:blank');
  4648. iw.webContents.executeJavaScript(`
  4649. const opened = window.open()
  4650. openedLocation = opened.location.href
  4651. opened.close()
  4652. window.postMessage({openedLocation}, '*')
  4653. `);
  4654. const [, data] = await p;
  4655. expect(data.pageContext.openedLocation).to.equal('about:blank');
  4656. });
  4657. it('reports process.contextIsolated', async () => {
  4658. const iw = new BrowserWindow({
  4659. show: false,
  4660. webPreferences: {
  4661. contextIsolation: true,
  4662. preload: path.join(fixtures, 'api', 'isolated-process.js')
  4663. }
  4664. });
  4665. const p = emittedOnce(ipcMain, 'context-isolation');
  4666. iw.loadURL('about:blank');
  4667. const [, contextIsolation] = await p;
  4668. expect(contextIsolation).to.be.true('contextIsolation');
  4669. });
  4670. });
  4671. it('reloading does not cause Node.js module API hangs after reload', (done) => {
  4672. const w = new BrowserWindow({
  4673. show: false,
  4674. webPreferences: {
  4675. nodeIntegration: true,
  4676. contextIsolation: false
  4677. }
  4678. });
  4679. let count = 0;
  4680. ipcMain.on('async-node-api-done', () => {
  4681. if (count === 3) {
  4682. ipcMain.removeAllListeners('async-node-api-done');
  4683. done();
  4684. } else {
  4685. count++;
  4686. w.reload();
  4687. }
  4688. });
  4689. w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
  4690. });
  4691. describe('window.webContents.focus()', () => {
  4692. afterEach(closeAllWindows);
  4693. it('focuses window', async () => {
  4694. const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
  4695. w1.loadURL('about:blank');
  4696. const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
  4697. w2.loadURL('about:blank');
  4698. const w1Focused = emittedOnce(w1, 'focus');
  4699. w1.webContents.focus();
  4700. await w1Focused;
  4701. expect(w1.webContents.isFocused()).to.be.true('focuses window');
  4702. });
  4703. });
  4704. ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
  4705. let w: BrowserWindow;
  4706. beforeEach(function () {
  4707. w = new BrowserWindow({
  4708. width: 100,
  4709. height: 100,
  4710. show: false,
  4711. webPreferences: {
  4712. backgroundThrottling: false,
  4713. offscreen: true
  4714. }
  4715. });
  4716. });
  4717. afterEach(closeAllWindows);
  4718. it('creates offscreen window with correct size', async () => {
  4719. const paint = emittedOnce(w.webContents, 'paint');
  4720. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4721. const [,, data] = await paint;
  4722. expect(data.constructor.name).to.equal('NativeImage');
  4723. expect(data.isEmpty()).to.be.false('data is empty');
  4724. const size = data.getSize();
  4725. const { scaleFactor } = screen.getPrimaryDisplay();
  4726. expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
  4727. expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
  4728. });
  4729. it('does not crash after navigation', () => {
  4730. w.webContents.loadURL('about:blank');
  4731. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4732. });
  4733. describe('window.webContents.isOffscreen()', () => {
  4734. it('is true for offscreen type', () => {
  4735. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4736. expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
  4737. });
  4738. it('is false for regular window', () => {
  4739. const c = new BrowserWindow({ show: false });
  4740. expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
  4741. c.destroy();
  4742. });
  4743. });
  4744. describe('window.webContents.isPainting()', () => {
  4745. it('returns whether is currently painting', async () => {
  4746. const paint = emittedOnce(w.webContents, 'paint');
  4747. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4748. await paint;
  4749. expect(w.webContents.isPainting()).to.be.true('isPainting');
  4750. });
  4751. });
  4752. describe('window.webContents.stopPainting()', () => {
  4753. it('stops painting', async () => {
  4754. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4755. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4756. await domReady;
  4757. w.webContents.stopPainting();
  4758. expect(w.webContents.isPainting()).to.be.false('isPainting');
  4759. });
  4760. });
  4761. describe('window.webContents.startPainting()', () => {
  4762. it('starts painting', async () => {
  4763. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4764. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4765. await domReady;
  4766. w.webContents.stopPainting();
  4767. w.webContents.startPainting();
  4768. await emittedOnce(w.webContents, 'paint');
  4769. expect(w.webContents.isPainting()).to.be.true('isPainting');
  4770. });
  4771. });
  4772. describe('frameRate APIs', () => {
  4773. it('has default frame rate (function)', async () => {
  4774. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4775. await emittedOnce(w.webContents, 'paint');
  4776. expect(w.webContents.getFrameRate()).to.equal(60);
  4777. });
  4778. it('has default frame rate (property)', async () => {
  4779. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4780. await emittedOnce(w.webContents, 'paint');
  4781. expect(w.webContents.frameRate).to.equal(60);
  4782. });
  4783. it('sets custom frame rate (function)', async () => {
  4784. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4785. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4786. await domReady;
  4787. w.webContents.setFrameRate(30);
  4788. await emittedOnce(w.webContents, 'paint');
  4789. expect(w.webContents.getFrameRate()).to.equal(30);
  4790. });
  4791. it('sets custom frame rate (property)', async () => {
  4792. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4793. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4794. await domReady;
  4795. w.webContents.frameRate = 30;
  4796. await emittedOnce(w.webContents, 'paint');
  4797. expect(w.webContents.frameRate).to.equal(30);
  4798. });
  4799. });
  4800. });
  4801. describe('"transparent" option', () => {
  4802. afterEach(closeAllWindows);
  4803. // Only applicable on Windows where transparent windows can't be maximized.
  4804. ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
  4805. const display = screen.getPrimaryDisplay();
  4806. const w = new BrowserWindow({
  4807. ...display.bounds,
  4808. frame: false,
  4809. transparent: true,
  4810. show: true
  4811. });
  4812. w.loadURL('about:blank');
  4813. await emittedOnce(w, 'ready-to-show');
  4814. expect(w.isMaximized()).to.be.true();
  4815. // Fails when the transparent HWND is in an invalid maximized state.
  4816. expect(w.getBounds()).to.deep.equal(display.workArea);
  4817. const newBounds = { width: 256, height: 256, x: 0, y: 0 };
  4818. w.setBounds(newBounds);
  4819. expect(w.getBounds()).to.deep.equal(newBounds);
  4820. });
  4821. // Linux and arm64 platforms (WOA and macOS) do not return any capture sources
  4822. ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => {
  4823. const display = screen.getPrimaryDisplay();
  4824. const backgroundWindow = new BrowserWindow({
  4825. ...display.bounds,
  4826. frame: false,
  4827. backgroundColor: CHROMA_COLOR_HEX,
  4828. hasShadow: false
  4829. });
  4830. await backgroundWindow.loadURL('about:blank');
  4831. const foregroundWindow = new BrowserWindow({
  4832. ...display.bounds,
  4833. show: true,
  4834. transparent: true,
  4835. frame: false,
  4836. hasShadow: false
  4837. });
  4838. foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html'));
  4839. await emittedOnce(foregroundWindow, 'ready-to-show');
  4840. const screenCapture = await captureScreen();
  4841. const leftHalfColor = getPixelColor(screenCapture, {
  4842. x: display.size.width / 4,
  4843. y: display.size.height / 2
  4844. });
  4845. const rightHalfColor = getPixelColor(screenCapture, {
  4846. x: display.size.width - (display.size.width / 4),
  4847. y: display.size.height / 2
  4848. });
  4849. expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true();
  4850. expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true();
  4851. });
  4852. });
  4853. describe('"backgroundColor" option', () => {
  4854. afterEach(closeAllWindows);
  4855. // Linux/WOA doesn't return any capture sources.
  4856. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => {
  4857. const display = screen.getPrimaryDisplay();
  4858. const w = new BrowserWindow({
  4859. ...display.bounds,
  4860. show: true,
  4861. backgroundColor: CHROMA_COLOR_HEX
  4862. });
  4863. w.loadURL('about:blank');
  4864. await emittedOnce(w, 'ready-to-show');
  4865. const screenCapture = await captureScreen();
  4866. const centerColor = getPixelColor(screenCapture, {
  4867. x: display.size.width / 2,
  4868. y: display.size.height / 2
  4869. });
  4870. expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true();
  4871. });
  4872. });
  4873. });