api-browser-window-spec.js 100 KB

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