api-browser-window-spec.ts 139 KB

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