api-browser-window-spec.js 101 KB

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