api-browser-window-spec.js 116 KB

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