api-browser-window-spec.js 122 KB

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