api-browser-window-spec.ts 167 KB

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