api-browser-window-spec.ts 151 KB

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