api-browser-window-spec.js 73 KB

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