api-browser-window-spec.js 115 KB

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