api-browser-window-spec.ts 146 KB

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