api-browser-window-spec.js 88 KB

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