api-browser-window-spec.js 104 KB

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