12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275 |
- 'use strict'
- const assert = require('assert')
- const {expect} = require('chai')
- const fs = require('fs')
- const path = require('path')
- const os = require('os')
- const qs = require('querystring')
- const http = require('http')
- const {closeWindow} = require('./window-helpers')
- const {ipcRenderer, remote, screen} = require('electron')
- const {app, ipcMain, BrowserWindow, BrowserView, protocol, session, webContents} = remote
- const features = process.atomBinding('features')
- const isCI = remote.getGlobal('isCi')
- const nativeModulesEnabled = remote.getGlobal('nativeModulesEnabled')
- describe('BrowserWindow module', () => {
- const fixtures = path.resolve(__dirname, 'fixtures')
- let w = null
- let ws = null
- let server
- let postData
- const closeTheWindow = function () {
- return closeWindow(w).then(() => { w = null })
- }
- before((done) => {
- const filePath = path.join(fixtures, 'pages', 'a.html')
- const fileStats = fs.statSync(filePath)
- postData = [
- {
- type: 'rawData',
- bytes: Buffer.from('username=test&file=')
- },
- {
- type: 'file',
- filePath: filePath,
- offset: 0,
- length: fileStats.size,
- modificationTime: fileStats.mtime.getTime() / 1000
- }
- ]
- server = http.createServer((req, res) => {
- function respond () {
- if (req.method === 'POST') {
- let body = ''
- req.on('data', (data) => {
- if (data) body += data
- })
- req.on('end', () => {
- let parsedData = qs.parse(body)
- fs.readFile(filePath, (err, data) => {
- if (err) return
- if (parsedData.username === 'test' &&
- parsedData.file === data.toString()) {
- res.end()
- }
- })
- })
- } else {
- res.end()
- }
- }
- setTimeout(respond, req.url.includes('slow') ? 200 : 0)
- })
- server.listen(0, '127.0.0.1', () => {
- server.url = `http://127.0.0.1:${server.address().port}`
- done()
- })
- })
- after(() => {
- server.close()
- server = null
- })
- beforeEach(() => {
- w = new BrowserWindow({
- show: false,
- width: 400,
- height: 400,
- webPreferences: {
- backgroundThrottling: false
- }
- })
- })
- afterEach(closeTheWindow)
- describe('BrowserWindow constructor', () => {
- it('allows passing void 0 as the webContents', () => {
- w.close()
- w = null
- w = new BrowserWindow({
- webContents: void 0
- })
- })
- })
- describe('BrowserWindow.close()', () => {
- let server
- before((done) => {
- server = http.createServer((request, response) => {
- switch (request.url) {
- case '/404':
- response.statusCode = '404'
- response.end()
- break
- case '/301':
- response.statusCode = '301'
- response.setHeader('Location', '/200')
- response.end()
- break
- case '/200':
- response.statusCode = '200'
- response.end('hello')
- break
- case '/title':
- response.statusCode = '200'
- response.end('<title>Hello</title>')
- break
- default:
- done('unsupported endpoint')
- }
- }).listen(0, '127.0.0.1', () => {
- server.url = 'http://127.0.0.1:' + server.address().port
- done()
- })
- })
- after(() => {
- server.close()
- server = null
- })
- it('should emit unload handler', (done) => {
- w.webContents.on('did-finish-load', () => { w.close() })
- w.once('closed', () => {
- const test = path.join(fixtures, 'api', 'unload')
- const content = fs.readFileSync(test)
- fs.unlinkSync(test)
- assert.equal(String(content), 'unload')
- done()
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'unload.html'))
- })
- it('should emit beforeunload handler', (done) => {
- w.once('onbeforeunload', () => { done() })
- w.webContents.on('did-finish-load', () => { w.close() })
- w.loadURL(`file://${path.join(fixtures, 'api', 'beforeunload-false.html')}`)
- })
- it('should not crash when invoked synchronously inside navigation observer', (done) => {
- const events = [
- { name: 'did-start-loading', url: `${server.url}/200` },
- { name: '-did-get-redirect-request', url: `${server.url}/301` },
- { name: '-did-get-response-details', url: `${server.url}/200` },
- { name: 'dom-ready', url: `${server.url}/200` },
- { name: 'page-title-updated', url: `${server.url}/title` },
- { name: 'did-stop-loading', url: `${server.url}/200` },
- { name: 'did-finish-load', url: `${server.url}/200` },
- { name: 'did-frame-finish-load', url: `${server.url}/200` },
- { name: 'did-fail-load', url: `${server.url}/404` }
- ]
- const responseEvent = 'window-webContents-destroyed'
- function * genNavigationEvent () {
- let eventOptions = null
- while ((eventOptions = events.shift()) && events.length) {
- let w = new BrowserWindow({show: false})
- eventOptions.id = w.id
- eventOptions.responseEvent = responseEvent
- ipcRenderer.send('test-webcontents-navigation-observer', eventOptions)
- yield 1
- }
- }
- let gen = genNavigationEvent()
- ipcRenderer.on(responseEvent, () => {
- if (!gen.next().value) done()
- })
- gen.next()
- })
- })
- describe('window.close()', () => {
- it('should emit unload handler', (done) => {
- w.once('closed', () => {
- const test = path.join(fixtures, 'api', 'close')
- const content = fs.readFileSync(test)
- fs.unlinkSync(test)
- assert.equal(String(content), 'close')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'close.html')}`)
- })
- it('should emit beforeunload handler', (done) => {
- w.once('onbeforeunload', () => { done() })
- w.loadURL(`file://${path.join(fixtures, 'api', 'close-beforeunload-false.html')}`)
- })
- })
- describe('BrowserWindow.destroy()', () => {
- it('prevents users to access methods of webContents', () => {
- const contents = w.webContents
- w.destroy()
- assert.throws(() => {
- contents.getId()
- }, /Object has been destroyed/)
- })
- })
- describe('BrowserWindow.loadURL(url)', () => {
- it('should emit did-start-loading event', (done) => {
- w.webContents.on('did-start-loading', () => { done() })
- w.loadURL('about:blank')
- })
- it('should emit ready-to-show event', (done) => {
- w.on('ready-to-show', () => { done() })
- w.loadURL('about:blank')
- })
- // TODO(nitsakh): Deprecated
- it('should emit did-get-response-details(deprecated) event', (done) => {
- // expected {fileName: resourceType} pairs
- const expectedResources = {
- 'did-get-response-details.html': 'mainFrame',
- 'logo.png': 'image'
- }
- let responses = 0
- w.webContents.on('-did-get-response-details', (event, status, newUrl, oldUrl, responseCode, method, referrer, headers, resourceType) => {
- responses += 1
- const fileName = newUrl.slice(newUrl.lastIndexOf('/') + 1)
- const expectedType = expectedResources[fileName]
- assert(!!expectedType, `Unexpected response details for ${newUrl}`)
- assert(typeof status === 'boolean', 'status should be boolean')
- assert.equal(responseCode, 200)
- assert.equal(method, 'GET')
- assert(typeof referrer === 'string', 'referrer should be string')
- assert(!!headers, 'headers should be present')
- assert(typeof headers === 'object', 'headers should be object')
- assert.equal(resourceType, expectedType, 'Incorrect resourceType')
- if (responses === Object.keys(expectedResources).length) done()
- })
- w.loadURL(`file://${path.join(fixtures, 'pages', 'did-get-response-details.html')}`)
- })
- it('should emit did-fail-load event for files that do not exist', (done) => {
- w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
- assert.equal(code, -6)
- assert.equal(desc, 'ERR_FILE_NOT_FOUND')
- assert.equal(isMainFrame, true)
- done()
- })
- w.loadURL('file://a.txt')
- })
- it('should emit did-fail-load event for invalid URL', (done) => {
- w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
- assert.equal(desc, 'ERR_INVALID_URL')
- assert.equal(code, -300)
- assert.equal(isMainFrame, true)
- done()
- })
- w.loadURL('http://example:port')
- })
- it('should set `mainFrame = false` on did-fail-load events in iframes', (done) => {
- w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
- assert.equal(isMainFrame, false)
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'did-fail-load-iframe.html')}`)
- })
- it('does not crash in did-fail-provisional-load handler', (done) => {
- w.webContents.once('did-fail-provisional-load', () => {
- w.loadURL('http://127.0.0.1:11111')
- done()
- })
- w.loadURL('http://127.0.0.1:11111')
- })
- it('should emit did-fail-load event for URL exceeding character limit', (done) => {
- w.webContents.on('did-fail-load', (event, code, desc, url, isMainFrame) => {
- assert.equal(desc, 'ERR_INVALID_URL')
- assert.equal(code, -300)
- assert.equal(isMainFrame, true)
- done()
- })
- const data = Buffer.alloc(2 * 1024 * 1024).toString('base64')
- w.loadURL(`data:image/png;base64,${data}`)
- })
- describe('POST navigations', () => {
- afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null) })
- it('supports specifying POST data', (done) => {
- w.webContents.on('did-finish-load', () => done())
- w.loadURL(server.url, {postData: postData})
- })
- it('sets the content type header on URL encoded forms', (done) => {
- w.webContents.on('did-finish-load', () => {
- w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
- assert.equal(details.requestHeaders['content-type'], 'application/x-www-form-urlencoded')
- done()
- })
- w.webContents.executeJavaScript(`
- form = document.createElement('form')
- document.body.appendChild(form)
- form.method = 'POST'
- form.target = '_blank'
- form.submit()
- `)
- })
- w.loadURL(server.url)
- })
- it('sets the content type header on multi part forms', (done) => {
- w.webContents.on('did-finish-load', () => {
- w.webContents.session.webRequest.onBeforeSendHeaders((details, callback) => {
- assert(details.requestHeaders['content-type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary'))
- done()
- })
- w.webContents.executeJavaScript(`
- form = document.createElement('form')
- document.body.appendChild(form)
- form.method = 'POST'
- form.target = '_blank'
- form.enctype = 'multipart/form-data'
- file = document.createElement('input')
- file.type = 'file'
- file.name = 'file'
- form.appendChild(file)
- form.submit()
- `)
- })
- w.loadURL(server.url)
- })
- })
- it('should support support base url for data urls', (done) => {
- ipcMain.once('answer', (event, test) => {
- assert.equal(test, 'test')
- done()
- })
- w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', {baseURLForDataURL: `file://${path.join(fixtures, 'api')}${path.sep}`})
- })
- })
- describe('will-navigate event', () => {
- it('allows the window to be closed from the event listener', (done) => {
- ipcRenderer.send('close-on-will-navigate', w.id)
- ipcRenderer.once('closed-on-will-navigate', () => { done() })
- w.loadURL(`file://${fixtures}/pages/will-navigate.html`)
- })
- })
- describe('BrowserWindow.show()', () => {
- before(function () {
- if (isCI) {
- this.skip()
- }
- })
- it('should focus on window', () => {
- w.show()
- assert(w.isFocused())
- })
- it('should make the window visible', () => {
- w.show()
- assert(w.isVisible())
- })
- it('emits when window is shown', (done) => {
- w.once('show', () => {
- assert.equal(w.isVisible(), true)
- done()
- })
- w.show()
- })
- })
- describe('BrowserWindow.hide()', () => {
- before(function () {
- if (isCI) {
- this.skip()
- }
- })
- it('should defocus on window', () => {
- w.hide()
- assert(!w.isFocused())
- })
- it('should make the window not visible', () => {
- w.show()
- w.hide()
- assert(!w.isVisible())
- })
- it('emits when window is hidden', (done) => {
- w.show()
- w.once('hide', () => {
- assert.equal(w.isVisible(), false)
- done()
- })
- w.hide()
- })
- })
- describe('BrowserWindow.showInactive()', () => {
- it('should not focus on window', () => {
- w.showInactive()
- assert(!w.isFocused())
- })
- })
- describe('BrowserWindow.focus()', () => {
- it('does not make the window become visible', () => {
- assert.equal(w.isVisible(), false)
- w.focus()
- assert.equal(w.isVisible(), false)
- })
- })
- describe('BrowserWindow.blur()', () => {
- it('removes focus from window', () => {
- w.blur()
- assert(!w.isFocused())
- })
- })
- describe('BrowserWindow.getFocusedWindow()', (done) => {
- it('returns the opener window when dev tools window is focused', (done) => {
- w.show()
- w.webContents.once('devtools-focused', () => {
- assert.deepEqual(BrowserWindow.getFocusedWindow(), w)
- done()
- })
- w.webContents.openDevTools({mode: 'undocked'})
- })
- })
- describe('BrowserWindow.capturePage(rect, callback)', () => {
- it('calls the callback with a Buffer', (done) => {
- w.capturePage({
- x: 0,
- y: 0,
- width: 100,
- height: 100
- }, (image) => {
- assert.equal(image.isEmpty(), true)
- done()
- })
- })
- it('preserves transparency', (done) => {
- w.close()
- const width = 400
- const height = 400
- w = new BrowserWindow({
- show: false,
- width: width,
- height: height,
- transparent: true
- })
- w.loadURL('data:text/html,<html><body background-color: rgba(255,255,255,0)></body></html>')
- w.once('ready-to-show', () => {
- w.show()
- w.capturePage((image) => {
- let imgBuffer = image.toPNG()
- // Check 25th byte in the PNG
- // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
- assert.equal(imgBuffer[25], 6)
- done()
- })
- })
- })
- })
- describe('BrowserWindow.setSize(width, height)', () => {
- it('sets the window size', (done) => {
- const size = [300, 400]
- w.once('resize', () => {
- assertBoundsEqual(w.getSize(), size)
- done()
- })
- w.setSize(size[0], size[1])
- })
- })
- describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
- it('sets the maximum and minimum size of the window', () => {
- assert.deepEqual(w.getMinimumSize(), [0, 0])
- assert.deepEqual(w.getMaximumSize(), [0, 0])
- w.setMinimumSize(100, 100)
- assertBoundsEqual(w.getMinimumSize(), [100, 100])
- assertBoundsEqual(w.getMaximumSize(), [0, 0])
- w.setMaximumSize(900, 600)
- assertBoundsEqual(w.getMinimumSize(), [100, 100])
- assertBoundsEqual(w.getMaximumSize(), [900, 600])
- })
- })
- describe('BrowserWindow.setAspectRatio(ratio)', () => {
- it('resets the behaviour when passing in 0', (done) => {
- const size = [300, 400]
- w.setAspectRatio(1 / 2)
- w.setAspectRatio(0)
- w.once('resize', () => {
- assertBoundsEqual(w.getSize(), size)
- done()
- })
- w.setSize(size[0], size[1])
- })
- })
- describe('BrowserWindow.setPosition(x, y)', () => {
- it('sets the window position', (done) => {
- const pos = [10, 10]
- w.once('move', () => {
- const newPos = w.getPosition()
- assert.equal(newPos[0], pos[0])
- assert.equal(newPos[1], pos[1])
- done()
- })
- w.setPosition(pos[0], pos[1])
- })
- })
- describe('BrowserWindow.setContentSize(width, height)', () => {
- it('sets the content size', () => {
- const size = [400, 400]
- w.setContentSize(size[0], size[1])
- var after = w.getContentSize()
- assert.equal(after[0], size[0])
- assert.equal(after[1], size[1])
- })
- it('works for a frameless window', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- frame: false,
- width: 400,
- height: 400
- })
- const size = [400, 400]
- w.setContentSize(size[0], size[1])
- const after = w.getContentSize()
- assert.equal(after[0], size[0])
- assert.equal(after[1], size[1])
- })
- })
- describe('BrowserWindow.setContentBounds(bounds)', () => {
- it('sets the content size and position', (done) => {
- const bounds = {x: 10, y: 10, width: 250, height: 250}
- w.once('resize', () => {
- assertBoundsEqual(w.getContentBounds(), bounds)
- done()
- })
- w.setContentBounds(bounds)
- })
- it('works for a frameless window', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- frame: false,
- width: 300,
- height: 300
- })
- const bounds = {x: 10, y: 10, width: 250, height: 250}
- w.once('resize', () => {
- assert.deepEqual(w.getContentBounds(), bounds)
- done()
- })
- w.setContentBounds(bounds)
- })
- })
- describe('BrowserWindow.setProgressBar(progress)', () => {
- it('sets the progress', () => {
- assert.doesNotThrow(() => {
- if (process.platform === 'darwin') {
- app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'))
- }
- w.setProgressBar(0.5)
- if (process.platform === 'darwin') {
- app.dock.setIcon(null)
- }
- w.setProgressBar(-1)
- })
- })
- it('sets the progress using "paused" mode', () => {
- assert.doesNotThrow(() => {
- w.setProgressBar(0.5, {mode: 'paused'})
- })
- })
- it('sets the progress using "error" mode', () => {
- assert.doesNotThrow(() => {
- w.setProgressBar(0.5, {mode: 'error'})
- })
- })
- it('sets the progress using "normal" mode', () => {
- assert.doesNotThrow(() => {
- w.setProgressBar(0.5, {mode: 'normal'})
- })
- })
- })
- describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
- it('sets the window as always on top', () => {
- assert.equal(w.isAlwaysOnTop(), false)
- w.setAlwaysOnTop(true, 'screen-saver')
- assert.equal(w.isAlwaysOnTop(), true)
- w.setAlwaysOnTop(false)
- assert.equal(w.isAlwaysOnTop(), false)
- w.setAlwaysOnTop(true)
- assert.equal(w.isAlwaysOnTop(), true)
- })
- it('raises an error when relativeLevel is out of bounds', function () {
- if (process.platform !== 'darwin') {
- // FIXME(alexeykuzmin): Skip the test instead of marking it as passed.
- // afterEach hook won't be run if a test is skipped dynamically.
- // If afterEach isn't run current window won't be destroyed
- // and the next test will fail on assertion in `closeWindow()`.
- // this.skip()
- return
- }
- assert.throws(() => {
- w.setAlwaysOnTop(true, '', -2147483644)
- })
- assert.throws(() => {
- w.setAlwaysOnTop(true, '', 2147483632)
- })
- })
- })
- describe('BrowserWindow.alwaysOnTop() resets level on minimize', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('resets the windows level on minimize', () => {
- assert.equal(w.isAlwaysOnTop(), false)
- w.setAlwaysOnTop(true, 'screen-saver')
- assert.equal(w.isAlwaysOnTop(), true)
- w.minimize()
- assert.equal(w.isAlwaysOnTop(), false)
- w.restore()
- assert.equal(w.isAlwaysOnTop(), true)
- })
- })
- describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
- describe('on macOS', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('allows changing cursor auto-hiding', () => {
- assert.doesNotThrow(() => {
- w.setAutoHideCursor(false)
- w.setAutoHideCursor(true)
- })
- })
- })
- describe('on non-macOS platforms', () => {
- before(function () {
- if (process.platform === 'darwin') {
- this.skip()
- }
- })
- it('is not available', () => {
- assert.ok(!w.setAutoHideCursor)
- })
- })
- })
- describe('BrowserWindow.selectPreviousTab()', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('does not throw', () => {
- assert.doesNotThrow(() => {
- w.selectPreviousTab()
- })
- })
- })
- describe('BrowserWindow.selectNextTab()', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('does not throw', () => {
- assert.doesNotThrow(() => {
- w.selectNextTab()
- })
- })
- })
- describe('BrowserWindow.mergeAllWindows()', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('does not throw', () => {
- assert.doesNotThrow(() => {
- w.mergeAllWindows()
- })
- })
- })
- describe('BrowserWindow.moveTabToNewWindow()', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('does not throw', () => {
- assert.doesNotThrow(() => {
- w.moveTabToNewWindow()
- })
- })
- })
- describe('BrowserWindow.toggleTabBar()', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('does not throw', () => {
- assert.doesNotThrow(() => {
- w.toggleTabBar()
- })
- })
- })
- describe('BrowserWindow.addTabbedWindow()', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('does not throw', (done) => {
- const tabbedWindow = new BrowserWindow({})
- assert.doesNotThrow(() => {
- w.addTabbedWindow(tabbedWindow)
- })
- assert.equal(BrowserWindow.getAllWindows().length, 3) // Test window + w + tabbedWindow
- closeWindow(tabbedWindow, {assertSingleWindow: false}).then(() => {
- assert.equal(BrowserWindow.getAllWindows().length, 2) // Test window + w
- done()
- })
- })
- it('throws when called on itself', () => {
- assert.throws(() => {
- w.addTabbedWindow(w)
- }, /AddTabbedWindow cannot be called by a window on itself./)
- })
- })
- describe('BrowserWindow.setVibrancy(type)', () => {
- it('allows setting, changing, and removing the vibrancy', () => {
- assert.doesNotThrow(() => {
- w.setVibrancy('light')
- w.setVibrancy('dark')
- w.setVibrancy(null)
- w.setVibrancy('ultra-dark')
- w.setVibrancy('')
- })
- })
- })
- describe('BrowserWindow.setAppDetails(options)', () => {
- before(function () {
- if (process.platform !== 'win32') {
- this.skip()
- }
- })
- it('supports setting the app details', () => {
- const iconPath = path.join(fixtures, 'assets', 'icon.ico')
- assert.doesNotThrow(() => {
- w.setAppDetails({appId: 'my.app.id'})
- w.setAppDetails({appIconPath: iconPath, appIconIndex: 0})
- w.setAppDetails({appIconPath: iconPath})
- w.setAppDetails({relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name'})
- w.setAppDetails({relaunchCommand: 'my-app.exe arg1 arg2'})
- w.setAppDetails({relaunchDisplayName: 'My app name'})
- w.setAppDetails({
- appId: 'my.app.id',
- appIconPath: iconPath,
- appIconIndex: 0,
- relaunchCommand: 'my-app.exe arg1 arg2',
- relaunchDisplayName: 'My app name'
- })
- w.setAppDetails({})
- })
- assert.throws(() => {
- w.setAppDetails()
- }, /Insufficient number of arguments\./)
- })
- })
- describe('BrowserWindow.fromId(id)', () => {
- it('returns the window with id', () => {
- assert.equal(w.id, BrowserWindow.fromId(w.id).id)
- })
- })
- describe('BrowserWindow.fromWebContents(webContents)', () => {
- let contents = null
- beforeEach(() => { contents = webContents.create({}) })
- afterEach(() => { contents.destroy() })
- it('returns the window with the webContents', () => {
- assert.equal(BrowserWindow.fromWebContents(w.webContents).id, w.id)
- assert.equal(BrowserWindow.fromWebContents(contents), undefined)
- })
- })
- describe('BrowserWindow.fromDevToolsWebContents(webContents)', () => {
- let contents = null
- beforeEach(() => { contents = webContents.create({}) })
- afterEach(() => { contents.destroy() })
- it('returns the window with the webContents', (done) => {
- w.webContents.once('devtools-opened', () => {
- assert.equal(BrowserWindow.fromDevToolsWebContents(w.devToolsWebContents).id, w.id)
- assert.equal(BrowserWindow.fromDevToolsWebContents(w.webContents), undefined)
- assert.equal(BrowserWindow.fromDevToolsWebContents(contents), undefined)
- done()
- })
- w.webContents.openDevTools()
- })
- })
- describe('BrowserWindow.fromBrowserView(browserView)', () => {
- let bv = null
- beforeEach(() => {
- bv = new BrowserView()
- w.setBrowserView(bv)
- })
- afterEach(() => {
- w.setBrowserView(null)
- bv.destroy()
- })
- it('returns the window with the browserView', () => {
- assert.equal(BrowserWindow.fromBrowserView(bv).id, w.id)
- })
- it('returns undefined if not attached', () => {
- w.setBrowserView(null)
- assert.equal(BrowserWindow.fromBrowserView(bv), undefined)
- })
- })
- describe('BrowserWindow.setOpacity(opacity)', () => {
- it('make window with initial opacity', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- width: 400,
- height: 400,
- opacity: 0.5
- })
- assert.equal(w.getOpacity(), 0.5)
- })
- it('allows setting the opacity', () => {
- assert.doesNotThrow(() => {
- w.setOpacity(0.0)
- assert.equal(w.getOpacity(), 0.0)
- w.setOpacity(0.5)
- assert.equal(w.getOpacity(), 0.5)
- w.setOpacity(1.0)
- assert.equal(w.getOpacity(), 1.0)
- })
- })
- })
- describe('"useContentSize" option', () => {
- it('make window created with content size when used', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- width: 400,
- height: 400,
- useContentSize: true
- })
- const contentSize = w.getContentSize()
- assert.equal(contentSize[0], 400)
- assert.equal(contentSize[1], 400)
- })
- it('make window created with window size when not used', () => {
- const size = w.getSize()
- assert.equal(size[0], 400)
- assert.equal(size[1], 400)
- })
- it('works for a frameless window', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- frame: false,
- width: 400,
- height: 400,
- useContentSize: true
- })
- const contentSize = w.getContentSize()
- assert.equal(contentSize[0], 400)
- assert.equal(contentSize[1], 400)
- const size = w.getSize()
- assert.equal(size[0], 400)
- assert.equal(size[1], 400)
- })
- })
- describe('"titleBarStyle" option', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- if (parseInt(os.release().split('.')[0]) < 14) {
- this.skip()
- }
- })
- it('creates browser window with hidden title bar', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- width: 400,
- height: 400,
- titleBarStyle: 'hidden'
- })
- const contentSize = w.getContentSize()
- assert.equal(contentSize[1], 400)
- })
- it('creates browser window with hidden inset title bar', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- width: 400,
- height: 400,
- titleBarStyle: 'hiddenInset'
- })
- const contentSize = w.getContentSize()
- assert.equal(contentSize[1], 400)
- })
- })
- describe('enableLargerThanScreen" option', () => {
- before(function () {
- if (process.platform === 'linux') {
- this.skip()
- }
- })
- beforeEach(() => {
- w.destroy()
- w = new BrowserWindow({
- show: true,
- width: 400,
- height: 400,
- enableLargerThanScreen: true
- })
- })
- it('can move the window out of screen', () => {
- w.setPosition(-10, -10)
- const after = w.getPosition()
- assert.equal(after[0], -10)
- assert.equal(after[1], -10)
- })
- it('can set the window larger than screen', () => {
- const size = screen.getPrimaryDisplay().size
- size.width += 100
- size.height += 100
- w.setSize(size.width, size.height)
- assertBoundsEqual(w.getSize(), [size.width, size.height])
- })
- })
- describe('"zoomToPageWidth" option', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('sets the window width to the page width when used', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- width: 500,
- height: 400,
- zoomToPageWidth: true
- })
- w.maximize()
- assert.equal(w.getSize()[0], 500)
- })
- })
- describe('"tabbingIdentifier" option', () => {
- it('can be set on a window', () => {
- w.destroy()
- w = new BrowserWindow({
- tabbingIdentifier: 'group1'
- })
- w.destroy()
- w = new BrowserWindow({
- tabbingIdentifier: 'group2',
- frame: false
- })
- })
- })
- describe('"webPreferences" option', () => {
- afterEach(() => { ipcMain.removeAllListeners('answer') })
- describe('"preload" option', () => {
- it('loads the script before other scripts in window', (done) => {
- const preload = path.join(fixtures, 'module', 'set-global.js')
- ipcMain.once('answer', (event, test) => {
- assert.equal(test, 'preload')
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload
- }
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'preload.html')}`)
- })
- it('can successfully delete the Buffer global', (done) => {
- const preload = path.join(fixtures, 'module', 'delete-buffer.js')
- ipcMain.once('answer', (event, test) => {
- assert.equal(test.toString(), 'buffer')
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload
- }
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'preload.html')}`)
- })
- })
- describe('session preload scripts', function () {
- const preloads = [
- path.join(fixtures, 'module', 'set-global-preload-1.js'),
- path.join(fixtures, 'module', 'set-global-preload-2.js')
- ]
- const defaultSession = session.defaultSession
- beforeEach(() => {
- assert.deepEqual(defaultSession.getPreloads(), [])
- defaultSession.setPreloads(preloads)
- })
- afterEach(() => {
- defaultSession.setPreloads([])
- })
- it('can set multiple session preload script', function () {
- assert.deepEqual(defaultSession.getPreloads(), preloads)
- })
- it('loads the script before other scripts in window including normal preloads', function (done) {
- ipcMain.once('vars', function (event, preload1, preload2, preload3) {
- assert.equal(preload1, 'preload-1')
- assert.equal(preload2, 'preload-1-2')
- assert.equal(preload3, 'preload-1-2-3')
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: path.join(fixtures, 'module', 'set-global-preload-3.js')
- }
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'preloads.html'))
- })
- })
- describe('"additionalArguments" option', () => {
- it('adds extra args to process.argv in the renderer process', (done) => {
- const preload = path.join(fixtures, 'module', 'check-arguments.js')
- ipcMain.once('answer', (event, argv) => {
- assert.ok(argv.includes('--my-magic-arg'))
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload,
- additionalArguments: ['--my-magic-arg']
- }
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'blank.html')}`)
- })
- it('adds extra value args to process.argv in the renderer process', (done) => {
- const preload = path.join(fixtures, 'module', 'check-arguments.js')
- ipcMain.once('answer', (event, argv) => {
- assert.ok(argv.includes('--my-magic-arg=foo'))
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload,
- additionalArguments: ['--my-magic-arg=foo']
- }
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'blank.html')}`)
- })
- })
- describe('"node-integration" option', () => {
- it('disables node integration when specified to false', (done) => {
- const preload = path.join(fixtures, 'module', 'send-later.js')
- ipcMain.once('answer', (event, typeofProcess, typeofBuffer) => {
- assert.equal(typeofProcess, 'undefined')
- assert.equal(typeofBuffer, 'undefined')
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload,
- nodeIntegration: false
- }
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'blank.html')}`)
- })
- })
- describe('"sandbox" option', () => {
- function waitForEvents (emitter, events, callback) {
- let count = events.length
- for (let event of events) {
- emitter.once(event, () => {
- if (!--count) callback()
- })
- }
- }
- const preload = path.join(fixtures, 'module', 'preload-sandbox.js')
- // http protocol to simulate accessing another domain. This is required
- // because the code paths for cross domain popups is different.
- function crossDomainHandler (request, callback) {
- // Disabled due to false positive in StandardJS
- // eslint-disable-next-line standard/no-callback-literal
- callback({
- mimeType: 'text/html',
- data: `<html><body><h1>${request.url}</h1></body></html>`
- })
- }
- before((done) => {
- protocol.interceptStringProtocol('http', crossDomainHandler, () => {
- done()
- })
- })
- after((done) => {
- protocol.uninterceptProtocol('http', () => {
- done()
- })
- })
- it('exposes ipcRenderer to preload script', (done) => {
- ipcMain.once('answer', function (event, test) {
- assert.equal(test, 'preload')
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html'))
- })
- it('exposes ipcRenderer to preload script (path has special chars)', function (done) {
- const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js')
- ipcMain.once('answer', function (event, test) {
- assert.equal(test, 'preload')
- done()
- })
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preloadSpecialChars
- }
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html'))
- })
- it('exposes "exit" event to preload script', function (done) {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- let htmlPath = path.join(fixtures, 'api', 'sandbox.html?exit-event')
- const pageUrl = 'file://' + htmlPath
- w.loadURL(pageUrl)
- ipcMain.once('answer', function (event, url) {
- let expectedUrl = pageUrl
- if (process.platform === 'win32') {
- expectedUrl = 'file:///' + htmlPath.replace(/\\/g, '/')
- }
- assert.equal(url, expectedUrl)
- done()
- })
- })
- it('should open windows in same domain with cross-scripting enabled', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
- let htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open')
- const pageUrl = 'file://' + htmlPath
- w.loadURL(pageUrl)
- w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
- let expectedUrl = pageUrl
- if (process.platform === 'win32') {
- expectedUrl = 'file:///' + htmlPath.replace(/\\/g, '/')
- }
- assert.equal(url, expectedUrl)
- assert.equal(frameName, 'popup!')
- assert.equal(options.width, 500)
- assert.equal(options.height, 600)
- ipcMain.once('answer', function (event, html) {
- assert.equal(html, '<h1>scripting from opener</h1>')
- done()
- })
- })
- })
- it('should open windows in another domain with cross-scripting disabled', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preload)
- let htmlPath = path.join(fixtures, 'api', 'sandbox.html?window-open-external')
- const pageUrl = 'file://' + htmlPath
- let popupWindow
- w.loadURL(pageUrl)
- w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
- assert.equal(url, 'http://www.google.com/#q=electron')
- assert.equal(options.width, 505)
- assert.equal(options.height, 605)
- ipcMain.once('child-loaded', function (event, openerIsNull, html) {
- assert(openerIsNull)
- assert.equal(html, '<h1>http://www.google.com/#q=electron</h1>')
- ipcMain.once('answer', function (event, exceptionMessage) {
- assert(/Blocked a frame with origin/.test(exceptionMessage))
- // FIXME this popup window should be closed in sandbox.html
- closeWindow(popupWindow, {assertSingleWindow: false}).then(() => {
- popupWindow = null
- done()
- })
- })
- w.webContents.send('child-loaded')
- })
- })
- app.once('browser-window-created', function (event, window) {
- popupWindow = window
- })
- })
- it('should inherit the sandbox setting in opened windows', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true
- }
- })
- const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
- ipcMain.once('answer', (event, args) => {
- assert.equal(args.includes('--enable-sandbox'), true)
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
- })
- it('should open windows with the options configured via new-window event listeners', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true
- }
- })
- const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'foo', 'bar')
- ipcMain.once('answer', (event, args, webPreferences) => {
- assert.equal(webPreferences.foo, 'bar')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
- })
- it('should set ipc event sender correctly', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- let htmlPath = path.join(fixtures, 'api', 'sandbox.html?verify-ipc-sender')
- const pageUrl = 'file://' + htmlPath
- w.loadURL(pageUrl)
- w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
- let parentWc = w.webContents
- let childWc = options.webContents
- assert.notEqual(parentWc, childWc)
- ipcMain.once('parent-ready', function (event) {
- assert.equal(parentWc, event.sender)
- parentWc.send('verified')
- })
- ipcMain.once('child-ready', function (event) {
- assert.equal(childWc, event.sender)
- childWc.send('verified')
- })
- waitForEvents(ipcMain, [
- 'parent-answer',
- 'child-answer'
- ], done)
- })
- })
- describe('event handling', () => {
- it('works for window events', (done) => {
- waitForEvents(w, [
- 'page-title-updated'
- ], done)
- w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?window-events'))
- })
- it('works for stop events', (done) => {
- waitForEvents(w.webContents, [
- 'did-navigate',
- 'did-fail-load',
- 'did-stop-loading'
- ], done)
- w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?webcontents-stop'))
- })
- it('works for web contents events', (done) => {
- waitForEvents(w.webContents, [
- 'did-finish-load',
- 'did-frame-finish-load',
- 'did-navigate-in-page',
- 'will-navigate',
- 'did-start-loading',
- 'did-stop-loading',
- 'did-frame-finish-load',
- 'dom-ready'
- ], done)
- w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?webcontents-events'))
- })
- })
- it('can get printer list', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
- w.webContents.once('did-finish-load', () => {
- const printers = w.webContents.getPrinters()
- assert.equal(Array.isArray(printers), true)
- done()
- })
- })
- it('can print to PDF', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- w.loadURL('data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E')
- w.webContents.once('did-finish-load', () => {
- w.webContents.printToPDF({}, function (error, data) {
- assert.equal(error, null)
- assert.equal(data instanceof Buffer, true)
- assert.notEqual(data.length, 0)
- done()
- })
- })
- })
- it('supports calling preventDefault on new-window events', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true
- }
- })
- const initialWebContents = webContents.getAllWebContents().map((i) => i.id)
- ipcRenderer.send('prevent-next-new-window', w.webContents.id)
- w.webContents.once('new-window', () => {
- // We need to give it some time so the windows get properly disposed (at least on OSX).
- setTimeout(() => {
- const currentWebContents = webContents.getAllWebContents().map((i) => i.id)
- assert.deepEqual(currentWebContents, initialWebContents)
- done()
- }, 100)
- })
- w.loadURL('file://' + path.join(fixtures, 'pages', 'window-open.html'))
- })
- it('releases memory after popup is closed', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload,
- sandbox: true
- }
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?allocate-memory'))
- ipcMain.once('answer', function (event, {bytesBeforeOpen, bytesAfterOpen, bytesAfterClose}) {
- const memoryIncreaseByOpen = bytesAfterOpen - bytesBeforeOpen
- const memoryDecreaseByClose = bytesAfterOpen - bytesAfterClose
- // decreased memory should be less than increased due to factors we
- // can't control, but given the amount of memory allocated in the
- // fixture, we can reasonably expect decrease to be at least 70% of
- // increase
- assert(memoryDecreaseByClose > memoryIncreaseByOpen * 0.7)
- done()
- })
- })
- // see #9387
- it('properly manages remote object references after page reload', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload,
- sandbox: true
- }
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?reload-remote'))
- ipcMain.on('get-remote-module-path', (event) => {
- event.returnValue = path.join(fixtures, 'module', 'hello.js')
- })
- let reload = false
- ipcMain.on('reloaded', (event) => {
- event.returnValue = reload
- reload = !reload
- })
- ipcMain.once('reload', (event) => {
- event.sender.reload()
- })
- ipcMain.once('answer', (event, arg) => {
- ipcMain.removeAllListeners('reloaded')
- ipcMain.removeAllListeners('get-remote-module-path')
- assert.equal(arg, 'hi')
- done()
- })
- })
- it('properly manages remote object references after page reload in child window', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- preload: preload,
- sandbox: true
- }
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'sandbox.html?reload-remote-child'))
- ipcMain.on('get-remote-module-path', (event) => {
- event.returnValue = path.join(fixtures, 'module', 'hello-child.js')
- })
- let reload = false
- ipcMain.on('reloaded', (event) => {
- event.returnValue = reload
- reload = !reload
- })
- ipcMain.once('reload', (event) => {
- event.sender.reload()
- })
- ipcMain.once('answer', (event, arg) => {
- ipcMain.removeAllListeners('reloaded')
- ipcMain.removeAllListeners('get-remote-module-path')
- assert.equal(arg, 'hi child window')
- done()
- })
- })
- it('validate process.env access in sandbox renderer', (done) => {
- ipcMain.once('answer', function (event, test) {
- assert.equal(test, 'foo')
- done()
- })
- remote.process.env.sandboxmain = 'foo'
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- preload: preload
- }
- })
- w.loadURL('file://' + path.join(fixtures, 'api', 'preload.html'))
- })
- })
- describe('nativeWindowOpen option', () => {
- beforeEach(() => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- nativeWindowOpen: true
- }
- })
- })
- it('opens window of about:blank with cross-scripting enabled', (done) => {
- ipcMain.once('answer', (event, content) => {
- assert.equal(content, 'Hello')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}`)
- })
- it('opens window of same domain with cross-scripting enabled', (done) => {
- ipcMain.once('answer', (event, content) => {
- assert.equal(content, 'Hello')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'native-window-open-file.html')}`)
- })
- it('blocks accessing cross-origin frames', (done) => {
- ipcMain.once('answer', (event, content) => {
- assert.equal(content, 'Blocked a frame with origin "file://" from accessing a cross-origin frame.')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}`)
- })
- it('opens window from <iframe> tags', (done) => {
- ipcMain.once('answer', (event, content) => {
- assert.equal(content, 'Hello')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'native-window-open-iframe.html')}`)
- })
- it('loads native addons correctly after reload', (done) => {
- if (!nativeModulesEnabled) return done()
- ipcMain.once('answer', (event, content) => {
- assert.equal(content, 'function')
- ipcMain.once('answer', (event, content) => {
- assert.equal(content, 'function')
- done()
- })
- w.reload()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'native-window-open-native-addon.html')}`)
- })
- it('should inherit the nativeWindowOpen setting in opened windows', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- nativeWindowOpen: true
- }
- })
- const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
- ipcMain.once('answer', (event, args) => {
- assert.equal(args.includes('--native-window-open'), true)
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
- })
- it('should open windows with the options configured via new-window event listeners', (done) => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- nativeWindowOpen: true
- }
- })
- const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js')
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', preloadPath)
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'foo', 'bar')
- ipcMain.once('answer', (event, args, webPreferences) => {
- assert.equal(webPreferences.foo, 'bar')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'new-window.html')}`)
- })
- it('retains the original web preferences when window.location is changed to a new origin', async () => {
- await serveFileFromProtocol('foo', path.join(fixtures, 'api', 'window-open-location-change.html'))
- await serveFileFromProtocol('bar', path.join(fixtures, 'api', 'window-open-location-final.html'))
- w.destroy()
- w = new BrowserWindow({
- show: true,
- webPreferences: {
- nodeIntegration: false,
- nativeWindowOpen: true
- }
- })
- return new Promise((resolve, reject) => {
- ipcRenderer.send('set-web-preferences-on-next-new-window', w.webContents.id, 'preload', path.join(fixtures, 'api', 'window-open-preload.js'))
- ipcMain.once('answer', (event, args, typeofProcess) => {
- assert.equal(args.includes('--node-integration=false'), true)
- assert.equal(args.includes('--native-window-open'), true)
- assert.equal(typeofProcess, 'undefined')
- resolve()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'window-open-location-open.html')}`)
- })
- })
- })
- })
- describe('nativeWindowOpen + contextIsolation options', () => {
- beforeEach(() => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- nativeWindowOpen: true,
- contextIsolation: true,
- preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
- }
- })
- })
- it('opens window with cross-scripting enabled from isolated context', (done) => {
- ipcMain.once('answer', (event, content) => {
- assert.equal(content, 'Hello')
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'native-window-open-isolated.html')}`)
- })
- })
- describe('beforeunload handler', () => {
- it('returning undefined would not prevent close', (done) => {
- w.once('closed', () => { done() })
- w.loadURL('file://' + path.join(fixtures, 'api', 'close-beforeunload-undefined.html'))
- })
- it('returning false would prevent close', (done) => {
- w.once('onbeforeunload', () => { done() })
- w.loadURL(`file://${path.join(fixtures, 'api', 'close-beforeunload-false.html')}`)
- })
- it('returning empty string would prevent close', (done) => {
- w.once('onbeforeunload', () => { done() })
- w.loadURL(`file://${path.join(fixtures, 'api', 'close-beforeunload-empty-string.html')}`)
- })
- it('emits for each close attempt', (done) => {
- let beforeUnloadCount = 0
- w.on('onbeforeunload', () => {
- beforeUnloadCount += 1
- if (beforeUnloadCount < 3) {
- w.close()
- } else if (beforeUnloadCount === 3) {
- done()
- }
- })
- w.webContents.once('did-finish-load', () => { w.close() })
- w.loadURL(`file://${path.join(fixtures, 'api', 'beforeunload-false-prevent3.html')}`)
- })
- it('emits for each reload attempt', (done) => {
- let beforeUnloadCount = 0
- w.on('onbeforeunload', () => {
- beforeUnloadCount += 1
- if (beforeUnloadCount < 3) {
- w.reload()
- } else if (beforeUnloadCount === 3) {
- done()
- }
- })
- w.webContents.once('did-finish-load', () => {
- w.webContents.once('did-finish-load', () => {
- assert.fail('Reload was not prevented')
- })
- w.reload()
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'beforeunload-false-prevent3.html')}`)
- })
- it('emits for each navigation attempt', (done) => {
- let beforeUnloadCount = 0
- w.on('onbeforeunload', () => {
- beforeUnloadCount += 1
- if (beforeUnloadCount < 3) {
- w.loadURL('about:blank')
- } else if (beforeUnloadCount === 3) {
- done()
- }
- })
- w.webContents.once('did-finish-load', () => {
- w.webContents.once('did-finish-load', () => {
- assert.fail('Navigation was not prevented')
- })
- w.loadURL('about:blank')
- })
- w.loadURL(`file://${path.join(fixtures, 'api', 'beforeunload-false-prevent3.html')}`)
- })
- })
- describe('document.visibilityState/hidden', () => {
- beforeEach(() => { w.destroy() })
- function onVisibilityChange (callback) {
- ipcMain.on('pong', (event, visibilityState, hidden) => {
- if (event.sender.id === w.webContents.id) {
- callback(visibilityState, hidden)
- }
- })
- }
- function onNextVisibilityChange (callback) {
- ipcMain.once('pong', (event, visibilityState, hidden) => {
- if (event.sender.id === w.webContents.id) {
- callback(visibilityState, hidden)
- }
- })
- }
- afterEach(() => { ipcMain.removeAllListeners('pong') })
- it('visibilityState is initially visible despite window being hidden', (done) => {
- w = new BrowserWindow({ show: false, width: 100, height: 100 })
- let readyToShow = false
- w.once('ready-to-show', () => {
- readyToShow = true
- })
- onNextVisibilityChange((visibilityState, hidden) => {
- assert.equal(readyToShow, false)
- assert.equal(visibilityState, 'visible')
- assert.equal(hidden, false)
- done()
- })
- w.loadURL(`file://${path.join(fixtures, 'pages', 'visibilitychange.html')}`)
- })
- it('visibilityState changes when window is hidden', (done) => {
- w = new BrowserWindow({width: 100, height: 100})
- onNextVisibilityChange((visibilityState, hidden) => {
- assert.equal(visibilityState, 'visible')
- assert.equal(hidden, false)
- onNextVisibilityChange((visibilityState, hidden) => {
- assert.equal(visibilityState, 'hidden')
- assert.equal(hidden, true)
- done()
- })
- w.hide()
- })
- w.loadURL(`file://${path.join(fixtures, 'pages', 'visibilitychange.html')}`)
- })
- it('visibilityState changes when window is shown', (done) => {
- w = new BrowserWindow({width: 100, height: 100})
- onNextVisibilityChange((visibilityState, hidden) => {
- onVisibilityChange((visibilityState, hidden) => {
- if (!hidden) {
- assert.equal(visibilityState, 'visible')
- done()
- }
- })
- w.hide()
- w.show()
- })
- w.loadURL(`file://${path.join(fixtures, 'pages', 'visibilitychange.html')}`)
- })
- it('visibilityState changes when window is shown inactive', function (done) {
- if (isCI && process.platform === 'win32') {
- // FIXME(alexeykuzmin): Skip the test instead of marking it as passed.
- // afterEach hook won't be run if a test is skipped dynamically.
- // If afterEach isn't run current window won't be destroyed
- // and the next test will fail on assertion in `closeWindow()`.
- // this.skip()
- return done()
- }
- w = new BrowserWindow({width: 100, height: 100})
- onNextVisibilityChange((visibilityState, hidden) => {
- onVisibilityChange((visibilityState, hidden) => {
- if (!hidden) {
- assert.equal(visibilityState, 'visible')
- done()
- }
- })
- w.hide()
- w.showInactive()
- })
- w.loadURL(`file://${path.join(fixtures, 'pages', 'visibilitychange.html')}`)
- })
- it('visibilityState changes when window is minimized', function (done) {
- if (isCI && process.platform === 'linux') {
- // FIXME(alexeykuzmin): Skip the test instead of marking it as passed.
- // afterEach hook won't be run if a test is skipped dynamically.
- // If afterEach isn't run current window won't be destroyed
- // and the next test will fail on assertion in `closeWindow()`.
- // this.skip()
- return done()
- }
- w = new BrowserWindow({width: 100, height: 100})
- onNextVisibilityChange((visibilityState, hidden) => {
- assert.equal(visibilityState, 'visible')
- assert.equal(hidden, false)
- onNextVisibilityChange((visibilityState, hidden) => {
- assert.equal(visibilityState, 'hidden')
- assert.equal(hidden, true)
- done()
- })
- w.minimize()
- })
- w.loadURL(`file://${path.join(fixtures, 'pages', 'visibilitychange.html')}`)
- })
- it('visibilityState remains visible if backgroundThrottling is disabled', (done) => {
- w = new BrowserWindow({
- show: false,
- width: 100,
- height: 100,
- webPreferences: {
- backgroundThrottling: false
- }
- })
- onNextVisibilityChange((visibilityState, hidden) => {
- assert.equal(visibilityState, 'visible')
- assert.equal(hidden, false)
- onNextVisibilityChange((visibilityState, hidden) => {
- done(new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`))
- })
- })
- w.once('show', () => {
- w.once('hide', () => {
- w.once('show', () => {
- done()
- })
- w.show()
- })
- w.hide()
- })
- w.show()
- w.loadURL(`file://${path.join(fixtures, 'pages', 'visibilitychange.html')}`)
- })
- })
- describe('new-window event', () => {
- before(function () {
- if (isCI && process.platform === 'darwin') {
- this.skip()
- }
- })
- it('emits when window.open is called', (done) => {
- w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures) => {
- e.preventDefault()
- assert.equal(url, 'http://host/')
- assert.equal(frameName, 'host')
- assert.equal(additionalFeatures[0], 'this-is-not-a-standard-feature')
- done()
- })
- w.loadURL(`file://${fixtures}/pages/window-open.html`)
- })
- it('emits when window.open is called with no webPreferences', (done) => {
- w.destroy()
- w = new BrowserWindow({ show: false })
- w.webContents.once('new-window', function (e, url, frameName, disposition, options, additionalFeatures) {
- e.preventDefault()
- assert.equal(url, 'http://host/')
- assert.equal(frameName, 'host')
- assert.equal(additionalFeatures[0], 'this-is-not-a-standard-feature')
- done()
- })
- w.loadURL(`file://${fixtures}/pages/window-open.html`)
- })
- it('emits when link with target is called', (done) => {
- w.webContents.once('new-window', (e, url, frameName) => {
- e.preventDefault()
- assert.equal(url, 'http://host/')
- assert.equal(frameName, 'target')
- done()
- })
- w.loadURL(`file://${fixtures}/pages/target-name.html`)
- })
- })
- describe('maximize event', () => {
- if (isCI) return
- it('emits when window is maximized', (done) => {
- w.once('maximize', () => { done() })
- w.show()
- w.maximize()
- })
- })
- describe('unmaximize event', () => {
- if (isCI) return
- it('emits when window is unmaximized', (done) => {
- w.once('unmaximize', () => { done() })
- w.show()
- w.maximize()
- w.unmaximize()
- })
- })
- describe('minimize event', () => {
- if (isCI) return
- it('emits when window is minimized', (done) => {
- w.once('minimize', () => { done() })
- w.show()
- w.minimize()
- })
- })
- describe('sheet-begin event', () => {
- let sheet = null
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- afterEach(() => {
- return closeWindow(sheet, {assertSingleWindow: false}).then(() => { sheet = null })
- })
- it('emits when window opens a sheet', (done) => {
- w.show()
- w.once('sheet-begin', () => {
- sheet.close()
- done()
- })
- sheet = new BrowserWindow({
- modal: true,
- parent: w
- })
- })
- })
- describe('sheet-end event', () => {
- let sheet = null
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- afterEach(() => {
- return closeWindow(sheet, {assertSingleWindow: false}).then(() => { sheet = null })
- })
- it('emits when window has closed a sheet', (done) => {
- w.show()
- sheet = new BrowserWindow({
- modal: true,
- parent: w
- })
- w.once('sheet-end', () => { done() })
- sheet.close()
- })
- })
- describe('beginFrameSubscription method', () => {
- before(function () {
- // This test is too slow, only test it on CI.
- if (!isCI) {
- this.skip()
- }
- // FIXME These specs crash on Linux when run in a docker container
- if (isCI && process.platform === 'linux') {
- this.skip()
- }
- })
- it('subscribes to frame updates', (done) => {
- let called = false
- w.loadURL(`file://${fixtures}/api/frame-subscriber.html`)
- w.webContents.on('dom-ready', () => {
- w.webContents.beginFrameSubscription(function (data) {
- // This callback might be called twice.
- if (called) return
- called = true
- assert.notEqual(data.length, 0)
- w.webContents.endFrameSubscription()
- done()
- })
- })
- })
- it('subscribes to frame updates (only dirty rectangle)', (done) => {
- let called = false
- w.loadURL(`file://${fixtures}/api/frame-subscriber.html`)
- w.webContents.on('dom-ready', () => {
- w.webContents.beginFrameSubscription(true, (data) => {
- // This callback might be called twice.
- if (called) return
- called = true
- assert.notEqual(data.length, 0)
- w.webContents.endFrameSubscription()
- done()
- })
- })
- })
- it('throws error when subscriber is not well defined', (done) => {
- w.loadURL(`file://${fixtures}'/api/frame-subscriber.html`)
- try {
- w.webContents.beginFrameSubscription(true, true)
- } catch (e) {
- done()
- }
- })
- })
- describe('savePage method', () => {
- const savePageDir = path.join(fixtures, 'save_page')
- const savePageHtmlPath = path.join(savePageDir, 'save_page.html')
- const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js')
- const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css')
- after(() => {
- try {
- fs.unlinkSync(savePageCssPath)
- fs.unlinkSync(savePageJsPath)
- fs.unlinkSync(savePageHtmlPath)
- fs.rmdirSync(path.join(savePageDir, 'save_page_files'))
- fs.rmdirSync(savePageDir)
- } catch (e) {
- // Ignore error
- }
- })
- it('should save page to disk', (done) => {
- w.webContents.on('did-finish-load', () => {
- w.webContents.savePage(savePageHtmlPath, 'HTMLComplete', function (error) {
- assert.equal(error, null)
- assert(fs.existsSync(savePageHtmlPath))
- assert(fs.existsSync(savePageJsPath))
- assert(fs.existsSync(savePageCssPath))
- done()
- })
- })
- w.loadURL('file://' + fixtures + '/pages/save_page/index.html')
- })
- })
- describe('BrowserWindow options argument is optional', () => {
- it('should create a window with default size (800x600)', () => {
- w.destroy()
- w = new BrowserWindow()
- const size = w.getSize()
- assert.equal(size[0], 800)
- assert.equal(size[1], 600)
- })
- })
- describe('window states', () => {
- it('does not resize frameless windows when states change', () => {
- w.destroy()
- w = new BrowserWindow({
- frame: false,
- width: 300,
- height: 200,
- show: false
- })
- w.setMinimizable(false)
- w.setMinimizable(true)
- assert.deepEqual(w.getSize(), [300, 200])
- w.setResizable(false)
- w.setResizable(true)
- assert.deepEqual(w.getSize(), [300, 200])
- w.setMaximizable(false)
- w.setMaximizable(true)
- assert.deepEqual(w.getSize(), [300, 200])
- w.setFullScreenable(false)
- w.setFullScreenable(true)
- assert.deepEqual(w.getSize(), [300, 200])
- w.setClosable(false)
- w.setClosable(true)
- assert.deepEqual(w.getSize(), [300, 200])
- })
- describe('resizable state', () => {
- it('can be changed with resizable option', () => {
- w.destroy()
- w = new BrowserWindow({show: false, resizable: false})
- assert.equal(w.isResizable(), false)
- if (process.platform === 'darwin') {
- assert.equal(w.isMaximizable(), true)
- }
- })
- it('can be changed with setResizable method', () => {
- assert.equal(w.isResizable(), true)
- w.setResizable(false)
- assert.equal(w.isResizable(), false)
- w.setResizable(true)
- assert.equal(w.isResizable(), true)
- })
- it('works for a frameless window', () => {
- w.destroy()
- w = new BrowserWindow({show: false, frame: false})
- assert.equal(w.isResizable(), true)
- if (process.platform === 'win32') {
- w.destroy()
- w = new BrowserWindow({show: false, thickFrame: false})
- assert.equal(w.isResizable(), false)
- }
- })
- if (process.platform === 'win32') {
- it('works for a window smaller than 64x64', () => {
- w.destroy()
- w = new BrowserWindow({
- show: false,
- frame: false,
- resizable: false,
- transparent: true
- })
- w.setContentSize(60, 60)
- assertBoundsEqual(w.getContentSize(), [60, 60])
- w.setContentSize(30, 30)
- assertBoundsEqual(w.getContentSize(), [30, 30])
- w.setContentSize(10, 10)
- assertBoundsEqual(w.getContentSize(), [10, 10])
- })
- }
- })
- describe('loading main frame state', () => {
- it('is true when the main frame is loading', (done) => {
- w.webContents.on('did-start-loading', () => {
- assert.equal(w.webContents.isLoadingMainFrame(), true)
- done()
- })
- w.webContents.loadURL(server.url)
- })
- it('is false when only a subframe is loading', (done) => {
- w.webContents.once('did-finish-load', () => {
- assert.equal(w.webContents.isLoadingMainFrame(), false)
- w.webContents.on('did-start-loading', () => {
- assert.equal(w.webContents.isLoadingMainFrame(), false)
- done()
- })
- w.webContents.executeJavaScript(`
- var iframe = document.createElement('iframe')
- iframe.src = '${server.url}/page2'
- document.body.appendChild(iframe)
- `)
- })
- w.webContents.loadURL(server.url)
- })
- it('is true when navigating to pages from the same origin', (done) => {
- w.webContents.once('did-finish-load', () => {
- assert.equal(w.webContents.isLoadingMainFrame(), false)
- w.webContents.on('did-start-loading', () => {
- assert.equal(w.webContents.isLoadingMainFrame(), true)
- done()
- })
- w.webContents.loadURL(`${server.url}/page2`)
- })
- w.webContents.loadURL(server.url)
- })
- })
- })
- describe('window states (excluding Linux)', () => {
- // FIXME(alexeykuzmin): Skip the tests instead of using the `return` here.
- // Why it cannot be done now:
- // - `.skip()` called in the 'before' hook doesn't affect
- // nested `describe`s.
- // - `.skip()` called in the 'beforeEach' hook prevents 'afterEach'
- // hook from being called.
- // Not implemented on Linux.
- if (process.platform === 'linux') {
- return
- }
- describe('movable state', () => {
- it('can be changed with movable option', () => {
- w.destroy()
- w = new BrowserWindow({show: false, movable: false})
- assert.equal(w.isMovable(), false)
- })
- it('can be changed with setMovable method', () => {
- assert.equal(w.isMovable(), true)
- w.setMovable(false)
- assert.equal(w.isMovable(), false)
- w.setMovable(true)
- assert.equal(w.isMovable(), true)
- })
- })
- describe('minimizable state', () => {
- it('can be changed with minimizable option', () => {
- w.destroy()
- w = new BrowserWindow({show: false, minimizable: false})
- assert.equal(w.isMinimizable(), false)
- })
- it('can be changed with setMinimizable method', () => {
- assert.equal(w.isMinimizable(), true)
- w.setMinimizable(false)
- assert.equal(w.isMinimizable(), false)
- w.setMinimizable(true)
- assert.equal(w.isMinimizable(), true)
- })
- })
- describe('maximizable state', () => {
- it('can be changed with maximizable option', () => {
- w.destroy()
- w = new BrowserWindow({show: false, maximizable: false})
- assert.equal(w.isMaximizable(), false)
- })
- it('can be changed with setMaximizable method', () => {
- assert.equal(w.isMaximizable(), true)
- w.setMaximizable(false)
- assert.equal(w.isMaximizable(), false)
- w.setMaximizable(true)
- assert.equal(w.isMaximizable(), true)
- })
- it('is not affected when changing other states', () => {
- w.setMaximizable(false)
- assert.equal(w.isMaximizable(), false)
- w.setMinimizable(false)
- assert.equal(w.isMaximizable(), false)
- w.setClosable(false)
- assert.equal(w.isMaximizable(), false)
- w.setMaximizable(true)
- assert.equal(w.isMaximizable(), true)
- w.setClosable(true)
- assert.equal(w.isMaximizable(), true)
- w.setFullScreenable(false)
- assert.equal(w.isMaximizable(), true)
- })
- })
- describe('maximizable state (Windows only)', () => {
- // Only implemented on windows.
- if (process.platform !== 'win32') return
- it('is set to false when resizable state is set to false', () => {
- w.setResizable(false)
- assert.equal(w.isMaximizable(), false)
- })
- })
- describe('fullscreenable state', () => {
- before(function () {
- // Only implemented on macOS.
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('can be changed with fullscreenable option', () => {
- w.destroy()
- w = new BrowserWindow({show: false, fullscreenable: false})
- assert.equal(w.isFullScreenable(), false)
- })
- it('can be changed with setFullScreenable method', () => {
- assert.equal(w.isFullScreenable(), true)
- w.setFullScreenable(false)
- assert.equal(w.isFullScreenable(), false)
- w.setFullScreenable(true)
- assert.equal(w.isFullScreenable(), true)
- })
- })
- describe('kiosk state', () => {
- before(function () {
- // Only implemented on macOS.
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('can be changed with setKiosk method', (done) => {
- w.destroy()
- w = new BrowserWindow()
- w.setKiosk(true)
- assert.equal(w.isKiosk(), true)
- w.once('enter-full-screen', () => {
- w.setKiosk(false)
- assert.equal(w.isKiosk(), false)
- })
- w.once('leave-full-screen', () => {
- done()
- })
- })
- })
- describe('fullscreen state with resizable set', () => {
- before(function () {
- // Only implemented on macOS.
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('resizable flag should be set to true and restored', (done) => {
- w.destroy()
- w = new BrowserWindow({ resizable: false })
- w.once('enter-full-screen', () => {
- assert.equal(w.isResizable(), true)
- w.setFullScreen(false)
- })
- w.once('leave-full-screen', () => {
- assert.equal(w.isResizable(), false)
- done()
- })
- w.setFullScreen(true)
- })
- })
- describe('fullscreen state', () => {
- before(function () {
- // Only implemented on macOS.
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('can be changed with setFullScreen method', (done) => {
- w.destroy()
- w = new BrowserWindow()
- w.once('enter-full-screen', () => {
- assert.equal(w.isFullScreen(), true)
- w.setFullScreen(false)
- })
- w.once('leave-full-screen', () => {
- assert.equal(w.isFullScreen(), false)
- done()
- })
- w.setFullScreen(true)
- })
- it('should not be changed by setKiosk method', (done) => {
- w.destroy()
- w = new BrowserWindow()
- w.once('enter-full-screen', () => {
- assert.equal(w.isFullScreen(), true)
- w.setKiosk(true)
- w.setKiosk(false)
- assert.equal(w.isFullScreen(), true)
- w.setFullScreen(false)
- })
- w.once('leave-full-screen', () => {
- assert.equal(w.isFullScreen(), false)
- done()
- })
- w.setFullScreen(true)
- })
- })
- describe('closable state', () => {
- it('can be changed with closable option', () => {
- w.destroy()
- w = new BrowserWindow({show: false, closable: false})
- assert.equal(w.isClosable(), false)
- })
- it('can be changed with setClosable method', () => {
- assert.equal(w.isClosable(), true)
- w.setClosable(false)
- assert.equal(w.isClosable(), false)
- w.setClosable(true)
- assert.equal(w.isClosable(), true)
- })
- })
- describe('hasShadow state', () => {
- // On Window there is no shadow by default and it can not be changed
- // dynamically.
- it('can be changed with hasShadow option', () => {
- w.destroy()
- let hasShadow = process.platform !== 'darwin'
- w = new BrowserWindow({show: false, hasShadow: hasShadow})
- assert.equal(w.hasShadow(), hasShadow)
- })
- it('can be changed with setHasShadow method', () => {
- if (process.platform !== 'darwin') return
- assert.equal(w.hasShadow(), true)
- w.setHasShadow(false)
- assert.equal(w.hasShadow(), false)
- w.setHasShadow(true)
- assert.equal(w.hasShadow(), true)
- })
- })
- })
- describe('BrowserWindow.restore()', () => {
- it('should restore the previous window size', () => {
- if (w != null) w.destroy()
- w = new BrowserWindow({
- minWidth: 800,
- width: 800
- })
- const initialSize = w.getSize()
- w.minimize()
- w.restore()
- assertBoundsEqual(w.getSize(), initialSize)
- })
- })
- describe('BrowserWindow.unmaximize()', () => {
- it('should restore the previous window position', () => {
- if (w != null) w.destroy()
- w = new BrowserWindow()
- const initialPosition = w.getPosition()
- w.maximize()
- w.unmaximize()
- assertBoundsEqual(w.getPosition(), initialPosition)
- })
- })
- describe('BrowserWindow.setFullScreen(false)', () => {
- before(function () {
- // only applicable to windows: https://github.com/electron/electron/issues/6036
- if (process.platform !== 'win32') {
- this.skip()
- }
- })
- it('should restore a normal visible window from a fullscreen startup state', (done) => {
- w.webContents.once('did-finish-load', () => {
- // start fullscreen and hidden
- w.setFullScreen(true)
- w.once('show', () => { w.setFullScreen(false) })
- w.once('leave-full-screen', () => {
- assert.equal(w.isVisible(), true)
- assert.equal(w.isFullScreen(), false)
- done()
- })
- w.show()
- })
- w.loadURL('about:blank')
- })
- it('should keep window hidden if already in hidden state', (done) => {
- w.webContents.once('did-finish-load', () => {
- w.once('leave-full-screen', () => {
- assert.equal(w.isVisible(), false)
- assert.equal(w.isFullScreen(), false)
- done()
- })
- w.setFullScreen(false)
- })
- w.loadURL('about:blank')
- })
- })
- describe('parent window', () => {
- let c = null
- beforeEach(() => {
- if (c != null) c.destroy()
- c = new BrowserWindow({show: false, parent: w})
- })
- afterEach(() => {
- if (c != null) c.destroy()
- c = null
- })
- describe('parent option', () => {
- it('sets parent window', () => {
- assert.equal(c.getParentWindow(), w)
- })
- it('adds window to child windows of parent', () => {
- assert.deepEqual(w.getChildWindows(), [c])
- })
- it('removes from child windows of parent when window is closed', (done) => {
- c.once('closed', () => {
- assert.deepEqual(w.getChildWindows(), [])
- done()
- })
- c.close()
- })
- it('should not affect the show option', () => {
- assert.equal(c.isVisible(), false)
- assert.equal(c.getParentWindow().isVisible(), false)
- })
- })
- describe('win.setParentWindow(parent)', () => {
- before(function () {
- if (process.platform === 'win32') {
- this.skip()
- }
- })
- beforeEach(() => {
- if (c != null) c.destroy()
- c = new BrowserWindow({show: false})
- })
- it('sets parent window', () => {
- assert.equal(w.getParentWindow(), null)
- assert.equal(c.getParentWindow(), null)
- c.setParentWindow(w)
- assert.equal(c.getParentWindow(), w)
- c.setParentWindow(null)
- assert.equal(c.getParentWindow(), null)
- })
- it('adds window to child windows of parent', () => {
- assert.deepEqual(w.getChildWindows(), [])
- c.setParentWindow(w)
- assert.deepEqual(w.getChildWindows(), [c])
- c.setParentWindow(null)
- assert.deepEqual(w.getChildWindows(), [])
- })
- it('removes from child windows of parent when window is closed', (done) => {
- c.once('closed', () => {
- assert.deepEqual(w.getChildWindows(), [])
- done()
- })
- c.setParentWindow(w)
- c.close()
- })
- })
- describe('modal option', () => {
- before(function () {
- // The isEnabled API is not reliable on macOS.
- if (process.platform === 'darwin') {
- this.skip()
- }
- })
- beforeEach(() => {
- if (c != null) c.destroy()
- c = new BrowserWindow({show: false, parent: w, modal: true})
- })
- it('disables parent window', () => {
- assert.equal(w.isEnabled(), true)
- c.show()
- assert.equal(w.isEnabled(), false)
- })
- it('enables parent window when closed', (done) => {
- c.once('closed', () => {
- assert.equal(w.isEnabled(), true)
- done()
- })
- c.show()
- c.close()
- })
- it('disables parent window recursively', () => {
- let c2 = new BrowserWindow({show: false, parent: w, modal: true})
- c.show()
- assert.equal(w.isEnabled(), false)
- c2.show()
- assert.equal(w.isEnabled(), false)
- c.destroy()
- assert.equal(w.isEnabled(), false)
- c2.destroy()
- assert.equal(w.isEnabled(), true)
- })
- })
- })
- describe('window.webContents.send(channel, args...)', () => {
- it('throws an error when the channel is missing', () => {
- assert.throws(() => {
- w.webContents.send()
- }, 'Missing required channel argument')
- assert.throws(() => {
- w.webContents.send(null)
- }, 'Missing required channel argument')
- })
- })
- describe('extensions and dev tools extensions', () => {
- let showPanelTimeoutId
- const showLastDevToolsPanel = () => {
- w.webContents.once('devtools-opened', () => {
- const show = () => {
- if (w == null || w.isDestroyed()) return
- const {devToolsWebContents} = w
- if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
- return
- }
- const showLastPanel = () => {
- const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id
- UI.inspectorView.showPanel(lastPanelId)
- }
- devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false, () => {
- showPanelTimeoutId = setTimeout(show, 100)
- })
- }
- showPanelTimeoutId = setTimeout(show, 100)
- })
- }
- afterEach(() => {
- clearTimeout(showPanelTimeoutId)
- })
- describe('BrowserWindow.addDevToolsExtension', () => {
- describe('for invalid extensions', () => {
- it('throws errors for missing manifest.json files', () => {
- const nonexistentExtensionPath = path.join(__dirname, 'does-not-exist')
- expect(() => {
- BrowserWindow.addDevToolsExtension(nonexistentExtensionPath)
- }).to.throw(/ENOENT: no such file or directory/)
- })
- it('throws errors for invalid manifest.json files', () => {
- const badManifestExtensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest')
- expect(() => {
- BrowserWindow.addDevToolsExtension(badManifestExtensionPath)
- }).to.throw(/Unexpected token }/)
- })
- })
- describe('for a valid extension', () => {
- const extensionName = 'foo'
- const removeExtension = () => {
- BrowserWindow.removeDevToolsExtension('foo')
- expect(BrowserWindow.getDevToolsExtensions().hasOwnProperty(extensionName)).to.equal(false)
- }
- const addExtension = () => {
- const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
- BrowserWindow.addDevToolsExtension(extensionPath)
- expect(BrowserWindow.getDevToolsExtensions().hasOwnProperty(extensionName)).to.equal(true)
- showLastDevToolsPanel()
- w.loadURL('about:blank')
- }
- // After* hooks won't be called if a test fail.
- // So let's make a clean-up in the before hook.
- beforeEach(removeExtension)
- describe('when the devtools is docked', () => {
- beforeEach(function (done) {
- addExtension()
- w.webContents.openDevTools({mode: 'bottom'})
- ipcMain.once('answer', (event, message) => {
- this.message = message
- done()
- })
- })
- describe('created extension info', function () {
- it('has proper "runtimeId"', function () {
- expect(this.message).to.have.own.property('runtimeId')
- expect(this.message.runtimeId).to.equal(extensionName)
- })
- it('has "tabId" matching webContents id', function () {
- expect(this.message).to.have.own.property('tabId')
- expect(this.message.tabId).to.equal(w.webContents.id)
- })
- it('has "i18nString" with proper contents', function () {
- expect(this.message).to.have.own.property('i18nString')
- expect(this.message.i18nString).to.equal('foo - bar (baz)')
- })
- it('has "storageItems" with proper contents', function () {
- expect(this.message).to.have.own.property('storageItems')
- expect(this.message.storageItems).to.deep.equal({
- local: {
- set: {hello: 'world', world: 'hello'},
- remove: {world: 'hello'},
- clear: {}
- },
- sync: {
- set: {foo: 'bar', bar: 'foo'},
- remove: {foo: 'bar'},
- clear: {}
- }
- })
- })
- })
- })
- describe('when the devtools is undocked', () => {
- beforeEach(function (done) {
- addExtension()
- w.webContents.openDevTools({mode: 'undocked'})
- ipcMain.once('answer', (event, message, extensionId) => {
- this.message = message
- done()
- })
- })
- describe('created extension info', function () {
- it('has proper "runtimeId"', function () {
- expect(this.message).to.have.own.property('runtimeId')
- expect(this.message.runtimeId).to.equal(extensionName)
- })
- it('has "tabId" matching webContents id', function () {
- expect(this.message).to.have.own.property('tabId')
- expect(this.message.tabId).to.equal(w.webContents.id)
- })
- })
- })
- })
- })
- it('works when used with partitions', (done) => {
- if (w != null) {
- w.destroy()
- }
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- partition: 'temp'
- }
- })
- var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
- BrowserWindow.removeDevToolsExtension('foo')
- BrowserWindow.addDevToolsExtension(extensionPath)
- showLastDevToolsPanel()
- w.loadURL('about:blank')
- w.webContents.openDevTools({mode: 'bottom'})
- ipcMain.once('answer', function (event, message) {
- assert.equal(message.runtimeId, 'foo')
- done()
- })
- })
- it('serializes the registered extensions on quit', () => {
- var extensionName = 'foo'
- var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', extensionName)
- var serializedPath = path.join(app.getPath('userData'), 'DevTools Extensions')
- BrowserWindow.addDevToolsExtension(extensionPath)
- app.emit('will-quit')
- assert.deepEqual(JSON.parse(fs.readFileSync(serializedPath)), [extensionPath])
- BrowserWindow.removeDevToolsExtension(extensionName)
- app.emit('will-quit')
- assert.equal(fs.existsSync(serializedPath), false)
- })
- describe('BrowserWindow.addExtension', () => {
- beforeEach(() => {
- BrowserWindow.removeExtension('foo')
- assert.equal(BrowserWindow.getExtensions().hasOwnProperty('foo'), false)
- var extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo')
- BrowserWindow.addExtension(extensionPath)
- assert.equal(BrowserWindow.getExtensions().hasOwnProperty('foo'), true)
- showLastDevToolsPanel()
- w.loadURL('about:blank')
- })
- it('throws errors for missing manifest.json files', () => {
- assert.throws(() => {
- BrowserWindow.addExtension(path.join(__dirname, 'does-not-exist'))
- }, /ENOENT: no such file or directory/)
- })
- it('throws errors for invalid manifest.json files', () => {
- assert.throws(() => {
- BrowserWindow.addExtension(path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest'))
- }, /Unexpected token }/)
- })
- })
- })
- describe('window.webContents.executeJavaScript', () => {
- const expected = 'hello, world!'
- const expectedErrorMsg = 'woops!'
- const code = `(() => "${expected}")()`
- const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`
- const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`
- const errorTypes = new Set([
- Error,
- ReferenceError,
- EvalError,
- RangeError,
- SyntaxError,
- TypeError,
- URIError
- ])
- it('doesnt throw when no calback is provided', () => {
- const result = ipcRenderer.sendSync('executeJavaScript', code, false)
- assert.equal(result, 'success')
- })
- it('returns result when calback is provided', (done) => {
- ipcRenderer.send('executeJavaScript', code, true)
- ipcRenderer.once('executeJavaScript-response', function (event, result) {
- assert.equal(result, expected)
- done()
- })
- })
- it('returns result if the code returns an asyncronous promise', (done) => {
- ipcRenderer.send('executeJavaScript', asyncCode, true)
- ipcRenderer.once('executeJavaScript-response', (event, result) => {
- assert.equal(result, expected)
- done()
- })
- })
- it('resolves the returned promise with the result when a callback is specified', (done) => {
- ipcRenderer.send('executeJavaScript', code, true)
- ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
- assert.equal(result, expected)
- done()
- })
- })
- it('resolves the returned promise with the result when no callback is specified', (done) => {
- ipcRenderer.send('executeJavaScript', code, false)
- ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
- assert.equal(result, expected)
- done()
- })
- })
- it('resolves the returned promise with the result if the code returns an asyncronous promise', (done) => {
- ipcRenderer.send('executeJavaScript', asyncCode, true)
- ipcRenderer.once('executeJavaScript-promise-response', (event, result) => {
- assert.equal(result, expected)
- done()
- })
- })
- it('rejects the returned promise if an async error is thrown', (done) => {
- ipcRenderer.send('executeJavaScript', badAsyncCode, true)
- ipcRenderer.once('executeJavaScript-promise-error', (event, error) => {
- assert.equal(error, expectedErrorMsg)
- done()
- })
- })
- it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
- for (const error in errorTypes) {
- await new Promise((resolve) => {
- ipcRenderer.send('executeJavaScript', `Promise.reject(new ${error.name}("Wamp-wamp")`, true)
- ipcRenderer.once('executeJavaScript-promise-error-name', (event, name) => {
- assert.equal(name, error.name)
- resolve()
- })
- })
- }
- })
- it('works after page load and during subframe load', (done) => {
- w.webContents.once('did-finish-load', () => {
- // initiate a sub-frame load, then try and execute script during it
- w.webContents.executeJavaScript(`
- var iframe = document.createElement('iframe')
- iframe.src = '${server.url}/slow'
- document.body.appendChild(iframe)
- `, () => {
- w.webContents.executeJavaScript('console.log(\'hello\')', () => {
- done()
- })
- })
- })
- w.loadURL(server.url)
- })
- it('executes after page load', (done) => {
- w.webContents.executeJavaScript(code, (result) => {
- assert.equal(result, expected)
- done()
- })
- w.loadURL(server.url)
- })
- it('works with result objects that have DOM class prototypes', (done) => {
- w.webContents.executeJavaScript('document.location', (result) => {
- assert.equal(result.origin, server.url)
- assert.equal(result.protocol, 'http:')
- done()
- })
- w.loadURL(server.url)
- })
- })
- describe('previewFile', () => {
- before(function () {
- if (process.platform !== 'darwin') {
- this.skip()
- }
- })
- it('opens the path in Quick Look on macOS', () => {
- assert.doesNotThrow(() => {
- w.previewFile(__filename)
- w.closeFilePreview()
- })
- })
- })
- describe('contextIsolation option with and without sandbox option', () => {
- const expectedContextData = {
- preloadContext: {
- preloadProperty: 'number',
- pageProperty: 'undefined',
- typeofRequire: 'function',
- typeofProcess: 'object',
- typeofArrayPush: 'function',
- typeofFunctionApply: 'function'
- },
- pageContext: {
- preloadProperty: 'undefined',
- pageProperty: 'string',
- typeofRequire: 'undefined',
- typeofProcess: 'undefined',
- typeofArrayPush: 'number',
- typeofFunctionApply: 'boolean',
- typeofPreloadExecuteJavaScriptProperty: 'number',
- typeofOpenedWindow: 'object'
- }
- }
- beforeEach(() => {
- if (w != null) w.destroy()
- w = new BrowserWindow({
- show: false,
- webPreferences: {
- contextIsolation: true,
- preload: path.join(fixtures, 'api', 'isolated-preload.js')
- }
- })
- if (ws != null) ws.destroy()
- ws = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- contextIsolation: true,
- preload: path.join(fixtures, 'api', 'isolated-preload.js')
- }
- })
- })
- afterEach(() => {
- if (ws != null) ws.destroy()
- })
- it('separates the page context from the Electron/preload context', (done) => {
- ipcMain.once('isolated-world', (event, data) => {
- assert.deepEqual(data, expectedContextData)
- done()
- })
- w.loadURL(`file://${fixtures}/api/isolated.html`)
- })
- it('recreates the contexts on reload', (done) => {
- w.webContents.once('did-finish-load', () => {
- ipcMain.once('isolated-world', (event, data) => {
- assert.deepEqual(data, expectedContextData)
- done()
- })
- w.webContents.reload()
- })
- w.loadURL(`file://${fixtures}/api/isolated.html`)
- })
- it('enables context isolation on child windows', (done) => {
- app.once('browser-window-created', (event, window) => {
- assert.equal(window.webContents.getLastWebPreferences().contextIsolation, true)
- done()
- })
- w.loadURL(`file://${fixtures}/pages/window-open.html`)
- })
- it('separates the page context from the Electron/preload context with sandbox on', (done) => {
- ipcMain.once('isolated-sandbox-world', (event, data) => {
- assert.deepEqual(data, expectedContextData)
- done()
- })
- w.loadURL(`file://${fixtures}/api/isolated.html`)
- })
- it('recreates the contexts on reload with sandbox on', (done) => {
- w.webContents.once('did-finish-load', () => {
- ipcMain.once('isolated-sandbox-world', (event, data) => {
- assert.deepEqual(data, expectedContextData)
- done()
- })
- w.webContents.reload()
- })
- w.loadURL(`file://${fixtures}/api/isolated.html`)
- })
- })
- describe('offscreen rendering', () => {
- beforeEach(function () {
- if (!features.isOffscreenRenderingEnabled()) {
- // XXX(alexeykuzmin): "afterEach" hook is not called
- // for skipped tests, we have to close the window manually.
- return closeTheWindow().then(() => { this.skip() })
- }
- if (w != null) w.destroy()
- w = new BrowserWindow({
- width: 100,
- height: 100,
- show: false,
- webPreferences: {
- backgroundThrottling: false,
- offscreen: true
- }
- })
- })
- it('creates offscreen window with correct size', (done) => {
- w.webContents.once('paint', function (event, rect, data) {
- assert.notEqual(data.length, 0)
- let size = data.getSize()
- assertWithinDelta(size.width, 100, 2, 'width')
- assertWithinDelta(size.height, 100, 2, 'height')
- done()
- })
- w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
- })
- describe('window.webContents.isOffscreen()', () => {
- it('is true for offscreen type', () => {
- w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
- assert.equal(w.webContents.isOffscreen(), true)
- })
- it('is false for regular window', () => {
- let c = new BrowserWindow({show: false})
- assert.equal(c.webContents.isOffscreen(), false)
- c.destroy()
- })
- })
- describe('window.webContents.isPainting()', () => {
- it('returns whether is currently painting', (done) => {
- w.webContents.once('paint', function (event, rect, data) {
- assert.equal(w.webContents.isPainting(), true)
- done()
- })
- w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
- })
- })
- describe('window.webContents.stopPainting()', () => {
- it('stops painting', (done) => {
- w.webContents.on('dom-ready', () => {
- w.webContents.stopPainting()
- assert.equal(w.webContents.isPainting(), false)
- done()
- })
- w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
- })
- })
- describe('window.webContents.startPainting()', () => {
- it('starts painting', (done) => {
- w.webContents.on('dom-ready', () => {
- w.webContents.stopPainting()
- w.webContents.startPainting()
- w.webContents.once('paint', function (event, rect, data) {
- assert.equal(w.webContents.isPainting(), true)
- done()
- })
- })
- w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
- })
- })
- describe('window.webContents.getFrameRate()', () => {
- it('has default frame rate', (done) => {
- w.webContents.once('paint', function (event, rect, data) {
- assert.equal(w.webContents.getFrameRate(), 60)
- done()
- })
- w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
- })
- })
- describe('window.webContents.setFrameRate(frameRate)', () => {
- it('sets custom frame rate', (done) => {
- w.webContents.on('dom-ready', () => {
- w.webContents.setFrameRate(30)
- w.webContents.once('paint', function (event, rect, data) {
- assert.equal(w.webContents.getFrameRate(), 30)
- done()
- })
- })
- w.loadURL('file://' + fixtures + '/api/offscreen-rendering.html')
- })
- })
- })
- })
- const assertBoundsEqual = (actual, expect) => {
- if (!isScaleFactorRounding()) {
- assert.deepEqual(expect, actual)
- } else if (Array.isArray(actual)) {
- assertWithinDelta(actual[0], expect[0], 1, 'x')
- assertWithinDelta(actual[1], expect[1], 1, 'y')
- } else {
- assertWithinDelta(actual.x, expect.x, 1, 'x')
- assertWithinDelta(actual.y, expect.y, 1, 'y')
- assertWithinDelta(actual.width, expect.width, 1, 'width')
- assertWithinDelta(actual.height, expect.height, 1, 'height')
- }
- }
- const assertWithinDelta = (actual, expect, delta, label) => {
- const result = Math.abs(actual - expect)
- assert.ok(result <= delta, `${label} value of ${actual} was not within ${delta} of ${expect}`)
- }
- // Is the display's scale factor possibly causing rounding of pixel coordinate
- // values?
- const isScaleFactorRounding = () => {
- const {scaleFactor} = screen.getPrimaryDisplay()
- // Return true if scale factor is non-integer value
- if (Math.round(scaleFactor) !== scaleFactor) return true
- // Return true if scale factor is odd number above 2
- return scaleFactor > 2 && scaleFactor % 2 === 1
- }
- function serveFileFromProtocol (protocolName, filePath) {
- return new Promise((resolve, reject) => {
- protocol.registerBufferProtocol(protocolName, (request, callback) => {
- // Disabled due to false positive in StandardJS
- // eslint-disable-next-line standard/no-callback-literal
- callback({
- mimeType: 'text/html',
- data: fs.readFileSync(filePath)
- })
- }, (error) => {
- if (error != null) {
- reject(error)
- } else {
- resolve()
- }
- })
- })
- }
|