api-browser-window-spec.js 125 KB

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