api-browser-window-spec.ts 207 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912
  1. import { expect } from 'chai';
  2. import * as childProcess from 'child_process';
  3. import * as path from 'path';
  4. import * as fs from 'fs';
  5. import * as qs from 'querystring';
  6. import * as http from 'http';
  7. import { AddressInfo } from 'net';
  8. import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents } from 'electron/main';
  9. import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers';
  10. import { ifit, ifdescribe, defer, delay } from './spec-helpers';
  11. import { closeWindow, closeAllWindows } from './window-helpers';
  12. import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './screen-helpers';
  13. const features = process._linkedBinding('electron_common_features');
  14. const fixtures = path.resolve(__dirname, 'fixtures');
  15. const mainFixtures = path.resolve(__dirname, 'fixtures');
  16. // Is the display's scale factor possibly causing rounding of pixel coordinate
  17. // values?
  18. const isScaleFactorRounding = () => {
  19. const { scaleFactor } = screen.getPrimaryDisplay();
  20. // Return true if scale factor is non-integer value
  21. if (Math.round(scaleFactor) !== scaleFactor) return true;
  22. // Return true if scale factor is odd number above 2
  23. return scaleFactor > 2 && scaleFactor % 2 === 1;
  24. };
  25. const expectBoundsEqual = (actual: any, expected: any) => {
  26. if (!isScaleFactorRounding()) {
  27. expect(expected).to.deep.equal(actual);
  28. } else if (Array.isArray(actual)) {
  29. expect(actual[0]).to.be.closeTo(expected[0], 1);
  30. expect(actual[1]).to.be.closeTo(expected[1], 1);
  31. } else {
  32. expect(actual.x).to.be.closeTo(expected.x, 1);
  33. expect(actual.y).to.be.closeTo(expected.y, 1);
  34. expect(actual.width).to.be.closeTo(expected.width, 1);
  35. expect(actual.height).to.be.closeTo(expected.height, 1);
  36. }
  37. };
  38. const isBeforeUnload = (event: Event, level: number, message: string) => {
  39. return (message === 'beforeunload');
  40. };
  41. describe('BrowserWindow module', () => {
  42. describe('BrowserWindow constructor', () => {
  43. it('allows passing void 0 as the webContents', async () => {
  44. expect(() => {
  45. const w = new BrowserWindow({
  46. show: false,
  47. // apparently void 0 had different behaviour from undefined in the
  48. // issue that this test is supposed to catch.
  49. webContents: void 0 // eslint-disable-line no-void
  50. } as any);
  51. w.destroy();
  52. }).not.to.throw();
  53. });
  54. ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
  55. const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
  56. const appProcess = childProcess.spawn(process.execPath, [appPath]);
  57. await new Promise((resolve) => { appProcess.once('exit', resolve); });
  58. });
  59. it('does not crash or throw when passed an invalid icon', async () => {
  60. expect(() => {
  61. const w = new BrowserWindow({
  62. icon: undefined
  63. } as any);
  64. w.destroy();
  65. }).not.to.throw();
  66. });
  67. });
  68. describe('garbage collection', () => {
  69. const v8Util = process._linkedBinding('electron_common_v8_util');
  70. afterEach(closeAllWindows);
  71. it('window does not get garbage collected when opened', async () => {
  72. const w = new BrowserWindow({ show: false });
  73. // Keep a weak reference to the window.
  74. // eslint-disable-next-line no-undef
  75. const wr = new WeakRef(w);
  76. await delay();
  77. // Do garbage collection, since |w| is not referenced in this closure
  78. // it would be gone after next call if there is no other reference.
  79. v8Util.requestGarbageCollectionForTesting();
  80. await delay();
  81. expect(wr.deref()).to.not.be.undefined();
  82. });
  83. });
  84. describe('BrowserWindow.close()', () => {
  85. let w = null as unknown as BrowserWindow;
  86. beforeEach(() => {
  87. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  88. });
  89. afterEach(async () => {
  90. await closeWindow(w);
  91. w = null as unknown as BrowserWindow;
  92. });
  93. it('should work if called when a messageBox is showing', async () => {
  94. const closed = emittedOnce(w, 'closed');
  95. dialog.showMessageBox(w, { message: 'Hello Error' });
  96. w.close();
  97. await closed;
  98. });
  99. it('closes window without rounded corners', async () => {
  100. await closeWindow(w);
  101. w = new BrowserWindow({ show: false, frame: false, roundedCorners: false });
  102. const closed = emittedOnce(w, 'closed');
  103. w.close();
  104. await closed;
  105. });
  106. it('should not crash if called after webContents is destroyed', () => {
  107. w.webContents.destroy();
  108. w.webContents.on('destroyed', () => w.close());
  109. });
  110. it('should allow access to id after destruction', async () => {
  111. const closed = emittedOnce(w, 'closed');
  112. w.destroy();
  113. await closed;
  114. expect(w.id).to.be.a('number');
  115. });
  116. it('should emit unload handler', async () => {
  117. await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
  118. const closed = emittedOnce(w, 'closed');
  119. w.close();
  120. await closed;
  121. const test = path.join(fixtures, 'api', 'unload');
  122. const content = fs.readFileSync(test);
  123. fs.unlinkSync(test);
  124. expect(String(content)).to.equal('unload');
  125. });
  126. it('should emit beforeunload handler', async () => {
  127. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  128. w.close();
  129. await emittedOnce(w.webContents, 'before-unload-fired');
  130. });
  131. it('should not crash when keyboard event is sent before closing', async () => {
  132. await w.loadURL('data:text/html,pls no crash');
  133. const closed = emittedOnce(w, 'closed');
  134. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
  135. w.close();
  136. await closed;
  137. });
  138. describe('when invoked synchronously inside navigation observer', () => {
  139. let server: http.Server = null as unknown as http.Server;
  140. let url: string = null as unknown as string;
  141. before((done) => {
  142. server = http.createServer((request, response) => {
  143. switch (request.url) {
  144. case '/net-error':
  145. response.destroy();
  146. break;
  147. case '/301':
  148. response.statusCode = 301;
  149. response.setHeader('Location', '/200');
  150. response.end();
  151. break;
  152. case '/200':
  153. response.statusCode = 200;
  154. response.end('hello');
  155. break;
  156. case '/title':
  157. response.statusCode = 200;
  158. response.end('<title>Hello</title>');
  159. break;
  160. default:
  161. throw new Error(`unsupported endpoint: ${request.url}`);
  162. }
  163. }).listen(0, '127.0.0.1', () => {
  164. url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  165. done();
  166. });
  167. });
  168. after(() => {
  169. server.close();
  170. });
  171. const events = [
  172. { name: 'did-start-loading', path: '/200' },
  173. { name: 'dom-ready', path: '/200' },
  174. { name: 'page-title-updated', path: '/title' },
  175. { name: 'did-stop-loading', path: '/200' },
  176. { name: 'did-finish-load', path: '/200' },
  177. { name: 'did-frame-finish-load', path: '/200' },
  178. { name: 'did-fail-load', path: '/net-error' }
  179. ];
  180. for (const { name, path } of events) {
  181. it(`should not crash when closed during ${name}`, async () => {
  182. const w = new BrowserWindow({ show: false });
  183. w.webContents.once((name as any), () => {
  184. w.close();
  185. });
  186. const destroyed = emittedOnce(w.webContents, 'destroyed');
  187. w.webContents.loadURL(url + path);
  188. await destroyed;
  189. });
  190. }
  191. });
  192. });
  193. describe('window.close()', () => {
  194. let w = null as unknown as BrowserWindow;
  195. beforeEach(() => {
  196. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
  197. });
  198. afterEach(async () => {
  199. await closeWindow(w);
  200. w = null as unknown as BrowserWindow;
  201. });
  202. it('should emit unload event', async () => {
  203. w.loadFile(path.join(fixtures, 'api', 'close.html'));
  204. await emittedOnce(w, 'closed');
  205. const test = path.join(fixtures, 'api', 'close');
  206. const content = fs.readFileSync(test).toString();
  207. fs.unlinkSync(test);
  208. expect(content).to.equal('close');
  209. });
  210. it('should emit beforeunload event', async function () {
  211. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  212. w.webContents.executeJavaScript('window.close()', true);
  213. await emittedOnce(w.webContents, 'before-unload-fired');
  214. });
  215. });
  216. describe('BrowserWindow.destroy()', () => {
  217. let w = null as unknown as BrowserWindow;
  218. beforeEach(() => {
  219. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  220. });
  221. afterEach(async () => {
  222. await closeWindow(w);
  223. w = null as unknown as BrowserWindow;
  224. });
  225. it('prevents users to access methods of webContents', async () => {
  226. const contents = w.webContents;
  227. w.destroy();
  228. await new Promise(setImmediate);
  229. expect(() => {
  230. contents.getProcessId();
  231. }).to.throw('Object has been destroyed');
  232. });
  233. it('should not crash when destroying windows with pending events', () => {
  234. const focusListener = () => { };
  235. app.on('browser-window-focus', focusListener);
  236. const windowCount = 3;
  237. const windowOptions = {
  238. show: false,
  239. width: 400,
  240. height: 400,
  241. webPreferences: {
  242. backgroundThrottling: false
  243. }
  244. };
  245. const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
  246. windows.forEach(win => win.show());
  247. windows.forEach(win => win.focus());
  248. windows.forEach(win => win.destroy());
  249. app.removeListener('browser-window-focus', focusListener);
  250. });
  251. });
  252. describe('BrowserWindow.loadURL(url)', () => {
  253. let w = null as unknown as BrowserWindow;
  254. const scheme = 'other';
  255. const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
  256. before(() => {
  257. protocol.registerFileProtocol(scheme, (request, callback) => {
  258. callback(srcPath);
  259. });
  260. });
  261. after(() => {
  262. protocol.unregisterProtocol(scheme);
  263. });
  264. beforeEach(() => {
  265. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  266. });
  267. afterEach(async () => {
  268. await closeWindow(w);
  269. w = null as unknown as BrowserWindow;
  270. });
  271. let server = null as unknown as http.Server;
  272. let url = null as unknown as string;
  273. let postData = null as any;
  274. before((done) => {
  275. const filePath = path.join(fixtures, 'pages', 'a.html');
  276. const fileStats = fs.statSync(filePath);
  277. postData = [
  278. {
  279. type: 'rawData',
  280. bytes: Buffer.from('username=test&file=')
  281. },
  282. {
  283. type: 'file',
  284. filePath: filePath,
  285. offset: 0,
  286. length: fileStats.size,
  287. modificationTime: fileStats.mtime.getTime() / 1000
  288. }
  289. ];
  290. server = http.createServer((req, res) => {
  291. function respond () {
  292. if (req.method === 'POST') {
  293. let body = '';
  294. req.on('data', (data) => {
  295. if (data) body += data;
  296. });
  297. req.on('end', () => {
  298. const parsedData = qs.parse(body);
  299. fs.readFile(filePath, (err, data) => {
  300. if (err) return;
  301. if (parsedData.username === 'test' &&
  302. parsedData.file === data.toString()) {
  303. res.end();
  304. }
  305. });
  306. });
  307. } else if (req.url === '/302') {
  308. res.setHeader('Location', '/200');
  309. res.statusCode = 302;
  310. res.end();
  311. } else {
  312. res.end();
  313. }
  314. }
  315. setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0);
  316. });
  317. server.listen(0, '127.0.0.1', () => {
  318. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  319. done();
  320. });
  321. });
  322. after(() => {
  323. server.close();
  324. });
  325. it('should emit did-start-loading event', async () => {
  326. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  327. w.loadURL('about:blank');
  328. await didStartLoading;
  329. });
  330. it('should emit ready-to-show event', async () => {
  331. const readyToShow = emittedOnce(w, 'ready-to-show');
  332. w.loadURL('about:blank');
  333. await readyToShow;
  334. });
  335. // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
  336. // changed and adjust the test.
  337. it.skip('should emit did-fail-load event for files that do not exist', async () => {
  338. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  339. w.loadURL('file://a.txt');
  340. const [, code, desc,, isMainFrame] = await didFailLoad;
  341. expect(code).to.equal(-6);
  342. expect(desc).to.equal('ERR_FILE_NOT_FOUND');
  343. expect(isMainFrame).to.equal(true);
  344. });
  345. it('should emit did-fail-load event for invalid URL', async () => {
  346. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  347. w.loadURL('http://example:port');
  348. const [, code, desc,, isMainFrame] = await didFailLoad;
  349. expect(desc).to.equal('ERR_INVALID_URL');
  350. expect(code).to.equal(-300);
  351. expect(isMainFrame).to.equal(true);
  352. });
  353. it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
  354. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  355. w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
  356. const [,,,, isMainFrame] = await didFailLoad;
  357. expect(isMainFrame).to.equal(false);
  358. });
  359. it('does not crash in did-fail-provisional-load handler', (done) => {
  360. w.webContents.once('did-fail-provisional-load', () => {
  361. w.loadURL('http://127.0.0.1:11111');
  362. done();
  363. });
  364. w.loadURL('http://127.0.0.1:11111');
  365. });
  366. it('should emit did-fail-load event for URL exceeding character limit', async () => {
  367. const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
  368. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  369. w.loadURL(`data:image/png;base64,${data}`);
  370. const [, code, desc,, isMainFrame] = await didFailLoad;
  371. expect(desc).to.equal('ERR_INVALID_URL');
  372. expect(code).to.equal(-300);
  373. expect(isMainFrame).to.equal(true);
  374. });
  375. it('should return a promise', () => {
  376. const p = w.loadURL('about:blank');
  377. expect(p).to.have.property('then');
  378. });
  379. it('should return a promise that resolves', async () => {
  380. await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
  381. });
  382. it('should return a promise that rejects on a load failure', async () => {
  383. const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
  384. const p = w.loadURL(`data:image/png;base64,${data}`);
  385. await expect(p).to.eventually.be.rejected;
  386. });
  387. it('should return a promise that resolves even if pushState occurs during navigation', async () => {
  388. const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
  389. await expect(p).to.eventually.be.fulfilled;
  390. });
  391. describe('POST navigations', () => {
  392. afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
  393. it('supports specifying POST data', async () => {
  394. await w.loadURL(url, { postData });
  395. });
  396. it('sets the content type header on URL encoded forms', async () => {
  397. await w.loadURL(url);
  398. const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
  399. w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
  400. resolve(details);
  401. });
  402. });
  403. w.webContents.executeJavaScript(`
  404. form = document.createElement('form')
  405. document.body.appendChild(form)
  406. form.method = 'POST'
  407. form.submit()
  408. `);
  409. const details = await requestDetails;
  410. expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
  411. });
  412. it('sets the content type header on multi part forms', async () => {
  413. await w.loadURL(url);
  414. const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
  415. w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
  416. resolve(details);
  417. });
  418. });
  419. w.webContents.executeJavaScript(`
  420. form = document.createElement('form')
  421. document.body.appendChild(form)
  422. form.method = 'POST'
  423. form.enctype = 'multipart/form-data'
  424. file = document.createElement('input')
  425. file.type = 'file'
  426. file.name = 'file'
  427. form.appendChild(file)
  428. form.submit()
  429. `);
  430. const details = await requestDetails;
  431. expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
  432. });
  433. });
  434. it('should support base url for data urls', async () => {
  435. await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
  436. expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
  437. });
  438. });
  439. for (const sandbox of [false, true]) {
  440. describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
  441. let w = null as unknown as BrowserWindow;
  442. beforeEach(() => {
  443. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
  444. });
  445. afterEach(async () => {
  446. await closeWindow(w);
  447. w = null as unknown as BrowserWindow;
  448. });
  449. describe('will-navigate event', () => {
  450. let server = null as unknown as http.Server;
  451. let url = null as unknown as string;
  452. before((done) => {
  453. server = http.createServer((req, res) => {
  454. if (req.url === '/navigate-top') {
  455. res.end('<a target=_top href="/">navigate _top</a>');
  456. } else {
  457. res.end('');
  458. }
  459. });
  460. server.listen(0, '127.0.0.1', () => {
  461. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
  462. done();
  463. });
  464. });
  465. after(() => {
  466. server.close();
  467. });
  468. it('allows the window to be closed from the event listener', (done) => {
  469. w.webContents.once('will-navigate', () => {
  470. w.close();
  471. done();
  472. });
  473. w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
  474. });
  475. it('can be prevented', (done) => {
  476. let willNavigate = false;
  477. w.webContents.once('will-navigate', (e) => {
  478. willNavigate = true;
  479. e.preventDefault();
  480. });
  481. w.webContents.on('did-stop-loading', () => {
  482. if (willNavigate) {
  483. // i.e. it shouldn't have had '?navigated' appended to it.
  484. try {
  485. expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
  486. done();
  487. } catch (e) {
  488. done(e);
  489. }
  490. }
  491. });
  492. w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
  493. });
  494. it('is triggered when navigating from file: to http:', async () => {
  495. await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  496. w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
  497. const navigatedTo = await new Promise(resolve => {
  498. w.webContents.once('will-navigate', (e, url) => {
  499. e.preventDefault();
  500. resolve(url);
  501. });
  502. });
  503. expect(navigatedTo).to.equal(url);
  504. expect(w.webContents.getURL()).to.match(/^file:/);
  505. });
  506. it('is triggered when navigating from about:blank to http:', async () => {
  507. await w.loadURL('about:blank');
  508. w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
  509. const navigatedTo = await new Promise(resolve => {
  510. w.webContents.once('will-navigate', (e, url) => {
  511. e.preventDefault();
  512. resolve(url);
  513. });
  514. });
  515. expect(navigatedTo).to.equal(url);
  516. expect(w.webContents.getURL()).to.equal('about:blank');
  517. });
  518. it('is triggered when a cross-origin iframe navigates _top', async () => {
  519. await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
  520. await delay(1000);
  521. w.webContents.debugger.attach('1.1');
  522. const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
  523. const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
  524. const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
  525. targetId: iframeTarget.targetId,
  526. flatten: true
  527. });
  528. let willNavigateEmitted = false;
  529. w.webContents.on('will-navigate', () => {
  530. willNavigateEmitted = true;
  531. });
  532. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  533. type: 'mousePressed',
  534. x: 10,
  535. y: 10,
  536. clickCount: 1,
  537. button: 'left'
  538. }, sessionId);
  539. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  540. type: 'mouseReleased',
  541. x: 10,
  542. y: 10,
  543. clickCount: 1,
  544. button: 'left'
  545. }, sessionId);
  546. await emittedOnce(w.webContents, 'did-navigate');
  547. expect(willNavigateEmitted).to.be.true();
  548. });
  549. });
  550. describe('will-redirect event', () => {
  551. let server = null as unknown as http.Server;
  552. let url = null as unknown as string;
  553. before((done) => {
  554. server = http.createServer((req, res) => {
  555. if (req.url === '/302') {
  556. res.setHeader('Location', '/200');
  557. res.statusCode = 302;
  558. res.end();
  559. } else if (req.url === '/navigate-302') {
  560. res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
  561. } else {
  562. res.end();
  563. }
  564. });
  565. server.listen(0, '127.0.0.1', () => {
  566. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  567. done();
  568. });
  569. });
  570. after(() => {
  571. server.close();
  572. });
  573. it('is emitted on redirects', async () => {
  574. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  575. w.loadURL(`${url}/302`);
  576. await willRedirect;
  577. });
  578. it('is emitted after will-navigate on redirects', async () => {
  579. let navigateCalled = false;
  580. w.webContents.on('will-navigate', () => {
  581. navigateCalled = true;
  582. });
  583. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  584. w.loadURL(`${url}/navigate-302`);
  585. await willRedirect;
  586. expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
  587. });
  588. it('is emitted before did-stop-loading on redirects', async () => {
  589. let stopCalled = false;
  590. w.webContents.on('did-stop-loading', () => {
  591. stopCalled = true;
  592. });
  593. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  594. w.loadURL(`${url}/302`);
  595. await willRedirect;
  596. expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
  597. });
  598. it('allows the window to be closed from the event listener', (done) => {
  599. w.webContents.once('will-redirect', () => {
  600. w.close();
  601. done();
  602. });
  603. w.loadURL(`${url}/302`);
  604. });
  605. it('can be prevented', (done) => {
  606. w.webContents.once('will-redirect', (event) => {
  607. event.preventDefault();
  608. });
  609. w.webContents.on('will-navigate', (e, u) => {
  610. expect(u).to.equal(`${url}/302`);
  611. });
  612. w.webContents.on('did-stop-loading', () => {
  613. try {
  614. expect(w.webContents.getURL()).to.equal(
  615. `${url}/navigate-302`,
  616. 'url should not have changed after navigation event'
  617. );
  618. done();
  619. } catch (e) {
  620. done(e);
  621. }
  622. });
  623. w.webContents.on('will-redirect', (e, u) => {
  624. try {
  625. expect(u).to.equal(`${url}/200`);
  626. } catch (e) {
  627. done(e);
  628. }
  629. });
  630. w.loadURL(`${url}/navigate-302`);
  631. });
  632. });
  633. });
  634. }
  635. describe('focus and visibility', () => {
  636. let w = null as unknown as BrowserWindow;
  637. beforeEach(() => {
  638. w = new BrowserWindow({ show: false });
  639. });
  640. afterEach(async () => {
  641. await closeWindow(w);
  642. w = null as unknown as BrowserWindow;
  643. });
  644. describe('BrowserWindow.show()', () => {
  645. it('should focus on window', async () => {
  646. await emittedOnce(w, 'focus', () => w.show());
  647. expect(w.isFocused()).to.equal(true);
  648. });
  649. it('should make the window visible', async () => {
  650. await emittedOnce(w, 'focus', () => w.show());
  651. expect(w.isVisible()).to.equal(true);
  652. });
  653. it('emits when window is shown', async () => {
  654. const show = emittedOnce(w, 'show');
  655. w.show();
  656. await show;
  657. expect(w.isVisible()).to.equal(true);
  658. });
  659. });
  660. describe('BrowserWindow.hide()', () => {
  661. it('should defocus on window', () => {
  662. w.hide();
  663. expect(w.isFocused()).to.equal(false);
  664. });
  665. it('should make the window not visible', () => {
  666. w.show();
  667. w.hide();
  668. expect(w.isVisible()).to.equal(false);
  669. });
  670. it('emits when window is hidden', async () => {
  671. const shown = emittedOnce(w, 'show');
  672. w.show();
  673. await shown;
  674. const hidden = emittedOnce(w, 'hide');
  675. w.hide();
  676. await hidden;
  677. expect(w.isVisible()).to.equal(false);
  678. });
  679. });
  680. describe('BrowserWindow.minimize()', () => {
  681. // TODO(codebytere): Enable for Linux once maximize/minimize events work in CI.
  682. ifit(process.platform !== 'linux')('should not be visible when the window is minimized', async () => {
  683. const minimize = emittedOnce(w, 'minimize');
  684. w.minimize();
  685. await minimize;
  686. expect(w.isMinimized()).to.equal(true);
  687. expect(w.isVisible()).to.equal(false);
  688. });
  689. });
  690. describe('BrowserWindow.showInactive()', () => {
  691. it('should not focus on window', () => {
  692. w.showInactive();
  693. expect(w.isFocused()).to.equal(false);
  694. });
  695. // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests
  696. ifit(process.platform !== 'linux')('should not restore maximized windows', async () => {
  697. const maximize = emittedOnce(w, 'maximize');
  698. const shown = emittedOnce(w, 'show');
  699. w.maximize();
  700. // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden
  701. if (process.platform !== 'darwin') {
  702. await maximize;
  703. } else {
  704. await delay(1000);
  705. }
  706. w.showInactive();
  707. await shown;
  708. expect(w.isMaximized()).to.equal(true);
  709. });
  710. });
  711. describe('BrowserWindow.focus()', () => {
  712. it('does not make the window become visible', () => {
  713. expect(w.isVisible()).to.equal(false);
  714. w.focus();
  715. expect(w.isVisible()).to.equal(false);
  716. });
  717. ifit(process.platform !== 'win32')('focuses a blurred window', async () => {
  718. {
  719. const isBlurred = emittedOnce(w, 'blur');
  720. const isShown = emittedOnce(w, 'show');
  721. w.show();
  722. w.blur();
  723. await isShown;
  724. await isBlurred;
  725. }
  726. expect(w.isFocused()).to.equal(false);
  727. w.focus();
  728. expect(w.isFocused()).to.equal(true);
  729. });
  730. ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => {
  731. const w1 = new BrowserWindow({ show: false });
  732. const w2 = new BrowserWindow({ show: false });
  733. const w3 = new BrowserWindow({ show: false });
  734. {
  735. const isFocused3 = emittedOnce(w3, 'focus');
  736. const isShown1 = emittedOnce(w1, 'show');
  737. const isShown2 = emittedOnce(w2, 'show');
  738. const isShown3 = emittedOnce(w3, 'show');
  739. w1.show();
  740. w2.show();
  741. w3.show();
  742. await isShown1;
  743. await isShown2;
  744. await isShown3;
  745. await isFocused3;
  746. }
  747. // TODO(RaisinTen): Investigate why this assertion fails only on Linux.
  748. expect(w1.isFocused()).to.equal(false);
  749. expect(w2.isFocused()).to.equal(false);
  750. expect(w3.isFocused()).to.equal(true);
  751. w1.focus();
  752. expect(w1.isFocused()).to.equal(true);
  753. expect(w2.isFocused()).to.equal(false);
  754. expect(w3.isFocused()).to.equal(false);
  755. w2.focus();
  756. expect(w1.isFocused()).to.equal(false);
  757. expect(w2.isFocused()).to.equal(true);
  758. expect(w3.isFocused()).to.equal(false);
  759. w3.focus();
  760. expect(w1.isFocused()).to.equal(false);
  761. expect(w2.isFocused()).to.equal(false);
  762. expect(w3.isFocused()).to.equal(true);
  763. {
  764. const isClosed1 = emittedOnce(w1, 'closed');
  765. const isClosed2 = emittedOnce(w2, 'closed');
  766. const isClosed3 = emittedOnce(w3, 'closed');
  767. w1.destroy();
  768. w2.destroy();
  769. w3.destroy();
  770. await isClosed1;
  771. await isClosed2;
  772. await isClosed3;
  773. }
  774. });
  775. });
  776. // TODO(RaisinTen): Make this work on Windows too.
  777. // Refs: https://github.com/electron/electron/issues/20464.
  778. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => {
  779. it('removes focus from window', async () => {
  780. {
  781. const isFocused = emittedOnce(w, 'focus');
  782. const isShown = emittedOnce(w, 'show');
  783. w.show();
  784. await isShown;
  785. await isFocused;
  786. }
  787. expect(w.isFocused()).to.equal(true);
  788. w.blur();
  789. expect(w.isFocused()).to.equal(false);
  790. });
  791. ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => {
  792. const w1 = new BrowserWindow({ show: false });
  793. const w2 = new BrowserWindow({ show: false });
  794. const w3 = new BrowserWindow({ show: false });
  795. {
  796. const isFocused3 = emittedOnce(w3, 'focus');
  797. const isShown1 = emittedOnce(w1, 'show');
  798. const isShown2 = emittedOnce(w2, 'show');
  799. const isShown3 = emittedOnce(w3, 'show');
  800. w1.show();
  801. w2.show();
  802. w3.show();
  803. await isShown1;
  804. await isShown2;
  805. await isShown3;
  806. await isFocused3;
  807. }
  808. // TODO(RaisinTen): Investigate why this assertion fails only on Linux.
  809. expect(w1.isFocused()).to.equal(false);
  810. expect(w2.isFocused()).to.equal(false);
  811. expect(w3.isFocused()).to.equal(true);
  812. w3.blur();
  813. expect(w1.isFocused()).to.equal(false);
  814. expect(w2.isFocused()).to.equal(true);
  815. expect(w3.isFocused()).to.equal(false);
  816. w2.blur();
  817. expect(w1.isFocused()).to.equal(true);
  818. expect(w2.isFocused()).to.equal(false);
  819. expect(w3.isFocused()).to.equal(false);
  820. w1.blur();
  821. expect(w1.isFocused()).to.equal(false);
  822. expect(w2.isFocused()).to.equal(false);
  823. expect(w3.isFocused()).to.equal(true);
  824. {
  825. const isClosed1 = emittedOnce(w1, 'closed');
  826. const isClosed2 = emittedOnce(w2, 'closed');
  827. const isClosed3 = emittedOnce(w3, 'closed');
  828. w1.destroy();
  829. w2.destroy();
  830. w3.destroy();
  831. await isClosed1;
  832. await isClosed2;
  833. await isClosed3;
  834. }
  835. });
  836. });
  837. describe('BrowserWindow.getFocusedWindow()', () => {
  838. it('returns the opener window when dev tools window is focused', async () => {
  839. await emittedOnce(w, 'focus', () => w.show());
  840. w.webContents.openDevTools({ mode: 'undocked' });
  841. await emittedOnce(w.webContents, 'devtools-focused');
  842. expect(BrowserWindow.getFocusedWindow()).to.equal(w);
  843. });
  844. });
  845. describe('BrowserWindow.moveTop()', () => {
  846. it('should not steal focus', async () => {
  847. const posDelta = 50;
  848. const wShownInactive = emittedOnce(w, 'show');
  849. w.showInactive();
  850. await wShownInactive;
  851. expect(w.isFocused()).to.equal(false);
  852. const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
  853. const otherWindowShown = emittedOnce(otherWindow, 'show');
  854. const otherWindowFocused = emittedOnce(otherWindow, 'focus');
  855. otherWindow.show();
  856. await otherWindowShown;
  857. await otherWindowFocused;
  858. expect(otherWindow.isFocused()).to.equal(true);
  859. w.moveTop();
  860. const wPos = w.getPosition();
  861. const wMoving = emittedOnce(w, 'move');
  862. w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
  863. await wMoving;
  864. expect(w.isFocused()).to.equal(false);
  865. expect(otherWindow.isFocused()).to.equal(true);
  866. const wFocused = emittedOnce(w, 'focus');
  867. const otherWindowBlurred = emittedOnce(otherWindow, 'blur');
  868. w.focus();
  869. await wFocused;
  870. await otherWindowBlurred;
  871. expect(w.isFocused()).to.equal(true);
  872. otherWindow.moveTop();
  873. const otherWindowPos = otherWindow.getPosition();
  874. const otherWindowMoving = emittedOnce(otherWindow, 'move');
  875. otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
  876. await otherWindowMoving;
  877. expect(otherWindow.isFocused()).to.equal(false);
  878. expect(w.isFocused()).to.equal(true);
  879. await closeWindow(otherWindow, { assertNotWindows: false });
  880. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
  881. });
  882. });
  883. ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => {
  884. it('should throw an exception if wrong formatting', async () => {
  885. const fakeSourceIds = [
  886. 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
  887. ];
  888. fakeSourceIds.forEach((sourceId) => {
  889. expect(() => {
  890. w.moveAbove(sourceId);
  891. }).to.throw(/Invalid media source id/);
  892. });
  893. });
  894. it('should throw an exception if wrong type', async () => {
  895. const fakeSourceIds = [null as any, 123 as any];
  896. fakeSourceIds.forEach((sourceId) => {
  897. expect(() => {
  898. w.moveAbove(sourceId);
  899. }).to.throw(/Error processing argument at index 0 */);
  900. });
  901. });
  902. it('should throw an exception if invalid window', async () => {
  903. // It is very unlikely that these window id exist.
  904. const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
  905. 'window:123456:9'];
  906. fakeSourceIds.forEach((sourceId) => {
  907. expect(() => {
  908. w.moveAbove(sourceId);
  909. }).to.throw(/Invalid media source id/);
  910. });
  911. });
  912. it('should not throw an exception', async () => {
  913. const w2 = new BrowserWindow({ show: false, title: 'window2' });
  914. const w2Shown = emittedOnce(w2, 'show');
  915. w2.show();
  916. await w2Shown;
  917. expect(() => {
  918. w.moveAbove(w2.getMediaSourceId());
  919. }).to.not.throw();
  920. await closeWindow(w2, { assertNotWindows: false });
  921. });
  922. });
  923. describe('BrowserWindow.setFocusable()', () => {
  924. it('can set unfocusable window to focusable', async () => {
  925. const w2 = new BrowserWindow({ focusable: false });
  926. const w2Focused = emittedOnce(w2, 'focus');
  927. w2.setFocusable(true);
  928. w2.focus();
  929. await w2Focused;
  930. await closeWindow(w2, { assertNotWindows: false });
  931. });
  932. });
  933. describe('BrowserWindow.isFocusable()', () => {
  934. it('correctly returns whether a window is focusable', async () => {
  935. const w2 = new BrowserWindow({ focusable: false });
  936. expect(w2.isFocusable()).to.be.false();
  937. w2.setFocusable(true);
  938. expect(w2.isFocusable()).to.be.true();
  939. await closeWindow(w2, { assertNotWindows: false });
  940. });
  941. });
  942. });
  943. describe('sizing', () => {
  944. let w = null as unknown as BrowserWindow;
  945. beforeEach(() => {
  946. w = new BrowserWindow({ show: false, width: 400, height: 400 });
  947. });
  948. afterEach(async () => {
  949. await closeWindow(w);
  950. w = null as unknown as BrowserWindow;
  951. });
  952. describe('BrowserWindow.setBounds(bounds[, animate])', () => {
  953. it('sets the window bounds with full bounds', () => {
  954. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  955. w.setBounds(fullBounds);
  956. expectBoundsEqual(w.getBounds(), fullBounds);
  957. });
  958. it('sets the window bounds with partial bounds', () => {
  959. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  960. w.setBounds(fullBounds);
  961. const boundsUpdate = { width: 200 };
  962. w.setBounds(boundsUpdate as any);
  963. const expectedBounds = { ...fullBounds, ...boundsUpdate };
  964. expectBoundsEqual(w.getBounds(), expectedBounds);
  965. });
  966. ifit(process.platform === 'darwin')('on macOS', () => {
  967. it('emits \'resized\' event after animating', async () => {
  968. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  969. w.setBounds(fullBounds, true);
  970. await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled();
  971. });
  972. });
  973. });
  974. describe('BrowserWindow.setSize(width, height)', () => {
  975. it('sets the window size', async () => {
  976. const size = [300, 400];
  977. const resized = emittedOnce(w, 'resize');
  978. w.setSize(size[0], size[1]);
  979. await resized;
  980. expectBoundsEqual(w.getSize(), size);
  981. });
  982. ifit(process.platform === 'darwin')('on macOS', () => {
  983. it('emits \'resized\' event after animating', async () => {
  984. const size = [300, 400];
  985. w.setSize(size[0], size[1], true);
  986. await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled();
  987. });
  988. });
  989. });
  990. describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
  991. it('sets the maximum and minimum size of the window', () => {
  992. expect(w.getMinimumSize()).to.deep.equal([0, 0]);
  993. expect(w.getMaximumSize()).to.deep.equal([0, 0]);
  994. w.setMinimumSize(100, 100);
  995. expectBoundsEqual(w.getMinimumSize(), [100, 100]);
  996. expectBoundsEqual(w.getMaximumSize(), [0, 0]);
  997. w.setMaximumSize(900, 600);
  998. expectBoundsEqual(w.getMinimumSize(), [100, 100]);
  999. expectBoundsEqual(w.getMaximumSize(), [900, 600]);
  1000. });
  1001. });
  1002. describe('BrowserWindow.setAspectRatio(ratio)', () => {
  1003. it('resets the behaviour when passing in 0', async () => {
  1004. const size = [300, 400];
  1005. w.setAspectRatio(1 / 2);
  1006. w.setAspectRatio(0);
  1007. const resize = emittedOnce(w, 'resize');
  1008. w.setSize(size[0], size[1]);
  1009. await resize;
  1010. expectBoundsEqual(w.getSize(), size);
  1011. });
  1012. it('doesn\'t change bounds when maximum size is set', () => {
  1013. w.setMenu(null);
  1014. w.setMaximumSize(400, 400);
  1015. // Without https://github.com/electron/electron/pull/29101
  1016. // following call would shrink the window to 384x361.
  1017. // There would be also DCHECK in resize_utils.cc on
  1018. // debug build.
  1019. w.setAspectRatio(1.0);
  1020. expectBoundsEqual(w.getSize(), [400, 400]);
  1021. });
  1022. });
  1023. describe('BrowserWindow.setPosition(x, y)', () => {
  1024. it('sets the window position', async () => {
  1025. const pos = [10, 10];
  1026. const move = emittedOnce(w, 'move');
  1027. w.setPosition(pos[0], pos[1]);
  1028. await move;
  1029. expect(w.getPosition()).to.deep.equal(pos);
  1030. });
  1031. });
  1032. describe('BrowserWindow.setContentSize(width, height)', () => {
  1033. it('sets the content size', async () => {
  1034. // NB. The CI server has a very small screen. Attempting to size the window
  1035. // larger than the screen will limit the window's size to the screen and
  1036. // cause the test to fail.
  1037. const size = [456, 567];
  1038. w.setContentSize(size[0], size[1]);
  1039. await new Promise(setImmediate);
  1040. const after = w.getContentSize();
  1041. expect(after).to.deep.equal(size);
  1042. });
  1043. it('works for a frameless window', async () => {
  1044. w.destroy();
  1045. w = new BrowserWindow({
  1046. show: false,
  1047. frame: false,
  1048. width: 400,
  1049. height: 400
  1050. });
  1051. const size = [456, 567];
  1052. w.setContentSize(size[0], size[1]);
  1053. await new Promise(setImmediate);
  1054. const after = w.getContentSize();
  1055. expect(after).to.deep.equal(size);
  1056. });
  1057. });
  1058. describe('BrowserWindow.setContentBounds(bounds)', () => {
  1059. it('sets the content size and position', async () => {
  1060. const bounds = { x: 10, y: 10, width: 250, height: 250 };
  1061. const resize = emittedOnce(w, 'resize');
  1062. w.setContentBounds(bounds);
  1063. await resize;
  1064. await delay();
  1065. expectBoundsEqual(w.getContentBounds(), bounds);
  1066. });
  1067. it('works for a frameless window', async () => {
  1068. w.destroy();
  1069. w = new BrowserWindow({
  1070. show: false,
  1071. frame: false,
  1072. width: 300,
  1073. height: 300
  1074. });
  1075. const bounds = { x: 10, y: 10, width: 250, height: 250 };
  1076. const resize = emittedOnce(w, 'resize');
  1077. w.setContentBounds(bounds);
  1078. await resize;
  1079. await delay();
  1080. expectBoundsEqual(w.getContentBounds(), bounds);
  1081. });
  1082. });
  1083. describe('BrowserWindow.getBackgroundColor()', () => {
  1084. it('returns default value if no backgroundColor is set', () => {
  1085. w.destroy();
  1086. w = new BrowserWindow({});
  1087. expect(w.getBackgroundColor()).to.equal('#FFFFFF');
  1088. });
  1089. it('returns correct value if backgroundColor is set', () => {
  1090. const backgroundColor = '#BBAAFF';
  1091. w.destroy();
  1092. w = new BrowserWindow({
  1093. backgroundColor: backgroundColor
  1094. });
  1095. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  1096. });
  1097. it('returns correct value from setBackgroundColor()', () => {
  1098. const backgroundColor = '#AABBFF';
  1099. w.destroy();
  1100. w = new BrowserWindow({});
  1101. w.setBackgroundColor(backgroundColor);
  1102. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  1103. });
  1104. it('returns correct color with multiple passed formats', () => {
  1105. w.destroy();
  1106. w = new BrowserWindow({});
  1107. w.setBackgroundColor('#AABBFF');
  1108. expect(w.getBackgroundColor()).to.equal('#AABBFF');
  1109. w.setBackgroundColor('blueviolet');
  1110. expect(w.getBackgroundColor()).to.equal('#8A2BE2');
  1111. w.setBackgroundColor('rgb(255, 0, 185)');
  1112. expect(w.getBackgroundColor()).to.equal('#FF00B9');
  1113. w.setBackgroundColor('rgba(245, 40, 145, 0.8)');
  1114. expect(w.getBackgroundColor()).to.equal('#F52891');
  1115. w.setBackgroundColor('hsl(155, 100%, 50%)');
  1116. expect(w.getBackgroundColor()).to.equal('#00FF95');
  1117. });
  1118. });
  1119. describe('BrowserWindow.getNormalBounds()', () => {
  1120. describe('Normal state', () => {
  1121. it('checks normal bounds after resize', async () => {
  1122. const size = [300, 400];
  1123. const resize = emittedOnce(w, 'resize');
  1124. w.setSize(size[0], size[1]);
  1125. await resize;
  1126. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  1127. });
  1128. it('checks normal bounds after move', async () => {
  1129. const pos = [10, 10];
  1130. const move = emittedOnce(w, 'move');
  1131. w.setPosition(pos[0], pos[1]);
  1132. await move;
  1133. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  1134. });
  1135. });
  1136. ifdescribe(process.platform !== 'linux')('Maximized state', () => {
  1137. it('checks normal bounds when maximized', async () => {
  1138. const bounds = w.getBounds();
  1139. const maximize = emittedOnce(w, 'maximize');
  1140. w.show();
  1141. w.maximize();
  1142. await maximize;
  1143. expectBoundsEqual(w.getNormalBounds(), bounds);
  1144. });
  1145. it('updates normal bounds after resize and maximize', async () => {
  1146. const size = [300, 400];
  1147. const resize = emittedOnce(w, 'resize');
  1148. w.setSize(size[0], size[1]);
  1149. await resize;
  1150. const original = w.getBounds();
  1151. const maximize = emittedOnce(w, 'maximize');
  1152. w.maximize();
  1153. await maximize;
  1154. const normal = w.getNormalBounds();
  1155. const bounds = w.getBounds();
  1156. expect(normal).to.deep.equal(original);
  1157. expect(normal).to.not.deep.equal(bounds);
  1158. const close = emittedOnce(w, 'close');
  1159. w.close();
  1160. await close;
  1161. });
  1162. it('updates normal bounds after move and maximize', async () => {
  1163. const pos = [10, 10];
  1164. const move = emittedOnce(w, 'move');
  1165. w.setPosition(pos[0], pos[1]);
  1166. await move;
  1167. const original = w.getBounds();
  1168. const maximize = emittedOnce(w, 'maximize');
  1169. w.maximize();
  1170. await maximize;
  1171. const normal = w.getNormalBounds();
  1172. const bounds = w.getBounds();
  1173. expect(normal).to.deep.equal(original);
  1174. expect(normal).to.not.deep.equal(bounds);
  1175. const close = emittedOnce(w, 'close');
  1176. w.close();
  1177. await close;
  1178. });
  1179. it('checks normal bounds when unmaximized', async () => {
  1180. const bounds = w.getBounds();
  1181. w.once('maximize', () => {
  1182. w.unmaximize();
  1183. });
  1184. const unmaximize = emittedOnce(w, 'unmaximize');
  1185. w.show();
  1186. w.maximize();
  1187. await unmaximize;
  1188. expectBoundsEqual(w.getNormalBounds(), bounds);
  1189. });
  1190. it('does not change size for a frameless window with min size', async () => {
  1191. w.destroy();
  1192. w = new BrowserWindow({
  1193. show: false,
  1194. frame: false,
  1195. width: 300,
  1196. height: 300,
  1197. minWidth: 300,
  1198. minHeight: 300
  1199. });
  1200. const bounds = w.getBounds();
  1201. w.once('maximize', () => {
  1202. w.unmaximize();
  1203. });
  1204. const unmaximize = emittedOnce(w, 'unmaximize');
  1205. w.show();
  1206. w.maximize();
  1207. await unmaximize;
  1208. expectBoundsEqual(w.getNormalBounds(), bounds);
  1209. });
  1210. it('correctly checks transparent window maximization state', async () => {
  1211. w.destroy();
  1212. w = new BrowserWindow({
  1213. show: false,
  1214. width: 300,
  1215. height: 300,
  1216. transparent: true
  1217. });
  1218. const maximize = emittedOnce(w, 'maximize');
  1219. w.show();
  1220. w.maximize();
  1221. await maximize;
  1222. expect(w.isMaximized()).to.equal(true);
  1223. const unmaximize = emittedOnce(w, 'unmaximize');
  1224. w.unmaximize();
  1225. await unmaximize;
  1226. expect(w.isMaximized()).to.equal(false);
  1227. });
  1228. it('returns the correct value for windows with an aspect ratio', async () => {
  1229. w.destroy();
  1230. w = new BrowserWindow({
  1231. show: false,
  1232. fullscreenable: false
  1233. });
  1234. w.setAspectRatio(16 / 11);
  1235. const maximize = emittedOnce(w, 'maximize');
  1236. w.show();
  1237. w.maximize();
  1238. await maximize;
  1239. expect(w.isMaximized()).to.equal(true);
  1240. w.resizable = false;
  1241. expect(w.isMaximized()).to.equal(true);
  1242. });
  1243. });
  1244. ifdescribe(process.platform !== 'linux')('Minimized state', () => {
  1245. it('checks normal bounds when minimized', async () => {
  1246. const bounds = w.getBounds();
  1247. const minimize = emittedOnce(w, 'minimize');
  1248. w.show();
  1249. w.minimize();
  1250. await minimize;
  1251. expectBoundsEqual(w.getNormalBounds(), bounds);
  1252. });
  1253. it('updates normal bounds after move and minimize', async () => {
  1254. const pos = [10, 10];
  1255. const move = emittedOnce(w, 'move');
  1256. w.setPosition(pos[0], pos[1]);
  1257. await move;
  1258. const original = w.getBounds();
  1259. const minimize = emittedOnce(w, 'minimize');
  1260. w.minimize();
  1261. await minimize;
  1262. const normal = w.getNormalBounds();
  1263. expect(original).to.deep.equal(normal);
  1264. expectBoundsEqual(normal, w.getBounds());
  1265. });
  1266. it('updates normal bounds after resize and minimize', async () => {
  1267. const size = [300, 400];
  1268. const resize = emittedOnce(w, 'resize');
  1269. w.setSize(size[0], size[1]);
  1270. await resize;
  1271. const original = w.getBounds();
  1272. const minimize = emittedOnce(w, 'minimize');
  1273. w.minimize();
  1274. await minimize;
  1275. const normal = w.getNormalBounds();
  1276. expect(original).to.deep.equal(normal);
  1277. expectBoundsEqual(normal, w.getBounds());
  1278. });
  1279. it('checks normal bounds when restored', async () => {
  1280. const bounds = w.getBounds();
  1281. w.once('minimize', () => {
  1282. w.restore();
  1283. });
  1284. const restore = emittedOnce(w, 'restore');
  1285. w.show();
  1286. w.minimize();
  1287. await restore;
  1288. expectBoundsEqual(w.getNormalBounds(), bounds);
  1289. });
  1290. it('correctly reports maximized state after maximizing then minimizing', async () => {
  1291. w.destroy();
  1292. w = new BrowserWindow({ show: false });
  1293. w.show();
  1294. const maximize = emittedOnce(w, 'maximize');
  1295. w.maximize();
  1296. await maximize;
  1297. const minimize = emittedOnce(w, 'minimize');
  1298. w.minimize();
  1299. await minimize;
  1300. expect(w.isMaximized()).to.equal(false);
  1301. expect(w.isMinimized()).to.equal(true);
  1302. });
  1303. it('correctly reports maximized state after maximizing then fullscreening', async () => {
  1304. w.destroy();
  1305. w = new BrowserWindow({ show: false });
  1306. w.show();
  1307. const maximize = emittedOnce(w, 'maximize');
  1308. w.maximize();
  1309. await maximize;
  1310. const enterFS = emittedOnce(w, 'enter-full-screen');
  1311. w.setFullScreen(true);
  1312. await enterFS;
  1313. expect(w.isMaximized()).to.equal(false);
  1314. expect(w.isFullScreen()).to.equal(true);
  1315. });
  1316. it('checks normal bounds for maximized transparent window', async () => {
  1317. w.destroy();
  1318. w = new BrowserWindow({
  1319. transparent: true,
  1320. show: false
  1321. });
  1322. w.show();
  1323. const bounds = w.getNormalBounds();
  1324. const maximize = emittedOnce(w, 'maximize');
  1325. w.maximize();
  1326. await maximize;
  1327. expectBoundsEqual(w.getNormalBounds(), bounds);
  1328. });
  1329. it('does not change size for a frameless window with min size', async () => {
  1330. w.destroy();
  1331. w = new BrowserWindow({
  1332. show: false,
  1333. frame: false,
  1334. width: 300,
  1335. height: 300,
  1336. minWidth: 300,
  1337. minHeight: 300
  1338. });
  1339. const bounds = w.getBounds();
  1340. w.once('minimize', () => {
  1341. w.restore();
  1342. });
  1343. const restore = emittedOnce(w, 'restore');
  1344. w.show();
  1345. w.minimize();
  1346. await restore;
  1347. expectBoundsEqual(w.getNormalBounds(), bounds);
  1348. });
  1349. });
  1350. ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
  1351. it('with properties', () => {
  1352. it('can be set with the fullscreen constructor option', () => {
  1353. w = new BrowserWindow({ fullscreen: true });
  1354. expect(w.fullScreen).to.be.true();
  1355. });
  1356. it('does not go fullscreen if roundedCorners are enabled', async () => {
  1357. w = new BrowserWindow({ frame: false, roundedCorners: false, fullscreen: true });
  1358. expect(w.fullScreen).to.be.false();
  1359. });
  1360. it('can be changed', () => {
  1361. w.fullScreen = false;
  1362. expect(w.fullScreen).to.be.false();
  1363. w.fullScreen = true;
  1364. expect(w.fullScreen).to.be.true();
  1365. });
  1366. it('checks normal bounds when fullscreen\'ed', async () => {
  1367. const bounds = w.getBounds();
  1368. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1369. w.show();
  1370. w.fullScreen = true;
  1371. await enterFullScreen;
  1372. expectBoundsEqual(w.getNormalBounds(), bounds);
  1373. });
  1374. it('updates normal bounds after resize and fullscreen', async () => {
  1375. const size = [300, 400];
  1376. const resize = emittedOnce(w, 'resize');
  1377. w.setSize(size[0], size[1]);
  1378. await resize;
  1379. const original = w.getBounds();
  1380. const fsc = emittedOnce(w, 'enter-full-screen');
  1381. w.fullScreen = true;
  1382. await fsc;
  1383. const normal = w.getNormalBounds();
  1384. const bounds = w.getBounds();
  1385. expect(normal).to.deep.equal(original);
  1386. expect(normal).to.not.deep.equal(bounds);
  1387. const close = emittedOnce(w, 'close');
  1388. w.close();
  1389. await close;
  1390. });
  1391. it('updates normal bounds after move and fullscreen', async () => {
  1392. const pos = [10, 10];
  1393. const move = emittedOnce(w, 'move');
  1394. w.setPosition(pos[0], pos[1]);
  1395. await move;
  1396. const original = w.getBounds();
  1397. const fsc = emittedOnce(w, 'enter-full-screen');
  1398. w.fullScreen = true;
  1399. await fsc;
  1400. const normal = w.getNormalBounds();
  1401. const bounds = w.getBounds();
  1402. expect(normal).to.deep.equal(original);
  1403. expect(normal).to.not.deep.equal(bounds);
  1404. const close = emittedOnce(w, 'close');
  1405. w.close();
  1406. await close;
  1407. });
  1408. it('checks normal bounds when unfullscreen\'ed', async () => {
  1409. const bounds = w.getBounds();
  1410. w.once('enter-full-screen', () => {
  1411. w.fullScreen = false;
  1412. });
  1413. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1414. w.show();
  1415. w.fullScreen = true;
  1416. await leaveFullScreen;
  1417. expectBoundsEqual(w.getNormalBounds(), bounds);
  1418. });
  1419. });
  1420. it('with functions', () => {
  1421. it('can be set with the fullscreen constructor option', () => {
  1422. w = new BrowserWindow({ fullscreen: true });
  1423. expect(w.isFullScreen()).to.be.true();
  1424. });
  1425. it('can be changed', () => {
  1426. w.setFullScreen(false);
  1427. expect(w.isFullScreen()).to.be.false();
  1428. w.setFullScreen(true);
  1429. expect(w.isFullScreen()).to.be.true();
  1430. });
  1431. it('checks normal bounds when fullscreen\'ed', async () => {
  1432. const bounds = w.getBounds();
  1433. w.show();
  1434. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1435. w.setFullScreen(true);
  1436. await enterFullScreen;
  1437. expectBoundsEqual(w.getNormalBounds(), bounds);
  1438. });
  1439. it('updates normal bounds after resize and fullscreen', async () => {
  1440. const size = [300, 400];
  1441. const resize = emittedOnce(w, 'resize');
  1442. w.setSize(size[0], size[1]);
  1443. await resize;
  1444. const original = w.getBounds();
  1445. const fsc = emittedOnce(w, 'enter-full-screen');
  1446. w.setFullScreen(true);
  1447. await fsc;
  1448. const normal = w.getNormalBounds();
  1449. const bounds = w.getBounds();
  1450. expect(normal).to.deep.equal(original);
  1451. expect(normal).to.not.deep.equal(bounds);
  1452. const close = emittedOnce(w, 'close');
  1453. w.close();
  1454. await close;
  1455. });
  1456. it('updates normal bounds after move and fullscreen', async () => {
  1457. const pos = [10, 10];
  1458. const move = emittedOnce(w, 'move');
  1459. w.setPosition(pos[0], pos[1]);
  1460. await move;
  1461. const original = w.getBounds();
  1462. const fsc = emittedOnce(w, 'enter-full-screen');
  1463. w.setFullScreen(true);
  1464. await fsc;
  1465. const normal = w.getNormalBounds();
  1466. const bounds = w.getBounds();
  1467. expect(normal).to.deep.equal(original);
  1468. expect(normal).to.not.deep.equal(bounds);
  1469. const close = emittedOnce(w, 'close');
  1470. w.close();
  1471. await close;
  1472. });
  1473. it('checks normal bounds when unfullscreen\'ed', async () => {
  1474. const bounds = w.getBounds();
  1475. w.show();
  1476. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1477. w.setFullScreen(true);
  1478. await enterFullScreen;
  1479. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1480. w.setFullScreen(false);
  1481. await leaveFullScreen;
  1482. expectBoundsEqual(w.getNormalBounds(), bounds);
  1483. });
  1484. });
  1485. });
  1486. });
  1487. });
  1488. ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
  1489. let w = null as unknown as BrowserWindow;
  1490. beforeEach(() => {
  1491. w = new BrowserWindow({ show: false });
  1492. });
  1493. afterEach(async () => {
  1494. await closeWindow(w);
  1495. w = null as unknown as BrowserWindow;
  1496. });
  1497. describe('BrowserWindow.selectPreviousTab()', () => {
  1498. it('does not throw', () => {
  1499. expect(() => {
  1500. w.selectPreviousTab();
  1501. }).to.not.throw();
  1502. });
  1503. });
  1504. describe('BrowserWindow.selectNextTab()', () => {
  1505. it('does not throw', () => {
  1506. expect(() => {
  1507. w.selectNextTab();
  1508. }).to.not.throw();
  1509. });
  1510. });
  1511. describe('BrowserWindow.mergeAllWindows()', () => {
  1512. it('does not throw', () => {
  1513. expect(() => {
  1514. w.mergeAllWindows();
  1515. }).to.not.throw();
  1516. });
  1517. });
  1518. describe('BrowserWindow.moveTabToNewWindow()', () => {
  1519. it('does not throw', () => {
  1520. expect(() => {
  1521. w.moveTabToNewWindow();
  1522. }).to.not.throw();
  1523. });
  1524. });
  1525. describe('BrowserWindow.toggleTabBar()', () => {
  1526. it('does not throw', () => {
  1527. expect(() => {
  1528. w.toggleTabBar();
  1529. }).to.not.throw();
  1530. });
  1531. });
  1532. describe('BrowserWindow.addTabbedWindow()', () => {
  1533. it('does not throw', async () => {
  1534. const tabbedWindow = new BrowserWindow({});
  1535. expect(() => {
  1536. w.addTabbedWindow(tabbedWindow);
  1537. }).to.not.throw();
  1538. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
  1539. await closeWindow(tabbedWindow, { assertNotWindows: false });
  1540. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
  1541. });
  1542. it('throws when called on itself', () => {
  1543. expect(() => {
  1544. w.addTabbedWindow(w);
  1545. }).to.throw('AddTabbedWindow cannot be called by a window on itself.');
  1546. });
  1547. });
  1548. });
  1549. describe('autoHideMenuBar state', () => {
  1550. afterEach(closeAllWindows);
  1551. it('for properties', () => {
  1552. it('can be set with autoHideMenuBar constructor option', () => {
  1553. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1554. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1555. });
  1556. it('can be changed', () => {
  1557. const w = new BrowserWindow({ show: false });
  1558. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1559. w.autoHideMenuBar = true;
  1560. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1561. w.autoHideMenuBar = false;
  1562. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1563. });
  1564. });
  1565. it('for functions', () => {
  1566. it('can be set with autoHideMenuBar constructor option', () => {
  1567. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1568. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1569. });
  1570. it('can be changed', () => {
  1571. const w = new BrowserWindow({ show: false });
  1572. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1573. w.setAutoHideMenuBar(true);
  1574. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1575. w.setAutoHideMenuBar(false);
  1576. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1577. });
  1578. });
  1579. });
  1580. describe('BrowserWindow.capturePage(rect)', () => {
  1581. afterEach(closeAllWindows);
  1582. it('returns a Promise with a Buffer', async () => {
  1583. const w = new BrowserWindow({ show: false });
  1584. const image = await w.capturePage({
  1585. x: 0,
  1586. y: 0,
  1587. width: 100,
  1588. height: 100
  1589. });
  1590. expect(image.isEmpty()).to.equal(true);
  1591. });
  1592. ifit(process.platform === 'darwin')('honors the stayHidden argument', async () => {
  1593. const w = new BrowserWindow({
  1594. webPreferences: {
  1595. nodeIntegration: true,
  1596. contextIsolation: false
  1597. }
  1598. });
  1599. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  1600. {
  1601. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  1602. expect(visibilityState).to.equal('visible');
  1603. expect(hidden).to.be.false('hidden');
  1604. }
  1605. w.hide();
  1606. {
  1607. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  1608. expect(visibilityState).to.equal('hidden');
  1609. expect(hidden).to.be.true('hidden');
  1610. }
  1611. await w.capturePage({ x: 0, y: 0, width: 0, height: 0 }, { stayHidden: true });
  1612. const visible = await w.webContents.executeJavaScript('document.visibilityState');
  1613. expect(visible).to.equal('hidden');
  1614. });
  1615. it('resolves after the window is hidden', async () => {
  1616. const w = new BrowserWindow({ show: false });
  1617. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  1618. await emittedOnce(w, 'ready-to-show');
  1619. w.show();
  1620. const visibleImage = await w.capturePage();
  1621. expect(visibleImage.isEmpty()).to.equal(false);
  1622. w.hide();
  1623. const hiddenImage = await w.capturePage();
  1624. const isEmpty = process.platform !== 'darwin';
  1625. expect(hiddenImage.isEmpty()).to.equal(isEmpty);
  1626. });
  1627. it('resolves after the window is hidden and capturer count is non-zero', async () => {
  1628. const w = new BrowserWindow({ show: false });
  1629. w.webContents.setBackgroundThrottling(false);
  1630. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  1631. await emittedOnce(w, 'ready-to-show');
  1632. const image = await w.capturePage();
  1633. expect(image.isEmpty()).to.equal(false);
  1634. });
  1635. it('preserves transparency', async () => {
  1636. const w = new BrowserWindow({ show: false, transparent: true });
  1637. w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
  1638. await emittedOnce(w, 'ready-to-show');
  1639. w.show();
  1640. const image = await w.capturePage();
  1641. const imgBuffer = image.toPNG();
  1642. // Check the 25th byte in the PNG.
  1643. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  1644. expect(imgBuffer[25]).to.equal(6);
  1645. });
  1646. });
  1647. describe('BrowserWindow.setProgressBar(progress)', () => {
  1648. let w = null as unknown as BrowserWindow;
  1649. before(() => {
  1650. w = new BrowserWindow({ show: false });
  1651. });
  1652. after(async () => {
  1653. await closeWindow(w);
  1654. w = null as unknown as BrowserWindow;
  1655. });
  1656. it('sets the progress', () => {
  1657. expect(() => {
  1658. if (process.platform === 'darwin') {
  1659. app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
  1660. }
  1661. w.setProgressBar(0.5);
  1662. if (process.platform === 'darwin') {
  1663. app.dock.setIcon(null as any);
  1664. }
  1665. w.setProgressBar(-1);
  1666. }).to.not.throw();
  1667. });
  1668. it('sets the progress using "paused" mode', () => {
  1669. expect(() => {
  1670. w.setProgressBar(0.5, { mode: 'paused' });
  1671. }).to.not.throw();
  1672. });
  1673. it('sets the progress using "error" mode', () => {
  1674. expect(() => {
  1675. w.setProgressBar(0.5, { mode: 'error' });
  1676. }).to.not.throw();
  1677. });
  1678. it('sets the progress using "normal" mode', () => {
  1679. expect(() => {
  1680. w.setProgressBar(0.5, { mode: 'normal' });
  1681. }).to.not.throw();
  1682. });
  1683. });
  1684. describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
  1685. let w = null as unknown as BrowserWindow;
  1686. afterEach(closeAllWindows);
  1687. beforeEach(() => {
  1688. w = new BrowserWindow({ show: true });
  1689. });
  1690. it('sets the window as always on top', () => {
  1691. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1692. w.setAlwaysOnTop(true, 'screen-saver');
  1693. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1694. w.setAlwaysOnTop(false);
  1695. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1696. w.setAlwaysOnTop(true);
  1697. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1698. });
  1699. ifit(process.platform === 'darwin')('resets the windows level on minimize', () => {
  1700. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1701. w.setAlwaysOnTop(true, 'screen-saver');
  1702. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1703. w.minimize();
  1704. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1705. w.restore();
  1706. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1707. });
  1708. it('causes the right value to be emitted on `always-on-top-changed`', async () => {
  1709. const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed');
  1710. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1711. w.setAlwaysOnTop(true);
  1712. const [, alwaysOnTop] = await alwaysOnTopChanged;
  1713. expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
  1714. });
  1715. ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
  1716. w = new BrowserWindow({ show: false });
  1717. const c = new BrowserWindow({ parent: w });
  1718. c.setAlwaysOnTop(true, 'screen-saver');
  1719. expect(w.isAlwaysOnTop()).to.be.false();
  1720. expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
  1721. expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver');
  1722. });
  1723. });
  1724. describe('preconnect feature', () => {
  1725. let w = null as unknown as BrowserWindow;
  1726. let server = null as unknown as http.Server;
  1727. let url = null as unknown as string;
  1728. let connections = 0;
  1729. beforeEach(async () => {
  1730. connections = 0;
  1731. server = http.createServer((req, res) => {
  1732. if (req.url === '/link') {
  1733. res.setHeader('Content-type', 'text/html');
  1734. res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
  1735. return;
  1736. }
  1737. res.end();
  1738. });
  1739. server.on('connection', () => { connections++; });
  1740. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()));
  1741. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1742. });
  1743. afterEach(async () => {
  1744. server.close();
  1745. await closeWindow(w);
  1746. w = null as unknown as BrowserWindow;
  1747. server = null as unknown as http.Server;
  1748. });
  1749. it('calling preconnect() connects to the server', async () => {
  1750. w = new BrowserWindow({ show: false });
  1751. w.webContents.on('did-start-navigation', (event, url) => {
  1752. w.webContents.session.preconnect({ url, numSockets: 4 });
  1753. });
  1754. await w.loadURL(url);
  1755. expect(connections).to.equal(4);
  1756. });
  1757. it('does not preconnect unless requested', async () => {
  1758. w = new BrowserWindow({ show: false });
  1759. await w.loadURL(url);
  1760. expect(connections).to.equal(1);
  1761. });
  1762. it('parses <link rel=preconnect>', async () => {
  1763. w = new BrowserWindow({ show: true });
  1764. const p = emittedOnce(w.webContents.session, 'preconnect');
  1765. w.loadURL(url + '/link');
  1766. const [, preconnectUrl, allowCredentials] = await p;
  1767. expect(preconnectUrl).to.equal('http://example.com/');
  1768. expect(allowCredentials).to.be.true('allowCredentials');
  1769. });
  1770. });
  1771. describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
  1772. let w = null as unknown as BrowserWindow;
  1773. beforeEach(() => {
  1774. w = new BrowserWindow({ show: false });
  1775. });
  1776. afterEach(async () => {
  1777. await closeWindow(w);
  1778. w = null as unknown as BrowserWindow;
  1779. });
  1780. ifit(process.platform === 'darwin')('on macOS', () => {
  1781. it('allows changing cursor auto-hiding', () => {
  1782. expect(() => {
  1783. w.setAutoHideCursor(false);
  1784. w.setAutoHideCursor(true);
  1785. }).to.not.throw();
  1786. });
  1787. });
  1788. ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
  1789. it('is not available', () => {
  1790. expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
  1791. });
  1792. });
  1793. });
  1794. ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
  1795. afterEach(closeAllWindows);
  1796. it('does not throw', () => {
  1797. const w = new BrowserWindow({ show: false });
  1798. expect(() => {
  1799. w.setWindowButtonVisibility(true);
  1800. w.setWindowButtonVisibility(false);
  1801. }).to.not.throw();
  1802. });
  1803. it('changes window button visibility for normal window', () => {
  1804. const w = new BrowserWindow({ show: false });
  1805. expect(w._getWindowButtonVisibility()).to.equal(true);
  1806. w.setWindowButtonVisibility(false);
  1807. expect(w._getWindowButtonVisibility()).to.equal(false);
  1808. w.setWindowButtonVisibility(true);
  1809. expect(w._getWindowButtonVisibility()).to.equal(true);
  1810. });
  1811. it('changes window button visibility for frameless window', () => {
  1812. const w = new BrowserWindow({ show: false, frame: false });
  1813. expect(w._getWindowButtonVisibility()).to.equal(false);
  1814. w.setWindowButtonVisibility(true);
  1815. expect(w._getWindowButtonVisibility()).to.equal(true);
  1816. w.setWindowButtonVisibility(false);
  1817. expect(w._getWindowButtonVisibility()).to.equal(false);
  1818. });
  1819. it('changes window button visibility for hiddenInset window', () => {
  1820. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  1821. expect(w._getWindowButtonVisibility()).to.equal(true);
  1822. w.setWindowButtonVisibility(false);
  1823. expect(w._getWindowButtonVisibility()).to.equal(false);
  1824. w.setWindowButtonVisibility(true);
  1825. expect(w._getWindowButtonVisibility()).to.equal(true);
  1826. });
  1827. // Buttons of customButtonsOnHover are always hidden unless hovered.
  1828. it('does not change window button visibility for customButtonsOnHover window', () => {
  1829. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
  1830. expect(w._getWindowButtonVisibility()).to.equal(false);
  1831. w.setWindowButtonVisibility(true);
  1832. expect(w._getWindowButtonVisibility()).to.equal(false);
  1833. w.setWindowButtonVisibility(false);
  1834. expect(w._getWindowButtonVisibility()).to.equal(false);
  1835. });
  1836. it('correctly updates when entering/exiting fullscreen for hidden style', async () => {
  1837. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' });
  1838. expect(w._getWindowButtonVisibility()).to.equal(true);
  1839. w.setWindowButtonVisibility(false);
  1840. expect(w._getWindowButtonVisibility()).to.equal(false);
  1841. const enterFS = emittedOnce(w, 'enter-full-screen');
  1842. w.setFullScreen(true);
  1843. await enterFS;
  1844. const leaveFS = emittedOnce(w, 'leave-full-screen');
  1845. w.setFullScreen(false);
  1846. await leaveFS;
  1847. w.setWindowButtonVisibility(true);
  1848. expect(w._getWindowButtonVisibility()).to.equal(true);
  1849. });
  1850. it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => {
  1851. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  1852. expect(w._getWindowButtonVisibility()).to.equal(true);
  1853. w.setWindowButtonVisibility(false);
  1854. expect(w._getWindowButtonVisibility()).to.equal(false);
  1855. const enterFS = emittedOnce(w, 'enter-full-screen');
  1856. w.setFullScreen(true);
  1857. await enterFS;
  1858. const leaveFS = emittedOnce(w, 'leave-full-screen');
  1859. w.setFullScreen(false);
  1860. await leaveFS;
  1861. w.setWindowButtonVisibility(true);
  1862. expect(w._getWindowButtonVisibility()).to.equal(true);
  1863. });
  1864. });
  1865. ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
  1866. afterEach(closeAllWindows);
  1867. it('allows setting, changing, and removing the vibrancy', () => {
  1868. const w = new BrowserWindow({ show: false });
  1869. expect(() => {
  1870. w.setVibrancy('light');
  1871. w.setVibrancy('dark');
  1872. w.setVibrancy(null);
  1873. w.setVibrancy('ultra-dark');
  1874. w.setVibrancy('' as any);
  1875. }).to.not.throw();
  1876. });
  1877. it('does not crash if vibrancy is set to an invalid value', () => {
  1878. const w = new BrowserWindow({ show: false });
  1879. expect(() => {
  1880. w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
  1881. }).to.not.throw();
  1882. });
  1883. });
  1884. ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
  1885. const pos = { x: 10, y: 10 };
  1886. afterEach(closeAllWindows);
  1887. describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
  1888. it('gets position property for "hidden" titleBarStyle', () => {
  1889. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1890. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1891. });
  1892. it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
  1893. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1894. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1895. });
  1896. });
  1897. describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
  1898. it('sets position property for "hidden" titleBarStyle', () => {
  1899. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1900. const newPos = { x: 20, y: 20 };
  1901. w.setTrafficLightPosition(newPos);
  1902. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1903. });
  1904. it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
  1905. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1906. const newPos = { x: 20, y: 20 };
  1907. w.setTrafficLightPosition(newPos);
  1908. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1909. });
  1910. });
  1911. });
  1912. ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
  1913. afterEach(closeAllWindows);
  1914. it('supports setting the app details', () => {
  1915. const w = new BrowserWindow({ show: false });
  1916. const iconPath = path.join(fixtures, 'assets', 'icon.ico');
  1917. expect(() => {
  1918. w.setAppDetails({ appId: 'my.app.id' });
  1919. w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
  1920. w.setAppDetails({ appIconPath: iconPath });
  1921. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
  1922. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
  1923. w.setAppDetails({ relaunchDisplayName: 'My app name' });
  1924. w.setAppDetails({
  1925. appId: 'my.app.id',
  1926. appIconPath: iconPath,
  1927. appIconIndex: 0,
  1928. relaunchCommand: 'my-app.exe arg1 arg2',
  1929. relaunchDisplayName: 'My app name'
  1930. });
  1931. w.setAppDetails({});
  1932. }).to.not.throw();
  1933. expect(() => {
  1934. (w.setAppDetails as any)();
  1935. }).to.throw('Insufficient number of arguments.');
  1936. });
  1937. });
  1938. describe('BrowserWindow.fromId(id)', () => {
  1939. afterEach(closeAllWindows);
  1940. it('returns the window with id', () => {
  1941. const w = new BrowserWindow({ show: false });
  1942. expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
  1943. });
  1944. });
  1945. describe('Opening a BrowserWindow from a link', () => {
  1946. let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
  1947. afterEach(() => {
  1948. if (appProcess && !appProcess.killed) {
  1949. appProcess.kill();
  1950. appProcess = undefined;
  1951. }
  1952. });
  1953. it('can properly open and load a new window from a link', async () => {
  1954. const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link');
  1955. appProcess = childProcess.spawn(process.execPath, [appPath]);
  1956. const [code] = await emittedOnce(appProcess, 'exit');
  1957. expect(code).to.equal(0);
  1958. });
  1959. });
  1960. describe('BrowserWindow.fromWebContents(webContents)', () => {
  1961. afterEach(closeAllWindows);
  1962. it('returns the window with the webContents', () => {
  1963. const w = new BrowserWindow({ show: false });
  1964. const found = BrowserWindow.fromWebContents(w.webContents);
  1965. expect(found!.id).to.equal(w.id);
  1966. });
  1967. it('returns null for webContents without a BrowserWindow', () => {
  1968. const contents = (webContents as any).create({});
  1969. try {
  1970. expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
  1971. } finally {
  1972. contents.destroy();
  1973. }
  1974. });
  1975. it('returns the correct window for a BrowserView webcontents', async () => {
  1976. const w = new BrowserWindow({ show: false });
  1977. const bv = new BrowserView();
  1978. w.setBrowserView(bv);
  1979. defer(() => {
  1980. w.removeBrowserView(bv);
  1981. bv.webContents.destroy();
  1982. });
  1983. await bv.webContents.loadURL('about:blank');
  1984. expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
  1985. });
  1986. it('returns the correct window for a WebView webcontents', async () => {
  1987. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  1988. w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
  1989. // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
  1990. // https://github.com/electron/electron/issues/25413, and is not integral
  1991. // to the test.
  1992. const p = emittedOnce(w.webContents, 'did-attach-webview');
  1993. const [, webviewContents] = await emittedOnce(app, 'web-contents-created');
  1994. expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
  1995. await p;
  1996. });
  1997. it('is usable immediately on browser-window-created', async () => {
  1998. const w = new BrowserWindow({ show: false });
  1999. w.loadURL('about:blank');
  2000. w.webContents.executeJavaScript('window.open(""); null');
  2001. const [win, winFromWebContents] = await new Promise((resolve) => {
  2002. app.once('browser-window-created', (e, win) => {
  2003. resolve([win, BrowserWindow.fromWebContents(win.webContents)]);
  2004. });
  2005. });
  2006. expect(winFromWebContents).to.equal(win);
  2007. });
  2008. });
  2009. describe('BrowserWindow.openDevTools()', () => {
  2010. afterEach(closeAllWindows);
  2011. it('does not crash for frameless window', () => {
  2012. const w = new BrowserWindow({ show: false, frame: false });
  2013. w.webContents.openDevTools();
  2014. });
  2015. });
  2016. describe('BrowserWindow.fromBrowserView(browserView)', () => {
  2017. afterEach(closeAllWindows);
  2018. it('returns the window with the BrowserView', () => {
  2019. const w = new BrowserWindow({ show: false });
  2020. const bv = new BrowserView();
  2021. w.setBrowserView(bv);
  2022. defer(() => {
  2023. w.removeBrowserView(bv);
  2024. bv.webContents.destroy();
  2025. });
  2026. expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
  2027. });
  2028. it('returns the window when there are multiple BrowserViews', () => {
  2029. const w = new BrowserWindow({ show: false });
  2030. const bv1 = new BrowserView();
  2031. w.addBrowserView(bv1);
  2032. const bv2 = new BrowserView();
  2033. w.addBrowserView(bv2);
  2034. defer(() => {
  2035. w.removeBrowserView(bv1);
  2036. w.removeBrowserView(bv2);
  2037. bv1.webContents.destroy();
  2038. bv2.webContents.destroy();
  2039. });
  2040. expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
  2041. expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
  2042. });
  2043. it('returns undefined if not attached', () => {
  2044. const bv = new BrowserView();
  2045. defer(() => {
  2046. bv.webContents.destroy();
  2047. });
  2048. expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
  2049. });
  2050. });
  2051. describe('BrowserWindow.setOpacity(opacity)', () => {
  2052. afterEach(closeAllWindows);
  2053. ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
  2054. it('make window with initial opacity', () => {
  2055. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  2056. expect(w.getOpacity()).to.equal(0.5);
  2057. });
  2058. it('allows setting the opacity', () => {
  2059. const w = new BrowserWindow({ show: false });
  2060. expect(() => {
  2061. w.setOpacity(0.0);
  2062. expect(w.getOpacity()).to.equal(0.0);
  2063. w.setOpacity(0.5);
  2064. expect(w.getOpacity()).to.equal(0.5);
  2065. w.setOpacity(1.0);
  2066. expect(w.getOpacity()).to.equal(1.0);
  2067. }).to.not.throw();
  2068. });
  2069. it('clamps opacity to [0.0...1.0]', () => {
  2070. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  2071. w.setOpacity(100);
  2072. expect(w.getOpacity()).to.equal(1.0);
  2073. w.setOpacity(-100);
  2074. expect(w.getOpacity()).to.equal(0.0);
  2075. });
  2076. });
  2077. ifdescribe(process.platform === 'linux')(('Linux'), () => {
  2078. it('sets 1 regardless of parameter', () => {
  2079. const w = new BrowserWindow({ show: false });
  2080. w.setOpacity(0);
  2081. expect(w.getOpacity()).to.equal(1.0);
  2082. w.setOpacity(0.5);
  2083. expect(w.getOpacity()).to.equal(1.0);
  2084. });
  2085. });
  2086. });
  2087. describe('BrowserWindow.setShape(rects)', () => {
  2088. afterEach(closeAllWindows);
  2089. it('allows setting shape', () => {
  2090. const w = new BrowserWindow({ show: false });
  2091. expect(() => {
  2092. w.setShape([]);
  2093. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
  2094. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
  2095. w.setShape([]);
  2096. }).to.not.throw();
  2097. });
  2098. });
  2099. describe('"useContentSize" option', () => {
  2100. afterEach(closeAllWindows);
  2101. it('make window created with content size when used', () => {
  2102. const w = new BrowserWindow({
  2103. show: false,
  2104. width: 400,
  2105. height: 400,
  2106. useContentSize: true
  2107. });
  2108. const contentSize = w.getContentSize();
  2109. expect(contentSize).to.deep.equal([400, 400]);
  2110. });
  2111. it('make window created with window size when not used', () => {
  2112. const w = new BrowserWindow({
  2113. show: false,
  2114. width: 400,
  2115. height: 400
  2116. });
  2117. const size = w.getSize();
  2118. expect(size).to.deep.equal([400, 400]);
  2119. });
  2120. it('works for a frameless window', () => {
  2121. const w = new BrowserWindow({
  2122. show: false,
  2123. frame: false,
  2124. width: 400,
  2125. height: 400,
  2126. useContentSize: true
  2127. });
  2128. const contentSize = w.getContentSize();
  2129. expect(contentSize).to.deep.equal([400, 400]);
  2130. const size = w.getSize();
  2131. expect(size).to.deep.equal([400, 400]);
  2132. });
  2133. });
  2134. ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => {
  2135. const testWindowsOverlay = async (style: any) => {
  2136. const w = new BrowserWindow({
  2137. show: false,
  2138. width: 400,
  2139. height: 400,
  2140. titleBarStyle: style,
  2141. webPreferences: {
  2142. nodeIntegration: true,
  2143. contextIsolation: false
  2144. },
  2145. titleBarOverlay: true
  2146. });
  2147. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2148. if (process.platform === 'darwin') {
  2149. await w.loadFile(overlayHTML);
  2150. } else {
  2151. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  2152. await w.loadFile(overlayHTML);
  2153. await overlayReady;
  2154. }
  2155. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2156. expect(overlayEnabled).to.be.true('overlayEnabled');
  2157. const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2158. expect(overlayRect.y).to.equal(0);
  2159. if (process.platform === 'darwin') {
  2160. expect(overlayRect.x).to.be.greaterThan(0);
  2161. } else {
  2162. expect(overlayRect.x).to.equal(0);
  2163. }
  2164. expect(overlayRect.width).to.be.greaterThan(0);
  2165. expect(overlayRect.height).to.be.greaterThan(0);
  2166. const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
  2167. expect(cssOverlayRect).to.deep.equal(overlayRect);
  2168. const geometryChange = emittedOnce(ipcMain, 'geometrychange');
  2169. w.setBounds({ width: 800 });
  2170. const [, newOverlayRect] = await geometryChange;
  2171. expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
  2172. };
  2173. afterEach(async () => {
  2174. await closeAllWindows();
  2175. ipcMain.removeAllListeners('geometrychange');
  2176. });
  2177. it('creates browser window with hidden title bar', () => {
  2178. const w = new BrowserWindow({
  2179. show: false,
  2180. width: 400,
  2181. height: 400,
  2182. titleBarStyle: 'hidden'
  2183. });
  2184. const contentSize = w.getContentSize();
  2185. expect(contentSize).to.deep.equal([400, 400]);
  2186. });
  2187. ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
  2188. const w = new BrowserWindow({
  2189. show: false,
  2190. width: 400,
  2191. height: 400,
  2192. titleBarStyle: 'hiddenInset'
  2193. });
  2194. const contentSize = w.getContentSize();
  2195. expect(contentSize).to.deep.equal([400, 400]);
  2196. });
  2197. it('sets Window Control Overlay with hidden title bar', async () => {
  2198. await testWindowsOverlay('hidden');
  2199. });
  2200. ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
  2201. await testWindowsOverlay('hiddenInset');
  2202. });
  2203. ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
  2204. let w: BrowserWindow;
  2205. beforeEach(() => {
  2206. w = new BrowserWindow({
  2207. show: false,
  2208. webPreferences: {
  2209. nodeIntegration: true,
  2210. contextIsolation: false
  2211. },
  2212. titleBarOverlay: {
  2213. color: '#0000f0',
  2214. symbolColor: '#ffffff'
  2215. },
  2216. titleBarStyle: 'hiddenInset'
  2217. });
  2218. });
  2219. afterEach(async () => {
  2220. await closeAllWindows();
  2221. });
  2222. it('does not crash changing minimizability ', () => {
  2223. expect(() => {
  2224. w.setMinimizable(false);
  2225. }).to.not.throw();
  2226. });
  2227. it('does not crash changing maximizability', () => {
  2228. expect(() => {
  2229. w.setMaximizable(false);
  2230. }).to.not.throw();
  2231. });
  2232. });
  2233. });
  2234. ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => {
  2235. const testWindowsOverlayHeight = async (size: any) => {
  2236. const w = new BrowserWindow({
  2237. show: false,
  2238. width: 400,
  2239. height: 400,
  2240. titleBarStyle: 'hidden',
  2241. webPreferences: {
  2242. nodeIntegration: true,
  2243. contextIsolation: false
  2244. },
  2245. titleBarOverlay: {
  2246. height: size
  2247. }
  2248. });
  2249. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2250. if (process.platform === 'darwin') {
  2251. await w.loadFile(overlayHTML);
  2252. } else {
  2253. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  2254. await w.loadFile(overlayHTML);
  2255. await overlayReady;
  2256. }
  2257. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2258. expect(overlayEnabled).to.be.true('overlayEnabled');
  2259. const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2260. if (!w.isMaximized()) {
  2261. const maximize = emittedOnce(w, 'maximize');
  2262. w.show();
  2263. w.maximize();
  2264. await maximize;
  2265. }
  2266. expect(w.isMaximized()).to.be.true('not maximized');
  2267. const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2268. expect(overlayRectPreMax.y).to.equal(0);
  2269. if (process.platform === 'darwin') {
  2270. expect(overlayRectPreMax.x).to.be.greaterThan(0);
  2271. } else {
  2272. expect(overlayRectPreMax.x).to.equal(0);
  2273. }
  2274. expect(overlayRectPreMax.width).to.be.greaterThan(0);
  2275. expect(overlayRectPreMax.height).to.equal(size);
  2276. // Confirm that maximization only affected the height of the buttons and not the title bar
  2277. expect(overlayRectPostMax.height).to.equal(size);
  2278. };
  2279. afterEach(async () => {
  2280. await closeAllWindows();
  2281. ipcMain.removeAllListeners('geometrychange');
  2282. });
  2283. it('sets Window Control Overlay with title bar height of 40', async () => {
  2284. await testWindowsOverlayHeight(40);
  2285. });
  2286. });
  2287. ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => {
  2288. afterEach(async () => {
  2289. await closeAllWindows();
  2290. ipcMain.removeAllListeners('geometrychange');
  2291. });
  2292. it('does not crash when an invalid titleBarStyle was initially set', () => {
  2293. const win = new BrowserWindow({
  2294. show: false,
  2295. webPreferences: {
  2296. nodeIntegration: true,
  2297. contextIsolation: false
  2298. },
  2299. titleBarOverlay: {
  2300. color: '#0000f0',
  2301. symbolColor: '#ffffff'
  2302. },
  2303. titleBarStyle: 'hiddenInset'
  2304. });
  2305. expect(() => {
  2306. win.setTitleBarOverlay({
  2307. color: '#000000'
  2308. });
  2309. }).to.not.throw();
  2310. });
  2311. it('correctly updates the height of the overlay', async () => {
  2312. const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => {
  2313. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  2314. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  2315. await w.loadFile(overlayHTML);
  2316. if (firstRun) {
  2317. await overlayReady;
  2318. }
  2319. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  2320. expect(overlayEnabled).to.be.true('overlayEnabled');
  2321. const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2322. if (!w.isMaximized()) {
  2323. const maximize = emittedOnce(w, 'maximize');
  2324. w.show();
  2325. w.maximize();
  2326. await maximize;
  2327. }
  2328. expect(w.isMaximized()).to.be.true('not maximized');
  2329. const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2330. expect(x).to.equal(0);
  2331. expect(y).to.equal(0);
  2332. expect(width).to.be.greaterThan(0);
  2333. expect(height).to.equal(size);
  2334. expect(preMaxHeight).to.equal(size);
  2335. };
  2336. const INITIAL_SIZE = 40;
  2337. const w = new BrowserWindow({
  2338. show: false,
  2339. width: 400,
  2340. height: 400,
  2341. titleBarStyle: 'hidden',
  2342. webPreferences: {
  2343. nodeIntegration: true,
  2344. contextIsolation: false
  2345. },
  2346. titleBarOverlay: {
  2347. height: INITIAL_SIZE
  2348. }
  2349. });
  2350. await testOverlay(w, INITIAL_SIZE, true);
  2351. w.setTitleBarOverlay({
  2352. height: INITIAL_SIZE + 10
  2353. });
  2354. await testOverlay(w, INITIAL_SIZE + 10, false);
  2355. });
  2356. });
  2357. ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
  2358. afterEach(closeAllWindows);
  2359. it('can move the window out of screen', () => {
  2360. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2361. w.setPosition(-10, 50);
  2362. const after = w.getPosition();
  2363. expect(after).to.deep.equal([-10, 50]);
  2364. });
  2365. it('cannot move the window behind menu bar', () => {
  2366. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2367. w.setPosition(-10, -10);
  2368. const after = w.getPosition();
  2369. expect(after[1]).to.be.at.least(0);
  2370. });
  2371. it('can move the window behind menu bar if it has no frame', () => {
  2372. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
  2373. w.setPosition(-10, -10);
  2374. const after = w.getPosition();
  2375. expect(after[0]).to.be.equal(-10);
  2376. expect(after[1]).to.be.equal(-10);
  2377. });
  2378. it('without it, cannot move the window out of screen', () => {
  2379. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2380. w.setPosition(-10, -10);
  2381. const after = w.getPosition();
  2382. expect(after[1]).to.be.at.least(0);
  2383. });
  2384. it('can set the window larger than screen', () => {
  2385. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2386. const size = screen.getPrimaryDisplay().size;
  2387. size.width += 100;
  2388. size.height += 100;
  2389. w.setSize(size.width, size.height);
  2390. expectBoundsEqual(w.getSize(), [size.width, size.height]);
  2391. });
  2392. it('without it, cannot set the window larger than screen', () => {
  2393. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2394. const size = screen.getPrimaryDisplay().size;
  2395. size.width += 100;
  2396. size.height += 100;
  2397. w.setSize(size.width, size.height);
  2398. expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
  2399. });
  2400. });
  2401. ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
  2402. afterEach(closeAllWindows);
  2403. it('sets the window width to the page width when used', () => {
  2404. const w = new BrowserWindow({
  2405. show: false,
  2406. width: 500,
  2407. height: 400,
  2408. zoomToPageWidth: true
  2409. });
  2410. w.maximize();
  2411. expect(w.getSize()[0]).to.equal(500);
  2412. });
  2413. });
  2414. describe('"tabbingIdentifier" option', () => {
  2415. afterEach(closeAllWindows);
  2416. it('can be set on a window', () => {
  2417. expect(() => {
  2418. /* eslint-disable no-new */
  2419. new BrowserWindow({
  2420. tabbingIdentifier: 'group1'
  2421. });
  2422. new BrowserWindow({
  2423. tabbingIdentifier: 'group2',
  2424. frame: false
  2425. });
  2426. /* eslint-enable no-new */
  2427. }).not.to.throw();
  2428. });
  2429. });
  2430. describe('"webPreferences" option', () => {
  2431. afterEach(() => { ipcMain.removeAllListeners('answer'); });
  2432. afterEach(closeAllWindows);
  2433. describe('"preload" option', () => {
  2434. const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
  2435. it(name, async () => {
  2436. const w = new BrowserWindow({
  2437. webPreferences: {
  2438. ...webPrefs,
  2439. preload: path.resolve(fixtures, 'module', 'empty.js')
  2440. },
  2441. show: false
  2442. });
  2443. w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
  2444. const [, result] = await emittedOnce(ipcMain, 'leak-result');
  2445. expect(result).to.have.property('require', 'undefined');
  2446. expect(result).to.have.property('exports', 'undefined');
  2447. expect(result).to.have.property('windowExports', 'undefined');
  2448. expect(result).to.have.property('windowPreload', 'undefined');
  2449. expect(result).to.have.property('windowRequire', 'undefined');
  2450. });
  2451. };
  2452. doesNotLeakSpec('does not leak require', {
  2453. nodeIntegration: false,
  2454. sandbox: false,
  2455. contextIsolation: false
  2456. });
  2457. doesNotLeakSpec('does not leak require when sandbox is enabled', {
  2458. nodeIntegration: false,
  2459. sandbox: true,
  2460. contextIsolation: false
  2461. });
  2462. doesNotLeakSpec('does not leak require when context isolation is enabled', {
  2463. nodeIntegration: false,
  2464. sandbox: false,
  2465. contextIsolation: true
  2466. });
  2467. doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
  2468. nodeIntegration: false,
  2469. sandbox: true,
  2470. contextIsolation: true
  2471. });
  2472. it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
  2473. let w = new BrowserWindow({
  2474. webPreferences: {
  2475. contextIsolation: false,
  2476. nodeIntegration: false,
  2477. preload: path.resolve(fixtures, 'module', 'empty.js')
  2478. },
  2479. show: false
  2480. });
  2481. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2482. const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result');
  2483. expect(notIsolated).to.have.property('globals');
  2484. w.destroy();
  2485. w = new BrowserWindow({
  2486. webPreferences: {
  2487. contextIsolation: true,
  2488. nodeIntegration: false,
  2489. preload: path.resolve(fixtures, 'module', 'empty.js')
  2490. },
  2491. show: false
  2492. });
  2493. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2494. const [, isolated] = await emittedOnce(ipcMain, 'leak-result');
  2495. expect(isolated).to.have.property('globals');
  2496. const notIsolatedGlobals = new Set(notIsolated.globals);
  2497. for (const isolatedGlobal of isolated.globals) {
  2498. notIsolatedGlobals.delete(isolatedGlobal);
  2499. }
  2500. expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals');
  2501. });
  2502. it('loads the script before other scripts in window', async () => {
  2503. const preload = path.join(fixtures, 'module', 'set-global.js');
  2504. const w = new BrowserWindow({
  2505. show: false,
  2506. webPreferences: {
  2507. nodeIntegration: true,
  2508. contextIsolation: false,
  2509. preload
  2510. }
  2511. });
  2512. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2513. const [, test] = await emittedOnce(ipcMain, 'answer');
  2514. expect(test).to.eql('preload');
  2515. });
  2516. it('has synchronous access to all eventual window APIs', async () => {
  2517. const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
  2518. const w = new BrowserWindow({
  2519. show: false,
  2520. webPreferences: {
  2521. nodeIntegration: true,
  2522. contextIsolation: false,
  2523. preload
  2524. }
  2525. });
  2526. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2527. const [, test] = await emittedOnce(ipcMain, 'answer');
  2528. expect(test).to.be.an('object');
  2529. expect(test.atPreload).to.be.an('array');
  2530. expect(test.atLoad).to.be.an('array');
  2531. expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
  2532. });
  2533. });
  2534. describe('session preload scripts', function () {
  2535. const preloads = [
  2536. path.join(fixtures, 'module', 'set-global-preload-1.js'),
  2537. path.join(fixtures, 'module', 'set-global-preload-2.js'),
  2538. path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
  2539. ];
  2540. const defaultSession = session.defaultSession;
  2541. beforeEach(() => {
  2542. expect(defaultSession.getPreloads()).to.deep.equal([]);
  2543. defaultSession.setPreloads(preloads);
  2544. });
  2545. afterEach(() => {
  2546. defaultSession.setPreloads([]);
  2547. });
  2548. it('can set multiple session preload script', () => {
  2549. expect(defaultSession.getPreloads()).to.deep.equal(preloads);
  2550. });
  2551. const generateSpecs = (description: string, sandbox: boolean) => {
  2552. describe(description, () => {
  2553. it('loads the script before other scripts in window including normal preloads', async () => {
  2554. const w = new BrowserWindow({
  2555. show: false,
  2556. webPreferences: {
  2557. sandbox,
  2558. preload: path.join(fixtures, 'module', 'get-global-preload.js'),
  2559. contextIsolation: false
  2560. }
  2561. });
  2562. w.loadURL('about:blank');
  2563. const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars');
  2564. expect(preload1).to.equal('preload-1');
  2565. expect(preload2).to.equal('preload-1-2');
  2566. expect(preload3).to.be.undefined('preload 3');
  2567. });
  2568. });
  2569. };
  2570. generateSpecs('without sandbox', false);
  2571. generateSpecs('with sandbox', true);
  2572. });
  2573. describe('"additionalArguments" option', () => {
  2574. it('adds extra args to process.argv in the renderer process', async () => {
  2575. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  2576. const w = new BrowserWindow({
  2577. show: false,
  2578. webPreferences: {
  2579. nodeIntegration: true,
  2580. preload,
  2581. additionalArguments: ['--my-magic-arg']
  2582. }
  2583. });
  2584. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2585. const [, argv] = await emittedOnce(ipcMain, 'answer');
  2586. expect(argv).to.include('--my-magic-arg');
  2587. });
  2588. it('adds extra value args to process.argv in the renderer process', async () => {
  2589. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  2590. const w = new BrowserWindow({
  2591. show: false,
  2592. webPreferences: {
  2593. nodeIntegration: true,
  2594. preload,
  2595. additionalArguments: ['--my-magic-arg=foo']
  2596. }
  2597. });
  2598. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2599. const [, argv] = await emittedOnce(ipcMain, 'answer');
  2600. expect(argv).to.include('--my-magic-arg=foo');
  2601. });
  2602. });
  2603. describe('"node-integration" option', () => {
  2604. it('disables node integration by default', async () => {
  2605. const preload = path.join(fixtures, 'module', 'send-later.js');
  2606. const w = new BrowserWindow({
  2607. show: false,
  2608. webPreferences: {
  2609. preload,
  2610. contextIsolation: false
  2611. }
  2612. });
  2613. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2614. const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer');
  2615. expect(typeofProcess).to.equal('undefined');
  2616. expect(typeofBuffer).to.equal('undefined');
  2617. });
  2618. });
  2619. describe('"sandbox" option', () => {
  2620. const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
  2621. let server: http.Server = null as unknown as http.Server;
  2622. let serverUrl: string = null as unknown as string;
  2623. before((done) => {
  2624. server = http.createServer((request, response) => {
  2625. switch (request.url) {
  2626. case '/cross-site':
  2627. response.end(`<html><body><h1>${request.url}</h1></body></html>`);
  2628. break;
  2629. default:
  2630. throw new Error(`unsupported endpoint: ${request.url}`);
  2631. }
  2632. }).listen(0, '127.0.0.1', () => {
  2633. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  2634. done();
  2635. });
  2636. });
  2637. after(() => {
  2638. server.close();
  2639. });
  2640. it('exposes ipcRenderer to preload script', async () => {
  2641. const w = new BrowserWindow({
  2642. show: false,
  2643. webPreferences: {
  2644. sandbox: true,
  2645. preload,
  2646. contextIsolation: false
  2647. }
  2648. });
  2649. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2650. const [, test] = await emittedOnce(ipcMain, 'answer');
  2651. expect(test).to.equal('preload');
  2652. });
  2653. it('exposes ipcRenderer to preload script (path has special chars)', async () => {
  2654. const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
  2655. const w = new BrowserWindow({
  2656. show: false,
  2657. webPreferences: {
  2658. sandbox: true,
  2659. preload: preloadSpecialChars,
  2660. contextIsolation: false
  2661. }
  2662. });
  2663. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2664. const [, test] = await emittedOnce(ipcMain, 'answer');
  2665. expect(test).to.equal('preload');
  2666. });
  2667. it('exposes "loaded" event to preload script', async () => {
  2668. const w = new BrowserWindow({
  2669. show: false,
  2670. webPreferences: {
  2671. sandbox: true,
  2672. preload
  2673. }
  2674. });
  2675. w.loadURL('about:blank');
  2676. await emittedOnce(ipcMain, 'process-loaded');
  2677. });
  2678. it('exposes "exit" event to preload script', async () => {
  2679. const w = new BrowserWindow({
  2680. show: false,
  2681. webPreferences: {
  2682. sandbox: true,
  2683. preload,
  2684. contextIsolation: false
  2685. }
  2686. });
  2687. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
  2688. const pageUrl = 'file://' + htmlPath;
  2689. w.loadURL(pageUrl);
  2690. const [, url] = await emittedOnce(ipcMain, 'answer');
  2691. const expectedUrl = process.platform === 'win32'
  2692. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2693. : pageUrl;
  2694. expect(url).to.equal(expectedUrl);
  2695. });
  2696. it('exposes full EventEmitter object to preload script', async () => {
  2697. const w = new BrowserWindow({
  2698. show: false,
  2699. webPreferences: {
  2700. sandbox: true,
  2701. preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
  2702. }
  2703. });
  2704. w.loadURL('about:blank');
  2705. const [, rendererEventEmitterProperties] = await emittedOnce(ipcMain, 'answer');
  2706. const { EventEmitter } = require('events');
  2707. const emitter = new EventEmitter();
  2708. const browserEventEmitterProperties = [];
  2709. let currentObj = emitter;
  2710. do {
  2711. browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
  2712. } while ((currentObj = Object.getPrototypeOf(currentObj)));
  2713. expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
  2714. });
  2715. it('should open windows in same domain with cross-scripting enabled', async () => {
  2716. const w = new BrowserWindow({
  2717. show: true,
  2718. webPreferences: {
  2719. sandbox: true,
  2720. preload,
  2721. contextIsolation: false
  2722. }
  2723. });
  2724. w.webContents.setWindowOpenHandler(() => ({
  2725. action: 'allow',
  2726. overrideBrowserWindowOptions: {
  2727. webPreferences: {
  2728. preload
  2729. }
  2730. }
  2731. }));
  2732. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
  2733. const pageUrl = 'file://' + htmlPath;
  2734. const answer = emittedOnce(ipcMain, 'answer');
  2735. w.loadURL(pageUrl);
  2736. const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window');
  2737. const expectedUrl = process.platform === 'win32'
  2738. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2739. : pageUrl;
  2740. expect(url).to.equal(expectedUrl);
  2741. expect(frameName).to.equal('popup!');
  2742. expect(options.width).to.equal(500);
  2743. expect(options.height).to.equal(600);
  2744. const [, html] = await answer;
  2745. expect(html).to.equal('<h1>scripting from opener</h1>');
  2746. });
  2747. it('should open windows in another domain with cross-scripting disabled', async () => {
  2748. const w = new BrowserWindow({
  2749. show: true,
  2750. webPreferences: {
  2751. sandbox: true,
  2752. preload,
  2753. contextIsolation: false
  2754. }
  2755. });
  2756. w.webContents.setWindowOpenHandler(() => ({
  2757. action: 'allow',
  2758. overrideBrowserWindowOptions: {
  2759. webPreferences: {
  2760. preload
  2761. }
  2762. }
  2763. }));
  2764. w.loadFile(
  2765. path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
  2766. { search: 'window-open-external' }
  2767. );
  2768. // Wait for a message from the main window saying that it's ready.
  2769. await emittedOnce(ipcMain, 'opener-loaded');
  2770. // Ask the opener to open a popup with window.opener.
  2771. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
  2772. w.webContents.send('open-the-popup', expectedPopupUrl);
  2773. // The page is going to open a popup that it won't be able to close.
  2774. // We have to close it from here later.
  2775. const [, popupWindow] = await emittedOnce(app, 'browser-window-created');
  2776. // Ask the popup window for details.
  2777. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded');
  2778. popupWindow.webContents.send('provide-details');
  2779. const [, openerIsNull, , locationHref] = await detailsAnswer;
  2780. expect(openerIsNull).to.be.false('window.opener is null');
  2781. expect(locationHref).to.equal(expectedPopupUrl);
  2782. // Ask the page to access the popup.
  2783. const touchPopupResult = emittedOnce(ipcMain, 'answer');
  2784. w.webContents.send('touch-the-popup');
  2785. const [, popupAccessMessage] = await touchPopupResult;
  2786. // Ask the popup to access the opener.
  2787. const touchOpenerResult = emittedOnce(ipcMain, 'answer');
  2788. popupWindow.webContents.send('touch-the-opener');
  2789. const [, openerAccessMessage] = await touchOpenerResult;
  2790. // We don't need the popup anymore, and its parent page can't close it,
  2791. // so let's close it from here before we run any checks.
  2792. await closeWindow(popupWindow, { assertNotWindows: false });
  2793. expect(popupAccessMessage).to.be.a('string',
  2794. 'child\'s .document is accessible from its parent window');
  2795. expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
  2796. expect(openerAccessMessage).to.be.a('string',
  2797. 'opener .document is accessible from a popup window');
  2798. expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
  2799. });
  2800. it('should inherit the sandbox setting in opened windows', async () => {
  2801. const w = new BrowserWindow({
  2802. show: false,
  2803. webPreferences: {
  2804. sandbox: true
  2805. }
  2806. });
  2807. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  2808. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
  2809. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2810. const [, { argv }] = await emittedOnce(ipcMain, 'answer');
  2811. expect(argv).to.include('--enable-sandbox');
  2812. });
  2813. it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
  2814. const w = new BrowserWindow({
  2815. show: false,
  2816. webPreferences: {
  2817. sandbox: true
  2818. }
  2819. });
  2820. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  2821. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
  2822. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2823. const [[, childWebContents]] = await Promise.all([
  2824. emittedOnce(app, 'web-contents-created'),
  2825. emittedOnce(ipcMain, 'answer')
  2826. ]);
  2827. const webPreferences = childWebContents.getLastWebPreferences();
  2828. expect(webPreferences.contextIsolation).to.equal(false);
  2829. });
  2830. it('should set ipc event sender correctly', async () => {
  2831. const w = new BrowserWindow({
  2832. show: false,
  2833. webPreferences: {
  2834. sandbox: true,
  2835. preload,
  2836. contextIsolation: false
  2837. }
  2838. });
  2839. let childWc: WebContents | null = null;
  2840. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
  2841. w.webContents.on('did-create-window', (win) => {
  2842. childWc = win.webContents;
  2843. expect(w.webContents).to.not.equal(childWc);
  2844. });
  2845. ipcMain.once('parent-ready', function (event) {
  2846. expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
  2847. event.sender.send('verified');
  2848. });
  2849. ipcMain.once('child-ready', function (event) {
  2850. expect(childWc).to.not.be.null('child webcontents should be available');
  2851. expect(event.sender).to.equal(childWc, 'sender should be the child');
  2852. event.sender.send('verified');
  2853. });
  2854. const done = Promise.all([
  2855. 'parent-answer',
  2856. 'child-answer'
  2857. ].map(name => emittedOnce(ipcMain, name)));
  2858. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
  2859. await done;
  2860. });
  2861. describe('event handling', () => {
  2862. let w: BrowserWindow = null as unknown as BrowserWindow;
  2863. beforeEach(() => {
  2864. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  2865. });
  2866. it('works for window events', async () => {
  2867. const pageTitleUpdated = emittedOnce(w, 'page-title-updated');
  2868. w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
  2869. await pageTitleUpdated;
  2870. });
  2871. it('works for stop events', async () => {
  2872. const done = Promise.all([
  2873. 'did-navigate',
  2874. 'did-fail-load',
  2875. 'did-stop-loading'
  2876. ].map(name => emittedOnce(w.webContents, name)));
  2877. w.loadURL('data:text/html,<script>stop()</script>');
  2878. await done;
  2879. });
  2880. it('works for web contents events', async () => {
  2881. const done = Promise.all([
  2882. 'did-finish-load',
  2883. 'did-frame-finish-load',
  2884. 'did-navigate-in-page',
  2885. 'will-navigate',
  2886. 'did-start-loading',
  2887. 'did-stop-loading',
  2888. 'did-frame-finish-load',
  2889. 'dom-ready'
  2890. ].map(name => emittedOnce(w.webContents, name)));
  2891. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
  2892. await done;
  2893. });
  2894. });
  2895. it('validates process APIs access in sandboxed renderer', async () => {
  2896. const w = new BrowserWindow({
  2897. show: false,
  2898. webPreferences: {
  2899. sandbox: true,
  2900. preload,
  2901. contextIsolation: false
  2902. }
  2903. });
  2904. w.webContents.once('preload-error', (event, preloadPath, error) => {
  2905. throw error;
  2906. });
  2907. process.env.sandboxmain = 'foo';
  2908. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2909. const [, test] = await emittedOnce(ipcMain, 'answer');
  2910. expect(test.hasCrash).to.be.true('has crash');
  2911. expect(test.hasHang).to.be.true('has hang');
  2912. expect(test.heapStatistics).to.be.an('object');
  2913. expect(test.blinkMemoryInfo).to.be.an('object');
  2914. expect(test.processMemoryInfo).to.be.an('object');
  2915. expect(test.systemVersion).to.be.a('string');
  2916. expect(test.cpuUsage).to.be.an('object');
  2917. expect(test.ioCounters).to.be.an('object');
  2918. expect(test.uptime).to.be.a('number');
  2919. expect(test.arch).to.equal(process.arch);
  2920. expect(test.platform).to.equal(process.platform);
  2921. expect(test.env).to.deep.equal(process.env);
  2922. expect(test.execPath).to.equal(process.helperExecPath);
  2923. expect(test.sandboxed).to.be.true('sandboxed');
  2924. expect(test.contextIsolated).to.be.false('contextIsolated');
  2925. expect(test.type).to.equal('renderer');
  2926. expect(test.version).to.equal(process.version);
  2927. expect(test.versions).to.deep.equal(process.versions);
  2928. expect(test.contextId).to.be.a('string');
  2929. if (process.platform === 'linux' && test.osSandbox) {
  2930. expect(test.creationTime).to.be.null('creation time');
  2931. expect(test.systemMemoryInfo).to.be.null('system memory info');
  2932. } else {
  2933. expect(test.creationTime).to.be.a('number');
  2934. expect(test.systemMemoryInfo).to.be.an('object');
  2935. }
  2936. });
  2937. it('webview in sandbox renderer', async () => {
  2938. const w = new BrowserWindow({
  2939. show: false,
  2940. webPreferences: {
  2941. sandbox: true,
  2942. preload,
  2943. webviewTag: true,
  2944. contextIsolation: false
  2945. }
  2946. });
  2947. const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
  2948. const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready');
  2949. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  2950. const [, webContents] = await didAttachWebview;
  2951. const [, id] = await webviewDomReady;
  2952. expect(webContents.id).to.equal(id);
  2953. });
  2954. });
  2955. describe('child windows', () => {
  2956. let w: BrowserWindow = null as unknown as BrowserWindow;
  2957. beforeEach(() => {
  2958. w = new BrowserWindow({
  2959. show: false,
  2960. webPreferences: {
  2961. nodeIntegration: true,
  2962. // tests relies on preloads in opened windows
  2963. nodeIntegrationInSubFrames: true,
  2964. contextIsolation: false
  2965. }
  2966. });
  2967. });
  2968. it('opens window of about:blank with cross-scripting enabled', async () => {
  2969. const answer = emittedOnce(ipcMain, 'answer');
  2970. w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
  2971. const [, content] = await answer;
  2972. expect(content).to.equal('Hello');
  2973. });
  2974. it('opens window of same domain with cross-scripting enabled', async () => {
  2975. const answer = emittedOnce(ipcMain, 'answer');
  2976. w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
  2977. const [, content] = await answer;
  2978. expect(content).to.equal('Hello');
  2979. });
  2980. it('blocks accessing cross-origin frames', async () => {
  2981. const answer = emittedOnce(ipcMain, 'answer');
  2982. w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
  2983. const [, content] = await answer;
  2984. expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
  2985. });
  2986. it('opens window from <iframe> tags', async () => {
  2987. const answer = emittedOnce(ipcMain, 'answer');
  2988. w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
  2989. const [, content] = await answer;
  2990. expect(content).to.equal('Hello');
  2991. });
  2992. it('opens window with cross-scripting enabled from isolated context', async () => {
  2993. const w = new BrowserWindow({
  2994. show: false,
  2995. webPreferences: {
  2996. preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
  2997. }
  2998. });
  2999. w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
  3000. const [, content] = await emittedOnce(ipcMain, 'answer');
  3001. expect(content).to.equal('Hello');
  3002. });
  3003. ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
  3004. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
  3005. {
  3006. const [, content] = await emittedOnce(ipcMain, 'answer');
  3007. expect(content).to.equal('function');
  3008. }
  3009. w.reload();
  3010. {
  3011. const [, content] = await emittedOnce(ipcMain, 'answer');
  3012. expect(content).to.equal('function');
  3013. }
  3014. });
  3015. it('<webview> works in a scriptable popup', async () => {
  3016. const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
  3017. const w = new BrowserWindow({
  3018. show: false,
  3019. webPreferences: {
  3020. nodeIntegrationInSubFrames: true,
  3021. webviewTag: true,
  3022. contextIsolation: false,
  3023. preload
  3024. }
  3025. });
  3026. w.webContents.setWindowOpenHandler(() => ({
  3027. action: 'allow',
  3028. overrideBrowserWindowOptions: {
  3029. show: false,
  3030. webPreferences: {
  3031. contextIsolation: false,
  3032. webviewTag: true,
  3033. nodeIntegrationInSubFrames: true,
  3034. preload
  3035. }
  3036. }
  3037. }));
  3038. const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded');
  3039. w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
  3040. await webviewLoaded;
  3041. });
  3042. it('should open windows with the options configured via setWindowOpenHandler handlers', async () => {
  3043. const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js');
  3044. w.webContents.setWindowOpenHandler(() => ({
  3045. action: 'allow',
  3046. overrideBrowserWindowOptions: {
  3047. webPreferences: {
  3048. preload: preloadPath,
  3049. contextIsolation: false
  3050. }
  3051. }
  3052. }));
  3053. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  3054. const [[, childWebContents]] = await Promise.all([
  3055. emittedOnce(app, 'web-contents-created'),
  3056. emittedOnce(ipcMain, 'answer')
  3057. ]);
  3058. const webPreferences = childWebContents.getLastWebPreferences();
  3059. expect(webPreferences.contextIsolation).to.equal(false);
  3060. });
  3061. describe('window.location', () => {
  3062. const protocols = [
  3063. ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
  3064. ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
  3065. ];
  3066. beforeEach(() => {
  3067. for (const [scheme, path] of protocols) {
  3068. protocol.registerBufferProtocol(scheme, (request, callback) => {
  3069. callback({
  3070. mimeType: 'text/html',
  3071. data: fs.readFileSync(path)
  3072. });
  3073. });
  3074. }
  3075. });
  3076. afterEach(() => {
  3077. for (const [scheme] of protocols) {
  3078. protocol.unregisterProtocol(scheme);
  3079. }
  3080. });
  3081. it('retains the original web preferences when window.location is changed to a new origin', async () => {
  3082. const w = new BrowserWindow({
  3083. show: false,
  3084. webPreferences: {
  3085. // test relies on preloads in opened window
  3086. nodeIntegrationInSubFrames: true,
  3087. contextIsolation: false
  3088. }
  3089. });
  3090. w.webContents.setWindowOpenHandler(() => ({
  3091. action: 'allow',
  3092. overrideBrowserWindowOptions: {
  3093. webPreferences: {
  3094. preload: path.join(mainFixtures, 'api', 'window-open-preload.js'),
  3095. contextIsolation: false,
  3096. nodeIntegrationInSubFrames: true
  3097. }
  3098. }
  3099. }));
  3100. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  3101. const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer');
  3102. expect(nodeIntegration).to.be.false();
  3103. expect(typeofProcess).to.eql('undefined');
  3104. });
  3105. it('window.opener is not null when window.location is changed to a new origin', async () => {
  3106. const w = new BrowserWindow({
  3107. show: false,
  3108. webPreferences: {
  3109. // test relies on preloads in opened window
  3110. nodeIntegrationInSubFrames: true
  3111. }
  3112. });
  3113. w.webContents.setWindowOpenHandler(() => ({
  3114. action: 'allow',
  3115. overrideBrowserWindowOptions: {
  3116. webPreferences: {
  3117. preload: path.join(mainFixtures, 'api', 'window-open-preload.js')
  3118. }
  3119. }
  3120. }));
  3121. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  3122. const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer');
  3123. expect(windowOpenerIsNull).to.be.false('window.opener is null');
  3124. });
  3125. });
  3126. });
  3127. describe('"disableHtmlFullscreenWindowResize" option', () => {
  3128. it('prevents window from resizing when set', async () => {
  3129. const w = new BrowserWindow({
  3130. show: false,
  3131. webPreferences: {
  3132. disableHtmlFullscreenWindowResize: true
  3133. }
  3134. });
  3135. await w.loadURL('about:blank');
  3136. const size = w.getSize();
  3137. const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen');
  3138. w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  3139. await enterHtmlFullScreen;
  3140. expect(w.getSize()).to.deep.equal(size);
  3141. });
  3142. });
  3143. describe('"defaultFontFamily" option', () => {
  3144. it('can change the standard font family', async () => {
  3145. const w = new BrowserWindow({
  3146. show: false,
  3147. webPreferences: {
  3148. defaultFontFamily: {
  3149. standard: 'Impact'
  3150. }
  3151. }
  3152. });
  3153. await w.loadFile(path.join(fixtures, 'pages', 'content.html'));
  3154. const fontFamily = await w.webContents.executeJavaScript("window.getComputedStyle(document.getElementsByTagName('p')[0])['font-family']", true);
  3155. expect(fontFamily).to.equal('Impact');
  3156. });
  3157. });
  3158. });
  3159. describe('beforeunload handler', function () {
  3160. let w: BrowserWindow = null as unknown as BrowserWindow;
  3161. beforeEach(() => {
  3162. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  3163. });
  3164. afterEach(closeAllWindows);
  3165. it('returning undefined would not prevent close', async () => {
  3166. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  3167. const wait = emittedOnce(w, 'closed');
  3168. w.close();
  3169. await wait;
  3170. });
  3171. it('returning false would prevent close', async () => {
  3172. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  3173. w.close();
  3174. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  3175. expect(proceed).to.equal(false);
  3176. });
  3177. it('returning empty string would prevent close', async () => {
  3178. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
  3179. w.close();
  3180. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  3181. expect(proceed).to.equal(false);
  3182. });
  3183. it('emits for each close attempt', async () => {
  3184. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3185. const destroyListener = () => { expect.fail('Close was not prevented'); };
  3186. w.webContents.once('destroyed', destroyListener);
  3187. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3188. // The renderer needs to report the status of beforeunload handler
  3189. // back to main process, so wait for next console message, which means
  3190. // the SuddenTerminationStatus message have been flushed.
  3191. await emittedOnce(w.webContents, 'console-message');
  3192. w.close();
  3193. await emittedOnce(w.webContents, 'before-unload-fired');
  3194. w.close();
  3195. await emittedOnce(w.webContents, 'before-unload-fired');
  3196. w.webContents.removeListener('destroyed', destroyListener);
  3197. const wait = emittedOnce(w, 'closed');
  3198. w.close();
  3199. await wait;
  3200. });
  3201. it('emits for each reload attempt', async () => {
  3202. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3203. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  3204. w.webContents.once('did-start-navigation', navigationListener);
  3205. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3206. // The renderer needs to report the status of beforeunload handler
  3207. // back to main process, so wait for next console message, which means
  3208. // the SuddenTerminationStatus message have been flushed.
  3209. await emittedOnce(w.webContents, 'console-message');
  3210. w.reload();
  3211. // Chromium does not emit 'before-unload-fired' on WebContents for
  3212. // navigations, so we have to use other ways to know if beforeunload
  3213. // is fired.
  3214. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3215. w.reload();
  3216. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3217. w.webContents.removeListener('did-start-navigation', navigationListener);
  3218. w.reload();
  3219. await emittedOnce(w.webContents, 'did-finish-load');
  3220. });
  3221. it('emits for each navigation attempt', async () => {
  3222. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  3223. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  3224. w.webContents.once('did-start-navigation', navigationListener);
  3225. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  3226. // The renderer needs to report the status of beforeunload handler
  3227. // back to main process, so wait for next console message, which means
  3228. // the SuddenTerminationStatus message have been flushed.
  3229. await emittedOnce(w.webContents, 'console-message');
  3230. w.loadURL('about:blank');
  3231. // Chromium does not emit 'before-unload-fired' on WebContents for
  3232. // navigations, so we have to use other ways to know if beforeunload
  3233. // is fired.
  3234. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3235. w.loadURL('about:blank');
  3236. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  3237. w.webContents.removeListener('did-start-navigation', navigationListener);
  3238. await w.loadURL('about:blank');
  3239. });
  3240. });
  3241. describe('document.visibilityState/hidden', () => {
  3242. afterEach(closeAllWindows);
  3243. it('visibilityState is initially visible despite window being hidden', async () => {
  3244. const w = new BrowserWindow({
  3245. show: false,
  3246. width: 100,
  3247. height: 100,
  3248. webPreferences: {
  3249. nodeIntegration: true,
  3250. contextIsolation: false
  3251. }
  3252. });
  3253. let readyToShow = false;
  3254. w.once('ready-to-show', () => {
  3255. readyToShow = true;
  3256. });
  3257. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3258. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3259. expect(readyToShow).to.be.false('ready to show');
  3260. expect(visibilityState).to.equal('visible');
  3261. expect(hidden).to.be.false('hidden');
  3262. });
  3263. // TODO(nornagon): figure out why this is failing on windows
  3264. ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
  3265. const w = new BrowserWindow({
  3266. width: 100,
  3267. height: 100,
  3268. webPreferences: {
  3269. nodeIntegration: true,
  3270. contextIsolation: false
  3271. }
  3272. });
  3273. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3274. {
  3275. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3276. expect(visibilityState).to.equal('visible');
  3277. expect(hidden).to.be.false('hidden');
  3278. }
  3279. w.hide();
  3280. {
  3281. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3282. expect(visibilityState).to.equal('hidden');
  3283. expect(hidden).to.be.true('hidden');
  3284. }
  3285. });
  3286. // TODO(nornagon): figure out why this is failing on windows
  3287. ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
  3288. const w = new BrowserWindow({
  3289. width: 100,
  3290. height: 100,
  3291. webPreferences: {
  3292. nodeIntegration: true,
  3293. contextIsolation: false
  3294. }
  3295. });
  3296. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3297. if (process.platform === 'darwin') {
  3298. // See https://github.com/electron/electron/issues/8664
  3299. await emittedOnce(w, 'show');
  3300. }
  3301. w.hide();
  3302. w.show();
  3303. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  3304. expect(visibilityState).to.equal('visible');
  3305. });
  3306. ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
  3307. const w = new BrowserWindow({
  3308. width: 100,
  3309. height: 100,
  3310. webPreferences: {
  3311. nodeIntegration: true,
  3312. contextIsolation: false
  3313. }
  3314. });
  3315. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3316. if (process.platform === 'darwin') {
  3317. // See https://github.com/electron/electron/issues/8664
  3318. await emittedOnce(w, 'show');
  3319. }
  3320. w.hide();
  3321. w.showInactive();
  3322. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  3323. expect(visibilityState).to.equal('visible');
  3324. });
  3325. // TODO(nornagon): figure out why this is failing on windows
  3326. ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
  3327. const w = new BrowserWindow({
  3328. width: 100,
  3329. height: 100,
  3330. webPreferences: {
  3331. nodeIntegration: true,
  3332. contextIsolation: false
  3333. }
  3334. });
  3335. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3336. {
  3337. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3338. expect(visibilityState).to.equal('visible');
  3339. expect(hidden).to.be.false('hidden');
  3340. }
  3341. w.minimize();
  3342. {
  3343. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3344. expect(visibilityState).to.equal('hidden');
  3345. expect(hidden).to.be.true('hidden');
  3346. }
  3347. });
  3348. // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
  3349. // when we introduced the compositor recycling patch. Should figure out how to fix this
  3350. it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => {
  3351. const w = new BrowserWindow({
  3352. show: false,
  3353. width: 100,
  3354. height: 100,
  3355. webPreferences: {
  3356. backgroundThrottling: false,
  3357. nodeIntegration: true
  3358. }
  3359. });
  3360. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3361. {
  3362. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3363. expect(visibilityState).to.equal('visible');
  3364. expect(hidden).to.be.false('hidden');
  3365. }
  3366. ipcMain.once('pong', (event, visibilityState, hidden) => {
  3367. throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
  3368. });
  3369. try {
  3370. const shown1 = emittedOnce(w, 'show');
  3371. w.show();
  3372. await shown1;
  3373. const hidden = emittedOnce(w, 'hide');
  3374. w.hide();
  3375. await hidden;
  3376. const shown2 = emittedOnce(w, 'show');
  3377. w.show();
  3378. await shown2;
  3379. } finally {
  3380. ipcMain.removeAllListeners('pong');
  3381. }
  3382. });
  3383. });
  3384. ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
  3385. afterEach(closeAllWindows);
  3386. it('emits an event when window is maximized', async () => {
  3387. const w = new BrowserWindow({ show: false });
  3388. const maximize = emittedOnce(w, 'maximize');
  3389. w.show();
  3390. w.maximize();
  3391. await maximize;
  3392. });
  3393. it('emits an event when a transparent window is maximized', async () => {
  3394. const w = new BrowserWindow({
  3395. show: false,
  3396. frame: false,
  3397. transparent: true
  3398. });
  3399. const maximize = emittedOnce(w, 'maximize');
  3400. w.show();
  3401. w.maximize();
  3402. await maximize;
  3403. });
  3404. it('emits only one event when frameless window is maximized', () => {
  3405. const w = new BrowserWindow({ show: false, frame: false });
  3406. let emitted = 0;
  3407. w.on('maximize', () => emitted++);
  3408. w.show();
  3409. w.maximize();
  3410. expect(emitted).to.equal(1);
  3411. });
  3412. it('emits an event when window is unmaximized', async () => {
  3413. const w = new BrowserWindow({ show: false });
  3414. const unmaximize = emittedOnce(w, 'unmaximize');
  3415. w.show();
  3416. w.maximize();
  3417. w.unmaximize();
  3418. await unmaximize;
  3419. });
  3420. it('emits an event when a transparent window is unmaximized', async () => {
  3421. const w = new BrowserWindow({
  3422. show: false,
  3423. frame: false,
  3424. transparent: true
  3425. });
  3426. const maximize = emittedOnce(w, 'maximize');
  3427. const unmaximize = emittedOnce(w, 'unmaximize');
  3428. w.show();
  3429. w.maximize();
  3430. await maximize;
  3431. w.unmaximize();
  3432. await unmaximize;
  3433. });
  3434. it('emits an event when window is minimized', async () => {
  3435. const w = new BrowserWindow({ show: false });
  3436. const minimize = emittedOnce(w, 'minimize');
  3437. w.show();
  3438. w.minimize();
  3439. await minimize;
  3440. });
  3441. });
  3442. describe('beginFrameSubscription method', () => {
  3443. it('does not crash when callback returns nothing', (done) => {
  3444. const w = new BrowserWindow({ show: false });
  3445. let called = false;
  3446. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3447. w.webContents.on('dom-ready', () => {
  3448. w.webContents.beginFrameSubscription(function () {
  3449. // This callback might be called twice.
  3450. if (called) return;
  3451. called = true;
  3452. // Pending endFrameSubscription to next tick can reliably reproduce
  3453. // a crash which happens when nothing is returned in the callback.
  3454. setTimeout(() => {
  3455. w.webContents.endFrameSubscription();
  3456. done();
  3457. });
  3458. });
  3459. });
  3460. });
  3461. it('subscribes to frame updates', (done) => {
  3462. const w = new BrowserWindow({ show: false });
  3463. let called = false;
  3464. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3465. w.webContents.on('dom-ready', () => {
  3466. w.webContents.beginFrameSubscription(function (data) {
  3467. // This callback might be called twice.
  3468. if (called) return;
  3469. called = true;
  3470. try {
  3471. expect(data.constructor.name).to.equal('NativeImage');
  3472. expect(data.isEmpty()).to.be.false('data is empty');
  3473. done();
  3474. } catch (e) {
  3475. done(e);
  3476. } finally {
  3477. w.webContents.endFrameSubscription();
  3478. }
  3479. });
  3480. });
  3481. });
  3482. it('subscribes to frame updates (only dirty rectangle)', (done) => {
  3483. const w = new BrowserWindow({ show: false });
  3484. let called = false;
  3485. let gotInitialFullSizeFrame = false;
  3486. const [contentWidth, contentHeight] = w.getContentSize();
  3487. w.webContents.on('did-finish-load', () => {
  3488. w.webContents.beginFrameSubscription(true, (image, rect) => {
  3489. if (image.isEmpty()) {
  3490. // Chromium sometimes sends a 0x0 frame at the beginning of the
  3491. // page load.
  3492. return;
  3493. }
  3494. if (rect.height === contentHeight && rect.width === contentWidth &&
  3495. !gotInitialFullSizeFrame) {
  3496. // The initial frame is full-size, but we're looking for a call
  3497. // with just the dirty-rect. The next frame should be a smaller
  3498. // rect.
  3499. gotInitialFullSizeFrame = true;
  3500. return;
  3501. }
  3502. // This callback might be called twice.
  3503. if (called) return;
  3504. // We asked for just the dirty rectangle, so we expect to receive a
  3505. // rect smaller than the full size.
  3506. // TODO(jeremy): this is failing on windows currently; investigate.
  3507. // assert(rect.width < contentWidth || rect.height < contentHeight)
  3508. called = true;
  3509. try {
  3510. const expectedSize = rect.width * rect.height * 4;
  3511. expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
  3512. done();
  3513. } catch (e) {
  3514. done(e);
  3515. } finally {
  3516. w.webContents.endFrameSubscription();
  3517. }
  3518. });
  3519. });
  3520. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3521. });
  3522. it('throws error when subscriber is not well defined', () => {
  3523. const w = new BrowserWindow({ show: false });
  3524. expect(() => {
  3525. w.webContents.beginFrameSubscription(true, true as any);
  3526. // TODO(zcbenz): gin is weak at guessing parameter types, we should
  3527. // upstream native_mate's implementation to gin.
  3528. }).to.throw('Error processing argument at index 1, conversion failure from ');
  3529. });
  3530. });
  3531. describe('savePage method', () => {
  3532. const savePageDir = path.join(fixtures, 'save_page');
  3533. const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
  3534. const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
  3535. const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
  3536. afterEach(() => {
  3537. closeAllWindows();
  3538. try {
  3539. fs.unlinkSync(savePageCssPath);
  3540. fs.unlinkSync(savePageJsPath);
  3541. fs.unlinkSync(savePageHtmlPath);
  3542. fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
  3543. fs.rmdirSync(savePageDir);
  3544. } catch {}
  3545. });
  3546. it('should throw when passing relative paths', async () => {
  3547. const w = new BrowserWindow({ show: false });
  3548. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3549. await expect(
  3550. w.webContents.savePage('save_page.html', 'HTMLComplete')
  3551. ).to.eventually.be.rejectedWith('Path must be absolute');
  3552. await expect(
  3553. w.webContents.savePage('save_page.html', 'HTMLOnly')
  3554. ).to.eventually.be.rejectedWith('Path must be absolute');
  3555. await expect(
  3556. w.webContents.savePage('save_page.html', 'MHTML')
  3557. ).to.eventually.be.rejectedWith('Path must be absolute');
  3558. });
  3559. it('should save page to disk with HTMLOnly', async () => {
  3560. const w = new BrowserWindow({ show: false });
  3561. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3562. await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
  3563. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3564. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  3565. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  3566. });
  3567. it('should save page to disk with MHTML', async () => {
  3568. const w = new BrowserWindow({ show: false });
  3569. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3570. await w.webContents.savePage(savePageHtmlPath, 'MHTML');
  3571. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3572. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  3573. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  3574. });
  3575. it('should save page to disk with HTMLComplete', async () => {
  3576. const w = new BrowserWindow({ show: false });
  3577. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3578. await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
  3579. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3580. expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
  3581. expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
  3582. });
  3583. });
  3584. describe('BrowserWindow options argument is optional', () => {
  3585. afterEach(closeAllWindows);
  3586. it('should create a window with default size (800x600)', () => {
  3587. const w = new BrowserWindow();
  3588. expect(w.getSize()).to.deep.equal([800, 600]);
  3589. });
  3590. });
  3591. describe('BrowserWindow.restore()', () => {
  3592. afterEach(closeAllWindows);
  3593. it('should restore the previous window size', () => {
  3594. const w = new BrowserWindow({
  3595. minWidth: 800,
  3596. width: 800
  3597. });
  3598. const initialSize = w.getSize();
  3599. w.minimize();
  3600. w.restore();
  3601. expectBoundsEqual(w.getSize(), initialSize);
  3602. });
  3603. it('does not crash when restoring hidden minimized window', () => {
  3604. const w = new BrowserWindow({});
  3605. w.minimize();
  3606. w.hide();
  3607. w.show();
  3608. });
  3609. // TODO(zcbenz):
  3610. // This test does not run on Linux CI. See:
  3611. // https://github.com/electron/electron/issues/28699
  3612. ifit(process.platform === 'linux' && !process.env.CI)('should bring a minimized maximized window back to maximized state', async () => {
  3613. const w = new BrowserWindow({});
  3614. const maximize = emittedOnce(w, 'maximize');
  3615. w.maximize();
  3616. await maximize;
  3617. const minimize = emittedOnce(w, 'minimize');
  3618. w.minimize();
  3619. await minimize;
  3620. expect(w.isMaximized()).to.equal(false);
  3621. const restore = emittedOnce(w, 'restore');
  3622. w.restore();
  3623. await restore;
  3624. expect(w.isMaximized()).to.equal(true);
  3625. });
  3626. });
  3627. // TODO(dsanders11): Enable once maximize event works on Linux again on CI
  3628. ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
  3629. afterEach(closeAllWindows);
  3630. it('should show the window if it is not currently shown', async () => {
  3631. const w = new BrowserWindow({ show: false });
  3632. const hidden = emittedOnce(w, 'hide');
  3633. let shown = emittedOnce(w, 'show');
  3634. const maximize = emittedOnce(w, 'maximize');
  3635. expect(w.isVisible()).to.be.false('visible');
  3636. w.maximize();
  3637. await maximize;
  3638. await shown;
  3639. expect(w.isMaximized()).to.be.true('maximized');
  3640. expect(w.isVisible()).to.be.true('visible');
  3641. // Even if the window is already maximized
  3642. w.hide();
  3643. await hidden;
  3644. expect(w.isVisible()).to.be.false('visible');
  3645. shown = emittedOnce(w, 'show');
  3646. w.maximize();
  3647. await shown;
  3648. expect(w.isVisible()).to.be.true('visible');
  3649. });
  3650. });
  3651. describe('BrowserWindow.unmaximize()', () => {
  3652. afterEach(closeAllWindows);
  3653. it('should restore the previous window position', () => {
  3654. const w = new BrowserWindow();
  3655. const initialPosition = w.getPosition();
  3656. w.maximize();
  3657. w.unmaximize();
  3658. expectBoundsEqual(w.getPosition(), initialPosition);
  3659. });
  3660. // TODO(dsanders11): Enable once minimize event works on Linux again.
  3661. // See https://github.com/electron/electron/issues/28699
  3662. ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
  3663. const w = new BrowserWindow();
  3664. const minimize = emittedOnce(w, 'minimize');
  3665. w.minimize();
  3666. await minimize;
  3667. w.unmaximize();
  3668. await delay(1000);
  3669. expect(w.isMinimized()).to.be.true();
  3670. });
  3671. it('should not change the size or position of a normal window', async () => {
  3672. const w = new BrowserWindow();
  3673. const initialSize = w.getSize();
  3674. const initialPosition = w.getPosition();
  3675. w.unmaximize();
  3676. await delay(1000);
  3677. expectBoundsEqual(w.getSize(), initialSize);
  3678. expectBoundsEqual(w.getPosition(), initialPosition);
  3679. });
  3680. ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
  3681. const { workArea } = screen.getPrimaryDisplay();
  3682. const bounds = {
  3683. x: workArea.x,
  3684. y: workArea.y,
  3685. width: workArea.width,
  3686. height: workArea.height
  3687. };
  3688. const w = new BrowserWindow(bounds);
  3689. w.unmaximize();
  3690. await delay(1000);
  3691. expectBoundsEqual(w.getBounds(), bounds);
  3692. });
  3693. });
  3694. describe('setFullScreen(false)', () => {
  3695. afterEach(closeAllWindows);
  3696. // only applicable to windows: https://github.com/electron/electron/issues/6036
  3697. ifdescribe(process.platform === 'win32')('on windows', () => {
  3698. it('should restore a normal visible window from a fullscreen startup state', async () => {
  3699. const w = new BrowserWindow({ show: false });
  3700. await w.loadURL('about:blank');
  3701. const shown = emittedOnce(w, 'show');
  3702. // start fullscreen and hidden
  3703. w.setFullScreen(true);
  3704. w.show();
  3705. await shown;
  3706. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3707. w.setFullScreen(false);
  3708. await leftFullScreen;
  3709. expect(w.isVisible()).to.be.true('visible');
  3710. expect(w.isFullScreen()).to.be.false('fullscreen');
  3711. });
  3712. it('should keep window hidden if already in hidden state', async () => {
  3713. const w = new BrowserWindow({ show: false });
  3714. await w.loadURL('about:blank');
  3715. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3716. w.setFullScreen(false);
  3717. await leftFullScreen;
  3718. expect(w.isVisible()).to.be.false('visible');
  3719. expect(w.isFullScreen()).to.be.false('fullscreen');
  3720. });
  3721. });
  3722. ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
  3723. it('exits HTML fullscreen when window leaves fullscreen', async () => {
  3724. const w = new BrowserWindow();
  3725. await w.loadURL('about:blank');
  3726. await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  3727. await emittedOnce(w, 'enter-full-screen');
  3728. // Wait a tick for the full-screen state to 'stick'
  3729. await delay();
  3730. w.setFullScreen(false);
  3731. await emittedOnce(w, 'leave-html-full-screen');
  3732. });
  3733. });
  3734. });
  3735. describe('parent window', () => {
  3736. afterEach(closeAllWindows);
  3737. ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
  3738. const w = new BrowserWindow();
  3739. const sheetBegin = emittedOnce(w, 'sheet-begin');
  3740. // eslint-disable-next-line no-new
  3741. new BrowserWindow({
  3742. modal: true,
  3743. parent: w
  3744. });
  3745. await sheetBegin;
  3746. });
  3747. ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
  3748. const w = new BrowserWindow();
  3749. const sheet = new BrowserWindow({
  3750. modal: true,
  3751. parent: w
  3752. });
  3753. const sheetEnd = emittedOnce(w, 'sheet-end');
  3754. sheet.close();
  3755. await sheetEnd;
  3756. });
  3757. describe('parent option', () => {
  3758. it('sets parent window', () => {
  3759. const w = new BrowserWindow({ show: false });
  3760. const c = new BrowserWindow({ show: false, parent: w });
  3761. expect(c.getParentWindow()).to.equal(w);
  3762. });
  3763. it('adds window to child windows of parent', () => {
  3764. const w = new BrowserWindow({ show: false });
  3765. const c = new BrowserWindow({ show: false, parent: w });
  3766. expect(w.getChildWindows()).to.deep.equal([c]);
  3767. });
  3768. it('removes from child windows of parent when window is closed', async () => {
  3769. const w = new BrowserWindow({ show: false });
  3770. const c = new BrowserWindow({ show: false, parent: w });
  3771. const closed = emittedOnce(c, 'closed');
  3772. c.close();
  3773. await closed;
  3774. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3775. await delay();
  3776. expect(w.getChildWindows().length).to.equal(0);
  3777. });
  3778. ifit(process.platform === 'darwin')('child window matches visibility when visibility changes', async () => {
  3779. const w = new BrowserWindow({ show: false });
  3780. const c = new BrowserWindow({ show: false, parent: w });
  3781. const wShow = emittedOnce(w, 'show');
  3782. const cShow = emittedOnce(c, 'show');
  3783. w.show();
  3784. c.show();
  3785. await Promise.all([wShow, cShow]);
  3786. const minimized = emittedOnce(w, 'minimize');
  3787. w.minimize();
  3788. await minimized;
  3789. expect(w.isVisible()).to.be.false('parent is visible');
  3790. expect(c.isVisible()).to.be.false('child is visible');
  3791. const restored = emittedOnce(w, 'restore');
  3792. w.restore();
  3793. await restored;
  3794. expect(w.isVisible()).to.be.true('parent is visible');
  3795. expect(c.isVisible()).to.be.true('child is visible');
  3796. });
  3797. ifit(process.platform === 'darwin')('matches child window visibility when visibility changes', async () => {
  3798. const w = new BrowserWindow({ show: false });
  3799. const c = new BrowserWindow({ show: false, parent: w });
  3800. const wShow = emittedOnce(w, 'show');
  3801. const cShow = emittedOnce(c, 'show');
  3802. w.show();
  3803. c.show();
  3804. await Promise.all([wShow, cShow]);
  3805. const minimized = emittedOnce(c, 'minimize');
  3806. c.minimize();
  3807. await minimized;
  3808. expect(c.isVisible()).to.be.false('child is visible');
  3809. const restored = emittedOnce(c, 'restore');
  3810. c.restore();
  3811. await restored;
  3812. expect(w.isVisible()).to.be.true('parent is visible');
  3813. expect(c.isVisible()).to.be.true('child is visible');
  3814. });
  3815. it('closes a grandchild window when a middle child window is destroyed', (done) => {
  3816. const w = new BrowserWindow();
  3817. w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
  3818. w.webContents.executeJavaScript('window.open("")');
  3819. w.webContents.on('did-create-window', async (window) => {
  3820. const childWindow = new BrowserWindow({ parent: window });
  3821. await delay();
  3822. window.close();
  3823. childWindow.on('closed', () => {
  3824. expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
  3825. done();
  3826. });
  3827. });
  3828. });
  3829. it('should not affect the show option', () => {
  3830. const w = new BrowserWindow({ show: false });
  3831. const c = new BrowserWindow({ show: false, parent: w });
  3832. expect(c.isVisible()).to.be.false('child is visible');
  3833. expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
  3834. });
  3835. });
  3836. describe('win.setParentWindow(parent)', () => {
  3837. it('sets parent window', () => {
  3838. const w = new BrowserWindow({ show: false });
  3839. const c = new BrowserWindow({ show: false });
  3840. expect(w.getParentWindow()).to.be.null('w.parent');
  3841. expect(c.getParentWindow()).to.be.null('c.parent');
  3842. c.setParentWindow(w);
  3843. expect(c.getParentWindow()).to.equal(w);
  3844. c.setParentWindow(null);
  3845. expect(c.getParentWindow()).to.be.null('c.parent');
  3846. });
  3847. it('adds window to child windows of parent', () => {
  3848. const w = new BrowserWindow({ show: false });
  3849. const c = new BrowserWindow({ show: false });
  3850. expect(w.getChildWindows()).to.deep.equal([]);
  3851. c.setParentWindow(w);
  3852. expect(w.getChildWindows()).to.deep.equal([c]);
  3853. c.setParentWindow(null);
  3854. expect(w.getChildWindows()).to.deep.equal([]);
  3855. });
  3856. it('removes from child windows of parent when window is closed', async () => {
  3857. const w = new BrowserWindow({ show: false });
  3858. const c = new BrowserWindow({ show: false });
  3859. const closed = emittedOnce(c, 'closed');
  3860. c.setParentWindow(w);
  3861. c.close();
  3862. await closed;
  3863. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3864. await delay();
  3865. expect(w.getChildWindows().length).to.equal(0);
  3866. });
  3867. });
  3868. describe('modal option', () => {
  3869. it('does not freeze or crash', async () => {
  3870. const parentWindow = new BrowserWindow();
  3871. const createTwo = async () => {
  3872. const two = new BrowserWindow({
  3873. width: 300,
  3874. height: 200,
  3875. parent: parentWindow,
  3876. modal: true,
  3877. show: false
  3878. });
  3879. const twoShown = emittedOnce(two, 'show');
  3880. two.show();
  3881. await twoShown;
  3882. setTimeout(() => two.close(), 500);
  3883. await emittedOnce(two, 'closed');
  3884. };
  3885. const one = new BrowserWindow({
  3886. width: 600,
  3887. height: 400,
  3888. parent: parentWindow,
  3889. modal: true,
  3890. show: false
  3891. });
  3892. const oneShown = emittedOnce(one, 'show');
  3893. one.show();
  3894. await oneShown;
  3895. setTimeout(() => one.destroy(), 500);
  3896. await emittedOnce(one, 'closed');
  3897. await createTwo();
  3898. });
  3899. ifit(process.platform !== 'darwin')('can disable and enable a window', () => {
  3900. const w = new BrowserWindow({ show: false });
  3901. w.setEnabled(false);
  3902. expect(w.isEnabled()).to.be.false('w.isEnabled()');
  3903. w.setEnabled(true);
  3904. expect(w.isEnabled()).to.be.true('!w.isEnabled()');
  3905. });
  3906. ifit(process.platform !== 'darwin')('disables parent window', () => {
  3907. const w = new BrowserWindow({ show: false });
  3908. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3909. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3910. c.show();
  3911. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3912. });
  3913. ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
  3914. const w = new BrowserWindow({ show: false });
  3915. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3916. const closed = emittedOnce(c, 'closed');
  3917. c.show();
  3918. c.close();
  3919. await closed;
  3920. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3921. });
  3922. ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
  3923. const w = new BrowserWindow({ show: false });
  3924. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3925. const closed = emittedOnce(c, 'closed');
  3926. w.setEnabled(false);
  3927. c.show();
  3928. c.close();
  3929. await closed;
  3930. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3931. });
  3932. ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
  3933. const w = new BrowserWindow({ show: false });
  3934. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3935. const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
  3936. c.show();
  3937. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3938. c2.show();
  3939. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3940. c.destroy();
  3941. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3942. c2.destroy();
  3943. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3944. });
  3945. });
  3946. });
  3947. describe('window states', () => {
  3948. afterEach(closeAllWindows);
  3949. it('does not resize frameless windows when states change', () => {
  3950. const w = new BrowserWindow({
  3951. frame: false,
  3952. width: 300,
  3953. height: 200,
  3954. show: false
  3955. });
  3956. w.minimizable = false;
  3957. w.minimizable = true;
  3958. expect(w.getSize()).to.deep.equal([300, 200]);
  3959. w.resizable = false;
  3960. w.resizable = true;
  3961. expect(w.getSize()).to.deep.equal([300, 200]);
  3962. w.maximizable = false;
  3963. w.maximizable = true;
  3964. expect(w.getSize()).to.deep.equal([300, 200]);
  3965. w.fullScreenable = false;
  3966. w.fullScreenable = true;
  3967. expect(w.getSize()).to.deep.equal([300, 200]);
  3968. w.closable = false;
  3969. w.closable = true;
  3970. expect(w.getSize()).to.deep.equal([300, 200]);
  3971. });
  3972. describe('resizable state', () => {
  3973. it('with properties', () => {
  3974. it('can be set with resizable constructor option', () => {
  3975. const w = new BrowserWindow({ show: false, resizable: false });
  3976. expect(w.resizable).to.be.false('resizable');
  3977. if (process.platform === 'darwin') {
  3978. expect(w.maximizable).to.to.true('maximizable');
  3979. }
  3980. });
  3981. it('can be changed', () => {
  3982. const w = new BrowserWindow({ show: false });
  3983. expect(w.resizable).to.be.true('resizable');
  3984. w.resizable = false;
  3985. expect(w.resizable).to.be.false('resizable');
  3986. w.resizable = true;
  3987. expect(w.resizable).to.be.true('resizable');
  3988. });
  3989. });
  3990. it('with functions', () => {
  3991. it('can be set with resizable constructor option', () => {
  3992. const w = new BrowserWindow({ show: false, resizable: false });
  3993. expect(w.isResizable()).to.be.false('resizable');
  3994. if (process.platform === 'darwin') {
  3995. expect(w.isMaximizable()).to.to.true('maximizable');
  3996. }
  3997. });
  3998. it('can be changed', () => {
  3999. const w = new BrowserWindow({ show: false });
  4000. expect(w.isResizable()).to.be.true('resizable');
  4001. w.setResizable(false);
  4002. expect(w.isResizable()).to.be.false('resizable');
  4003. w.setResizable(true);
  4004. expect(w.isResizable()).to.be.true('resizable');
  4005. });
  4006. });
  4007. it('works for a frameless window', () => {
  4008. const w = new BrowserWindow({ show: false, frame: false });
  4009. expect(w.resizable).to.be.true('resizable');
  4010. if (process.platform === 'win32') {
  4011. const w = new BrowserWindow({ show: false, thickFrame: false });
  4012. expect(w.resizable).to.be.false('resizable');
  4013. }
  4014. });
  4015. // On Linux there is no "resizable" property of a window.
  4016. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
  4017. const w = new BrowserWindow({ show: false });
  4018. expect(w.resizable).to.be.true('resizable');
  4019. expect(w.maximizable).to.be.true('maximizable');
  4020. w.resizable = false;
  4021. expect(w.maximizable).to.be.false('not maximizable');
  4022. w.resizable = true;
  4023. expect(w.maximizable).to.be.true('maximizable');
  4024. });
  4025. ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
  4026. const w = new BrowserWindow({
  4027. show: false,
  4028. frame: false,
  4029. resizable: false,
  4030. transparent: true
  4031. });
  4032. w.setContentSize(60, 60);
  4033. expectBoundsEqual(w.getContentSize(), [60, 60]);
  4034. w.setContentSize(30, 30);
  4035. expectBoundsEqual(w.getContentSize(), [30, 30]);
  4036. w.setContentSize(10, 10);
  4037. expectBoundsEqual(w.getContentSize(), [10, 10]);
  4038. });
  4039. });
  4040. describe('loading main frame state', () => {
  4041. let server: http.Server = null as unknown as http.Server;
  4042. let serverUrl: string = null as unknown as string;
  4043. before((done) => {
  4044. server = http.createServer((request, response) => {
  4045. response.end();
  4046. }).listen(0, '127.0.0.1', () => {
  4047. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  4048. done();
  4049. });
  4050. });
  4051. after(() => {
  4052. server.close();
  4053. });
  4054. it('is true when the main frame is loading', async () => {
  4055. const w = new BrowserWindow({ show: false });
  4056. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  4057. w.webContents.loadURL(serverUrl);
  4058. await didStartLoading;
  4059. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  4060. });
  4061. it('is false when only a subframe is loading', async () => {
  4062. const w = new BrowserWindow({ show: false });
  4063. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  4064. w.webContents.loadURL(serverUrl);
  4065. await didStopLoading;
  4066. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  4067. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  4068. w.webContents.executeJavaScript(`
  4069. var iframe = document.createElement('iframe')
  4070. iframe.src = '${serverUrl}/page2'
  4071. document.body.appendChild(iframe)
  4072. `);
  4073. await didStartLoading;
  4074. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  4075. });
  4076. it('is true when navigating to pages from the same origin', async () => {
  4077. const w = new BrowserWindow({ show: false });
  4078. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  4079. w.webContents.loadURL(serverUrl);
  4080. await didStopLoading;
  4081. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  4082. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  4083. w.webContents.loadURL(`${serverUrl}/page2`);
  4084. await didStartLoading;
  4085. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  4086. });
  4087. });
  4088. });
  4089. ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
  4090. // Not implemented on Linux.
  4091. afterEach(closeAllWindows);
  4092. describe('movable state', () => {
  4093. it('with properties', () => {
  4094. it('can be set with movable constructor option', () => {
  4095. const w = new BrowserWindow({ show: false, movable: false });
  4096. expect(w.movable).to.be.false('movable');
  4097. });
  4098. it('can be changed', () => {
  4099. const w = new BrowserWindow({ show: false });
  4100. expect(w.movable).to.be.true('movable');
  4101. w.movable = false;
  4102. expect(w.movable).to.be.false('movable');
  4103. w.movable = true;
  4104. expect(w.movable).to.be.true('movable');
  4105. });
  4106. });
  4107. it('with functions', () => {
  4108. it('can be set with movable constructor option', () => {
  4109. const w = new BrowserWindow({ show: false, movable: false });
  4110. expect(w.isMovable()).to.be.false('movable');
  4111. });
  4112. it('can be changed', () => {
  4113. const w = new BrowserWindow({ show: false });
  4114. expect(w.isMovable()).to.be.true('movable');
  4115. w.setMovable(false);
  4116. expect(w.isMovable()).to.be.false('movable');
  4117. w.setMovable(true);
  4118. expect(w.isMovable()).to.be.true('movable');
  4119. });
  4120. });
  4121. });
  4122. describe('visibleOnAllWorkspaces state', () => {
  4123. it('with properties', () => {
  4124. it('can be changed', () => {
  4125. const w = new BrowserWindow({ show: false });
  4126. expect(w.visibleOnAllWorkspaces).to.be.false();
  4127. w.visibleOnAllWorkspaces = true;
  4128. expect(w.visibleOnAllWorkspaces).to.be.true();
  4129. });
  4130. });
  4131. it('with functions', () => {
  4132. it('can be changed', () => {
  4133. const w = new BrowserWindow({ show: false });
  4134. expect(w.isVisibleOnAllWorkspaces()).to.be.false();
  4135. w.setVisibleOnAllWorkspaces(true);
  4136. expect(w.isVisibleOnAllWorkspaces()).to.be.true();
  4137. });
  4138. });
  4139. });
  4140. ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
  4141. it('with properties', () => {
  4142. it('can be changed', () => {
  4143. const w = new BrowserWindow({ show: false });
  4144. expect(w.documentEdited).to.be.false();
  4145. w.documentEdited = true;
  4146. expect(w.documentEdited).to.be.true();
  4147. });
  4148. });
  4149. it('with functions', () => {
  4150. it('can be changed', () => {
  4151. const w = new BrowserWindow({ show: false });
  4152. expect(w.isDocumentEdited()).to.be.false();
  4153. w.setDocumentEdited(true);
  4154. expect(w.isDocumentEdited()).to.be.true();
  4155. });
  4156. });
  4157. });
  4158. ifdescribe(process.platform === 'darwin')('representedFilename', () => {
  4159. it('with properties', () => {
  4160. it('can be changed', () => {
  4161. const w = new BrowserWindow({ show: false });
  4162. expect(w.representedFilename).to.eql('');
  4163. w.representedFilename = 'a name';
  4164. expect(w.representedFilename).to.eql('a name');
  4165. });
  4166. });
  4167. it('with functions', () => {
  4168. it('can be changed', () => {
  4169. const w = new BrowserWindow({ show: false });
  4170. expect(w.getRepresentedFilename()).to.eql('');
  4171. w.setRepresentedFilename('a name');
  4172. expect(w.getRepresentedFilename()).to.eql('a name');
  4173. });
  4174. });
  4175. });
  4176. describe('native window title', () => {
  4177. it('with properties', () => {
  4178. it('can be set with title constructor option', () => {
  4179. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  4180. expect(w.title).to.eql('mYtItLe');
  4181. });
  4182. it('can be changed', () => {
  4183. const w = new BrowserWindow({ show: false });
  4184. expect(w.title).to.eql('Electron Test Main');
  4185. w.title = 'NEW TITLE';
  4186. expect(w.title).to.eql('NEW TITLE');
  4187. });
  4188. });
  4189. it('with functions', () => {
  4190. it('can be set with minimizable constructor option', () => {
  4191. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  4192. expect(w.getTitle()).to.eql('mYtItLe');
  4193. });
  4194. it('can be changed', () => {
  4195. const w = new BrowserWindow({ show: false });
  4196. expect(w.getTitle()).to.eql('Electron Test Main');
  4197. w.setTitle('NEW TITLE');
  4198. expect(w.getTitle()).to.eql('NEW TITLE');
  4199. });
  4200. });
  4201. });
  4202. describe('minimizable state', () => {
  4203. it('with properties', () => {
  4204. it('can be set with minimizable constructor option', () => {
  4205. const w = new BrowserWindow({ show: false, minimizable: false });
  4206. expect(w.minimizable).to.be.false('minimizable');
  4207. });
  4208. it('can be changed', () => {
  4209. const w = new BrowserWindow({ show: false });
  4210. expect(w.minimizable).to.be.true('minimizable');
  4211. w.minimizable = false;
  4212. expect(w.minimizable).to.be.false('minimizable');
  4213. w.minimizable = true;
  4214. expect(w.minimizable).to.be.true('minimizable');
  4215. });
  4216. });
  4217. it('with functions', () => {
  4218. it('can be set with minimizable constructor option', () => {
  4219. const w = new BrowserWindow({ show: false, minimizable: false });
  4220. expect(w.isMinimizable()).to.be.false('movable');
  4221. });
  4222. it('can be changed', () => {
  4223. const w = new BrowserWindow({ show: false });
  4224. expect(w.isMinimizable()).to.be.true('isMinimizable');
  4225. w.setMinimizable(false);
  4226. expect(w.isMinimizable()).to.be.false('isMinimizable');
  4227. w.setMinimizable(true);
  4228. expect(w.isMinimizable()).to.be.true('isMinimizable');
  4229. });
  4230. });
  4231. });
  4232. describe('maximizable state (property)', () => {
  4233. it('with properties', () => {
  4234. it('can be set with maximizable constructor option', () => {
  4235. const w = new BrowserWindow({ show: false, maximizable: false });
  4236. expect(w.maximizable).to.be.false('maximizable');
  4237. });
  4238. it('can be changed', () => {
  4239. const w = new BrowserWindow({ show: false });
  4240. expect(w.maximizable).to.be.true('maximizable');
  4241. w.maximizable = false;
  4242. expect(w.maximizable).to.be.false('maximizable');
  4243. w.maximizable = true;
  4244. expect(w.maximizable).to.be.true('maximizable');
  4245. });
  4246. it('is not affected when changing other states', () => {
  4247. const w = new BrowserWindow({ show: false });
  4248. w.maximizable = false;
  4249. expect(w.maximizable).to.be.false('maximizable');
  4250. w.minimizable = false;
  4251. expect(w.maximizable).to.be.false('maximizable');
  4252. w.closable = false;
  4253. expect(w.maximizable).to.be.false('maximizable');
  4254. w.maximizable = true;
  4255. expect(w.maximizable).to.be.true('maximizable');
  4256. w.closable = true;
  4257. expect(w.maximizable).to.be.true('maximizable');
  4258. w.fullScreenable = false;
  4259. expect(w.maximizable).to.be.true('maximizable');
  4260. });
  4261. });
  4262. it('with functions', () => {
  4263. it('can be set with maximizable constructor option', () => {
  4264. const w = new BrowserWindow({ show: false, maximizable: false });
  4265. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4266. });
  4267. it('can be changed', () => {
  4268. const w = new BrowserWindow({ show: false });
  4269. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4270. w.setMaximizable(false);
  4271. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4272. w.setMaximizable(true);
  4273. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4274. });
  4275. it('is not affected when changing other states', () => {
  4276. const w = new BrowserWindow({ show: false });
  4277. w.setMaximizable(false);
  4278. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4279. w.setMinimizable(false);
  4280. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4281. w.setClosable(false);
  4282. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4283. w.setMaximizable(true);
  4284. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4285. w.setClosable(true);
  4286. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4287. w.setFullScreenable(false);
  4288. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4289. });
  4290. });
  4291. });
  4292. ifdescribe(process.platform === 'win32')('maximizable state', () => {
  4293. it('with properties', () => {
  4294. it('is reset to its former state', () => {
  4295. const w = new BrowserWindow({ show: false });
  4296. w.maximizable = false;
  4297. w.resizable = false;
  4298. w.resizable = true;
  4299. expect(w.maximizable).to.be.false('maximizable');
  4300. w.maximizable = true;
  4301. w.resizable = false;
  4302. w.resizable = true;
  4303. expect(w.maximizable).to.be.true('maximizable');
  4304. });
  4305. });
  4306. it('with functions', () => {
  4307. it('is reset to its former state', () => {
  4308. const w = new BrowserWindow({ show: false });
  4309. w.setMaximizable(false);
  4310. w.setResizable(false);
  4311. w.setResizable(true);
  4312. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4313. w.setMaximizable(true);
  4314. w.setResizable(false);
  4315. w.setResizable(true);
  4316. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4317. });
  4318. });
  4319. });
  4320. ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
  4321. describe('with properties', () => {
  4322. it('can be changed', () => {
  4323. const w = new BrowserWindow({ show: false });
  4324. expect(w.menuBarVisible).to.be.true();
  4325. w.menuBarVisible = false;
  4326. expect(w.menuBarVisible).to.be.false();
  4327. w.menuBarVisible = true;
  4328. expect(w.menuBarVisible).to.be.true();
  4329. });
  4330. });
  4331. describe('with functions', () => {
  4332. it('can be changed', () => {
  4333. const w = new BrowserWindow({ show: false });
  4334. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4335. w.setMenuBarVisibility(false);
  4336. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4337. w.setMenuBarVisibility(true);
  4338. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4339. });
  4340. });
  4341. });
  4342. ifdescribe(process.platform !== 'darwin')('when fullscreen state is changed', () => {
  4343. it('correctly remembers state prior to fullscreen change', async () => {
  4344. const w = new BrowserWindow({ show: false });
  4345. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4346. w.setMenuBarVisibility(false);
  4347. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4348. const enterFS = emittedOnce(w, 'enter-full-screen');
  4349. w.setFullScreen(true);
  4350. await enterFS;
  4351. expect(w.fullScreen).to.be.true('not fullscreen');
  4352. const exitFS = emittedOnce(w, 'leave-full-screen');
  4353. w.setFullScreen(false);
  4354. await exitFS;
  4355. expect(w.fullScreen).to.be.false('not fullscreen');
  4356. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4357. });
  4358. it('correctly remembers state prior to fullscreen change with autoHide', async () => {
  4359. const w = new BrowserWindow({ show: false });
  4360. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  4361. w.autoHideMenuBar = true;
  4362. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  4363. w.setMenuBarVisibility(false);
  4364. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4365. const enterFS = emittedOnce(w, 'enter-full-screen');
  4366. w.setFullScreen(true);
  4367. await enterFS;
  4368. expect(w.fullScreen).to.be.true('not fullscreen');
  4369. const exitFS = emittedOnce(w, 'leave-full-screen');
  4370. w.setFullScreen(false);
  4371. await exitFS;
  4372. expect(w.fullScreen).to.be.false('not fullscreen');
  4373. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4374. });
  4375. });
  4376. ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
  4377. it('with functions', () => {
  4378. it('can be set with fullscreenable constructor option', () => {
  4379. const w = new BrowserWindow({ show: false, fullscreenable: false });
  4380. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4381. });
  4382. it('can be changed', () => {
  4383. const w = new BrowserWindow({ show: false });
  4384. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4385. w.setFullScreenable(false);
  4386. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4387. w.setFullScreenable(true);
  4388. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4389. });
  4390. });
  4391. });
  4392. ifdescribe(process.platform === 'darwin')('isHiddenInMissionControl state', () => {
  4393. it('with functions', () => {
  4394. it('can be set with ignoreMissionControl constructor option', () => {
  4395. const w = new BrowserWindow({ show: false, hiddenInMissionControl: true });
  4396. expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
  4397. });
  4398. it('can be changed', () => {
  4399. const w = new BrowserWindow({ show: false });
  4400. expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
  4401. w.setHiddenInMissionControl(true);
  4402. expect(w.isHiddenInMissionControl()).to.be.true('isHiddenInMissionControl');
  4403. w.setHiddenInMissionControl(false);
  4404. expect(w.isHiddenInMissionControl()).to.be.false('isHiddenInMissionControl');
  4405. });
  4406. });
  4407. });
  4408. // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
  4409. ifdescribe(process.platform === 'darwin')('kiosk state', () => {
  4410. it('with properties', () => {
  4411. it('can be set with a constructor property', () => {
  4412. const w = new BrowserWindow({ kiosk: true });
  4413. expect(w.kiosk).to.be.true();
  4414. });
  4415. it('can be changed ', async () => {
  4416. const w = new BrowserWindow();
  4417. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4418. w.kiosk = true;
  4419. expect(w.isKiosk()).to.be.true('isKiosk');
  4420. await enterFullScreen;
  4421. await delay();
  4422. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4423. w.kiosk = false;
  4424. expect(w.isKiosk()).to.be.false('isKiosk');
  4425. await leaveFullScreen;
  4426. });
  4427. });
  4428. it('with functions', () => {
  4429. it('can be set with a constructor property', () => {
  4430. const w = new BrowserWindow({ kiosk: true });
  4431. expect(w.isKiosk()).to.be.true();
  4432. });
  4433. it('can be changed ', async () => {
  4434. const w = new BrowserWindow();
  4435. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4436. w.setKiosk(true);
  4437. expect(w.isKiosk()).to.be.true('isKiosk');
  4438. await enterFullScreen;
  4439. await delay();
  4440. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4441. w.setKiosk(false);
  4442. expect(w.isKiosk()).to.be.false('isKiosk');
  4443. await leaveFullScreen;
  4444. });
  4445. });
  4446. });
  4447. ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
  4448. it('resizable flag should be set to false and restored', async () => {
  4449. const w = new BrowserWindow({ resizable: false });
  4450. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4451. w.setFullScreen(true);
  4452. await enterFullScreen;
  4453. expect(w.resizable).to.be.false('resizable');
  4454. await delay();
  4455. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4456. w.setFullScreen(false);
  4457. await leaveFullScreen;
  4458. expect(w.resizable).to.be.false('resizable');
  4459. });
  4460. it('default resizable flag should be restored after entering/exiting fullscreen', async () => {
  4461. const w = new BrowserWindow();
  4462. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4463. w.setFullScreen(true);
  4464. await enterFullScreen;
  4465. expect(w.resizable).to.be.false('resizable');
  4466. await delay();
  4467. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4468. w.setFullScreen(false);
  4469. await leaveFullScreen;
  4470. expect(w.resizable).to.be.true('resizable');
  4471. });
  4472. });
  4473. ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
  4474. it('should not cause a crash if called when exiting fullscreen', async () => {
  4475. const w = new BrowserWindow();
  4476. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4477. w.setFullScreen(true);
  4478. await enterFullScreen;
  4479. await delay();
  4480. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4481. w.setFullScreen(false);
  4482. await leaveFullScreen;
  4483. });
  4484. it('should be able to load a URL while transitioning to fullscreen', async () => {
  4485. const w = new BrowserWindow({ fullscreen: true });
  4486. w.loadFile(path.join(fixtures, 'pages', 'c.html'));
  4487. const load = emittedOnce(w.webContents, 'did-finish-load');
  4488. const enterFS = emittedOnce(w, 'enter-full-screen');
  4489. await Promise.all([enterFS, load]);
  4490. expect(w.fullScreen).to.be.true();
  4491. await delay();
  4492. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4493. w.setFullScreen(false);
  4494. await leaveFullScreen;
  4495. });
  4496. it('can be changed with setFullScreen method', async () => {
  4497. const w = new BrowserWindow();
  4498. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4499. w.setFullScreen(true);
  4500. await enterFullScreen;
  4501. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4502. await delay();
  4503. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4504. w.setFullScreen(false);
  4505. await leaveFullScreen;
  4506. expect(w.isFullScreen()).to.be.false('isFullScreen');
  4507. });
  4508. it('handles several transitions starting with fullscreen', async () => {
  4509. const w = new BrowserWindow({ fullscreen: true, show: true });
  4510. expect(w.isFullScreen()).to.be.true('not fullscreen');
  4511. w.setFullScreen(false);
  4512. w.setFullScreen(true);
  4513. const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
  4514. await enterFullScreen;
  4515. expect(w.isFullScreen()).to.be.true('not fullscreen');
  4516. await delay();
  4517. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4518. w.setFullScreen(false);
  4519. await leaveFullScreen;
  4520. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4521. });
  4522. it('handles several HTML fullscreen transitions', async () => {
  4523. const w = new BrowserWindow();
  4524. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  4525. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4526. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4527. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4528. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4529. await enterFullScreen;
  4530. await w.webContents.executeJavaScript('document.exitFullscreen()', true);
  4531. await leaveFullScreen;
  4532. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4533. await delay();
  4534. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4535. await enterFullScreen;
  4536. await w.webContents.executeJavaScript('document.exitFullscreen()', true);
  4537. await leaveFullScreen;
  4538. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4539. });
  4540. it('handles several transitions in close proximity', async () => {
  4541. const w = new BrowserWindow();
  4542. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4543. const enterFS = emittedNTimes(w, 'enter-full-screen', 2);
  4544. const leaveFS = emittedNTimes(w, 'leave-full-screen', 2);
  4545. w.setFullScreen(true);
  4546. w.setFullScreen(false);
  4547. w.setFullScreen(true);
  4548. w.setFullScreen(false);
  4549. await Promise.all([enterFS, leaveFS]);
  4550. expect(w.isFullScreen()).to.be.false('not fullscreen');
  4551. });
  4552. it('handles several chromium-initiated transitions in close proximity', async () => {
  4553. const w = new BrowserWindow();
  4554. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  4555. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4556. let enterCount = 0;
  4557. let exitCount = 0;
  4558. const done = new Promise<void>(resolve => {
  4559. const checkDone = () => {
  4560. if (enterCount === 2 && exitCount === 2) resolve();
  4561. };
  4562. w.webContents.on('enter-html-full-screen', () => {
  4563. enterCount++;
  4564. checkDone();
  4565. });
  4566. w.webContents.on('leave-html-full-screen', () => {
  4567. exitCount++;
  4568. checkDone();
  4569. });
  4570. });
  4571. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4572. await w.webContents.executeJavaScript('document.exitFullscreen()');
  4573. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4574. await w.webContents.executeJavaScript('document.exitFullscreen()');
  4575. await done;
  4576. });
  4577. it('handles HTML fullscreen transitions when fullscreenable is false', async () => {
  4578. const w = new BrowserWindow({ fullscreenable: false });
  4579. await w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  4580. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4581. let enterCount = 0;
  4582. let exitCount = 0;
  4583. const done = new Promise<void>((resolve, reject) => {
  4584. const checkDone = () => {
  4585. if (enterCount === 2 && exitCount === 2) resolve();
  4586. };
  4587. w.webContents.on('enter-html-full-screen', async () => {
  4588. enterCount++;
  4589. if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
  4590. const isFS = await w.webContents.executeJavaScript('!!document.fullscreenElement');
  4591. if (!isFS) reject(new Error('Document should have fullscreen element'));
  4592. checkDone();
  4593. });
  4594. w.webContents.on('leave-html-full-screen', () => {
  4595. exitCount++;
  4596. if (w.isFullScreen()) reject(new Error('w.isFullScreen should be false'));
  4597. checkDone();
  4598. });
  4599. });
  4600. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4601. await w.webContents.executeJavaScript('document.exitFullscreen()');
  4602. await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  4603. await w.webContents.executeJavaScript('document.exitFullscreen()');
  4604. await expect(done).to.eventually.be.fulfilled();
  4605. });
  4606. it('does not crash when exiting simpleFullScreen (properties)', async () => {
  4607. const w = new BrowserWindow();
  4608. w.setSimpleFullScreen(true);
  4609. await delay(1000);
  4610. w.setFullScreen(!w.isFullScreen());
  4611. });
  4612. it('does not crash when exiting simpleFullScreen (functions)', async () => {
  4613. const w = new BrowserWindow();
  4614. w.simpleFullScreen = true;
  4615. await delay(1000);
  4616. w.setFullScreen(!w.isFullScreen());
  4617. });
  4618. it('should not be changed by setKiosk method', async () => {
  4619. const w = new BrowserWindow();
  4620. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4621. w.setFullScreen(true);
  4622. await enterFullScreen;
  4623. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4624. await delay();
  4625. w.setKiosk(true);
  4626. await delay();
  4627. w.setKiosk(false);
  4628. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4629. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4630. w.setFullScreen(false);
  4631. await leaveFullScreen;
  4632. expect(w.isFullScreen()).to.be.false('isFullScreen');
  4633. });
  4634. // FIXME: https://github.com/electron/electron/issues/30140
  4635. xit('multiple windows inherit correct fullscreen state', async () => {
  4636. const w = new BrowserWindow();
  4637. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4638. w.setFullScreen(true);
  4639. await enterFullScreen;
  4640. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4641. await delay();
  4642. const w2 = new BrowserWindow({ show: false });
  4643. const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen');
  4644. w2.show();
  4645. await enterFullScreen2;
  4646. expect(w2.isFullScreen()).to.be.true('isFullScreen');
  4647. });
  4648. });
  4649. describe('closable state', () => {
  4650. it('with properties', () => {
  4651. it('can be set with closable constructor option', () => {
  4652. const w = new BrowserWindow({ show: false, closable: false });
  4653. expect(w.closable).to.be.false('closable');
  4654. });
  4655. it('can be changed', () => {
  4656. const w = new BrowserWindow({ show: false });
  4657. expect(w.closable).to.be.true('closable');
  4658. w.closable = false;
  4659. expect(w.closable).to.be.false('closable');
  4660. w.closable = true;
  4661. expect(w.closable).to.be.true('closable');
  4662. });
  4663. });
  4664. it('with functions', () => {
  4665. it('can be set with closable constructor option', () => {
  4666. const w = new BrowserWindow({ show: false, closable: false });
  4667. expect(w.isClosable()).to.be.false('isClosable');
  4668. });
  4669. it('can be changed', () => {
  4670. const w = new BrowserWindow({ show: false });
  4671. expect(w.isClosable()).to.be.true('isClosable');
  4672. w.setClosable(false);
  4673. expect(w.isClosable()).to.be.false('isClosable');
  4674. w.setClosable(true);
  4675. expect(w.isClosable()).to.be.true('isClosable');
  4676. });
  4677. });
  4678. });
  4679. describe('hasShadow state', () => {
  4680. it('with properties', () => {
  4681. it('returns a boolean on all platforms', () => {
  4682. const w = new BrowserWindow({ show: false });
  4683. expect(w.shadow).to.be.a('boolean');
  4684. });
  4685. // On Windows there's no shadow by default & it can't be changed dynamically.
  4686. it('can be changed with hasShadow option', () => {
  4687. const hasShadow = process.platform !== 'darwin';
  4688. const w = new BrowserWindow({ show: false, hasShadow });
  4689. expect(w.shadow).to.equal(hasShadow);
  4690. });
  4691. it('can be changed with setHasShadow method', () => {
  4692. const w = new BrowserWindow({ show: false });
  4693. w.shadow = false;
  4694. expect(w.shadow).to.be.false('hasShadow');
  4695. w.shadow = true;
  4696. expect(w.shadow).to.be.true('hasShadow');
  4697. w.shadow = false;
  4698. expect(w.shadow).to.be.false('hasShadow');
  4699. });
  4700. });
  4701. describe('with functions', () => {
  4702. it('returns a boolean on all platforms', () => {
  4703. const w = new BrowserWindow({ show: false });
  4704. const hasShadow = w.hasShadow();
  4705. expect(hasShadow).to.be.a('boolean');
  4706. });
  4707. // On Windows there's no shadow by default & it can't be changed dynamically.
  4708. it('can be changed with hasShadow option', () => {
  4709. const hasShadow = process.platform !== 'darwin';
  4710. const w = new BrowserWindow({ show: false, hasShadow });
  4711. expect(w.hasShadow()).to.equal(hasShadow);
  4712. });
  4713. it('can be changed with setHasShadow method', () => {
  4714. const w = new BrowserWindow({ show: false });
  4715. w.setHasShadow(false);
  4716. expect(w.hasShadow()).to.be.false('hasShadow');
  4717. w.setHasShadow(true);
  4718. expect(w.hasShadow()).to.be.true('hasShadow');
  4719. w.setHasShadow(false);
  4720. expect(w.hasShadow()).to.be.false('hasShadow');
  4721. });
  4722. });
  4723. });
  4724. });
  4725. describe('window.getMediaSourceId()', () => {
  4726. afterEach(closeAllWindows);
  4727. it('returns valid source id', async () => {
  4728. const w = new BrowserWindow({ show: false });
  4729. const shown = emittedOnce(w, 'show');
  4730. w.show();
  4731. await shown;
  4732. // Check format 'window:1234:0'.
  4733. const sourceId = w.getMediaSourceId();
  4734. expect(sourceId).to.match(/^window:\d+:\d+$/);
  4735. });
  4736. });
  4737. ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
  4738. afterEach(closeAllWindows);
  4739. it('returns valid handle', () => {
  4740. const w = new BrowserWindow({ show: false });
  4741. // The module's source code is hosted at
  4742. // https://github.com/electron/node-is-valid-window
  4743. const isValidWindow = require('is-valid-window');
  4744. expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
  4745. });
  4746. });
  4747. ifdescribe(process.platform === 'darwin')('previewFile', () => {
  4748. afterEach(closeAllWindows);
  4749. it('opens the path in Quick Look on macOS', () => {
  4750. const w = new BrowserWindow({ show: false });
  4751. expect(() => {
  4752. w.previewFile(__filename);
  4753. w.closeFilePreview();
  4754. }).to.not.throw();
  4755. });
  4756. it('should not call BrowserWindow show event', async () => {
  4757. const w = new BrowserWindow({ show: false });
  4758. const shown = emittedOnce(w, 'show');
  4759. w.show();
  4760. await shown;
  4761. let showCalled = false;
  4762. w.on('show', () => {
  4763. showCalled = true;
  4764. });
  4765. w.previewFile(__filename);
  4766. await delay(500);
  4767. expect(showCalled).to.equal(false, 'should not have called show twice');
  4768. });
  4769. });
  4770. // TODO (jkleinsc) renable these tests on mas arm64
  4771. ifdescribe(!process.mas || process.arch !== 'arm64')('contextIsolation option with and without sandbox option', () => {
  4772. const expectedContextData = {
  4773. preloadContext: {
  4774. preloadProperty: 'number',
  4775. pageProperty: 'undefined',
  4776. typeofRequire: 'function',
  4777. typeofProcess: 'object',
  4778. typeofArrayPush: 'function',
  4779. typeofFunctionApply: 'function',
  4780. typeofPreloadExecuteJavaScriptProperty: 'undefined'
  4781. },
  4782. pageContext: {
  4783. preloadProperty: 'undefined',
  4784. pageProperty: 'string',
  4785. typeofRequire: 'undefined',
  4786. typeofProcess: 'undefined',
  4787. typeofArrayPush: 'number',
  4788. typeofFunctionApply: 'boolean',
  4789. typeofPreloadExecuteJavaScriptProperty: 'number',
  4790. typeofOpenedWindow: 'object'
  4791. }
  4792. };
  4793. afterEach(closeAllWindows);
  4794. it('separates the page context from the Electron/preload context', async () => {
  4795. const iw = new BrowserWindow({
  4796. show: false,
  4797. webPreferences: {
  4798. contextIsolation: true,
  4799. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4800. }
  4801. });
  4802. const p = emittedOnce(ipcMain, 'isolated-world');
  4803. iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4804. const [, data] = await p;
  4805. expect(data).to.deep.equal(expectedContextData);
  4806. });
  4807. it('recreates the contexts on reload', async () => {
  4808. const iw = new BrowserWindow({
  4809. show: false,
  4810. webPreferences: {
  4811. contextIsolation: true,
  4812. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4813. }
  4814. });
  4815. await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4816. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  4817. iw.webContents.reload();
  4818. const [, data] = await isolatedWorld;
  4819. expect(data).to.deep.equal(expectedContextData);
  4820. });
  4821. it('enables context isolation on child windows', async () => {
  4822. const iw = new BrowserWindow({
  4823. show: false,
  4824. webPreferences: {
  4825. contextIsolation: true,
  4826. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4827. }
  4828. });
  4829. const browserWindowCreated = emittedOnce(app, 'browser-window-created');
  4830. iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  4831. const [, window] = await browserWindowCreated;
  4832. expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
  4833. });
  4834. it('separates the page context from the Electron/preload context with sandbox on', async () => {
  4835. const ws = new BrowserWindow({
  4836. show: false,
  4837. webPreferences: {
  4838. sandbox: true,
  4839. contextIsolation: true,
  4840. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4841. }
  4842. });
  4843. const p = emittedOnce(ipcMain, 'isolated-world');
  4844. ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4845. const [, data] = await p;
  4846. expect(data).to.deep.equal(expectedContextData);
  4847. });
  4848. it('recreates the contexts on reload with sandbox on', async () => {
  4849. const ws = new BrowserWindow({
  4850. show: false,
  4851. webPreferences: {
  4852. sandbox: true,
  4853. contextIsolation: true,
  4854. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4855. }
  4856. });
  4857. await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4858. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  4859. ws.webContents.reload();
  4860. const [, data] = await isolatedWorld;
  4861. expect(data).to.deep.equal(expectedContextData);
  4862. });
  4863. it('supports fetch api', async () => {
  4864. const fetchWindow = new BrowserWindow({
  4865. show: false,
  4866. webPreferences: {
  4867. contextIsolation: true,
  4868. preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
  4869. }
  4870. });
  4871. const p = emittedOnce(ipcMain, 'isolated-fetch-error');
  4872. fetchWindow.loadURL('about:blank');
  4873. const [, error] = await p;
  4874. expect(error).to.equal('Failed to fetch');
  4875. });
  4876. it('doesn\'t break ipc serialization', async () => {
  4877. const iw = new BrowserWindow({
  4878. show: false,
  4879. webPreferences: {
  4880. contextIsolation: true,
  4881. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4882. }
  4883. });
  4884. const p = emittedOnce(ipcMain, 'isolated-world');
  4885. iw.loadURL('about:blank');
  4886. iw.webContents.executeJavaScript(`
  4887. const opened = window.open()
  4888. openedLocation = opened.location.href
  4889. opened.close()
  4890. window.postMessage({openedLocation}, '*')
  4891. `);
  4892. const [, data] = await p;
  4893. expect(data.pageContext.openedLocation).to.equal('about:blank');
  4894. });
  4895. it('reports process.contextIsolated', async () => {
  4896. const iw = new BrowserWindow({
  4897. show: false,
  4898. webPreferences: {
  4899. contextIsolation: true,
  4900. preload: path.join(fixtures, 'api', 'isolated-process.js')
  4901. }
  4902. });
  4903. const p = emittedOnce(ipcMain, 'context-isolation');
  4904. iw.loadURL('about:blank');
  4905. const [, contextIsolation] = await p;
  4906. expect(contextIsolation).to.be.true('contextIsolation');
  4907. });
  4908. });
  4909. it('reloading does not cause Node.js module API hangs after reload', (done) => {
  4910. const w = new BrowserWindow({
  4911. show: false,
  4912. webPreferences: {
  4913. nodeIntegration: true,
  4914. contextIsolation: false
  4915. }
  4916. });
  4917. let count = 0;
  4918. ipcMain.on('async-node-api-done', () => {
  4919. if (count === 3) {
  4920. ipcMain.removeAllListeners('async-node-api-done');
  4921. done();
  4922. } else {
  4923. count++;
  4924. w.reload();
  4925. }
  4926. });
  4927. w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
  4928. });
  4929. describe('window.webContents.focus()', () => {
  4930. afterEach(closeAllWindows);
  4931. it('focuses window', async () => {
  4932. const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
  4933. w1.loadURL('about:blank');
  4934. const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
  4935. w2.loadURL('about:blank');
  4936. const w1Focused = emittedOnce(w1, 'focus');
  4937. w1.webContents.focus();
  4938. await w1Focused;
  4939. expect(w1.webContents.isFocused()).to.be.true('focuses window');
  4940. });
  4941. });
  4942. ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
  4943. let w: BrowserWindow;
  4944. beforeEach(function () {
  4945. w = new BrowserWindow({
  4946. width: 100,
  4947. height: 100,
  4948. show: false,
  4949. webPreferences: {
  4950. backgroundThrottling: false,
  4951. offscreen: true
  4952. }
  4953. });
  4954. });
  4955. afterEach(closeAllWindows);
  4956. it('creates offscreen window with correct size', async () => {
  4957. const paint = emittedOnce(w.webContents, 'paint');
  4958. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4959. const [,, data] = await paint;
  4960. expect(data.constructor.name).to.equal('NativeImage');
  4961. expect(data.isEmpty()).to.be.false('data is empty');
  4962. const size = data.getSize();
  4963. const { scaleFactor } = screen.getPrimaryDisplay();
  4964. expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
  4965. expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
  4966. });
  4967. it('does not crash after navigation', () => {
  4968. w.webContents.loadURL('about:blank');
  4969. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4970. });
  4971. describe('window.webContents.isOffscreen()', () => {
  4972. it('is true for offscreen type', () => {
  4973. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4974. expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
  4975. });
  4976. it('is false for regular window', () => {
  4977. const c = new BrowserWindow({ show: false });
  4978. expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
  4979. c.destroy();
  4980. });
  4981. });
  4982. describe('window.webContents.isPainting()', () => {
  4983. it('returns whether is currently painting', async () => {
  4984. const paint = emittedOnce(w.webContents, 'paint');
  4985. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4986. await paint;
  4987. expect(w.webContents.isPainting()).to.be.true('isPainting');
  4988. });
  4989. });
  4990. describe('window.webContents.stopPainting()', () => {
  4991. it('stops painting', async () => {
  4992. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4993. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4994. await domReady;
  4995. w.webContents.stopPainting();
  4996. expect(w.webContents.isPainting()).to.be.false('isPainting');
  4997. });
  4998. });
  4999. describe('window.webContents.startPainting()', () => {
  5000. it('starts painting', async () => {
  5001. const domReady = emittedOnce(w.webContents, 'dom-ready');
  5002. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5003. await domReady;
  5004. w.webContents.stopPainting();
  5005. w.webContents.startPainting();
  5006. await emittedOnce(w.webContents, 'paint');
  5007. expect(w.webContents.isPainting()).to.be.true('isPainting');
  5008. });
  5009. });
  5010. describe('frameRate APIs', () => {
  5011. it('has default frame rate (function)', async () => {
  5012. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5013. await emittedOnce(w.webContents, 'paint');
  5014. expect(w.webContents.getFrameRate()).to.equal(60);
  5015. });
  5016. it('has default frame rate (property)', async () => {
  5017. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5018. await emittedOnce(w.webContents, 'paint');
  5019. expect(w.webContents.frameRate).to.equal(60);
  5020. });
  5021. it('sets custom frame rate (function)', async () => {
  5022. const domReady = emittedOnce(w.webContents, 'dom-ready');
  5023. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5024. await domReady;
  5025. w.webContents.setFrameRate(30);
  5026. await emittedOnce(w.webContents, 'paint');
  5027. expect(w.webContents.getFrameRate()).to.equal(30);
  5028. });
  5029. it('sets custom frame rate (property)', async () => {
  5030. const domReady = emittedOnce(w.webContents, 'dom-ready');
  5031. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  5032. await domReady;
  5033. w.webContents.frameRate = 30;
  5034. await emittedOnce(w.webContents, 'paint');
  5035. expect(w.webContents.frameRate).to.equal(30);
  5036. });
  5037. });
  5038. });
  5039. describe('"transparent" option', () => {
  5040. afterEach(closeAllWindows);
  5041. ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => {
  5042. const w = new BrowserWindow({
  5043. frame: false,
  5044. transparent: true
  5045. });
  5046. const maximize = emittedOnce(w, 'maximize');
  5047. w.maximize();
  5048. await maximize;
  5049. const minimize = emittedOnce(w, 'minimize');
  5050. w.minimize();
  5051. await minimize;
  5052. expect(w.isMaximized()).to.be.false();
  5053. expect(w.isMinimized()).to.be.true();
  5054. });
  5055. // Only applicable on Windows where transparent windows can't be maximized.
  5056. ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
  5057. const display = screen.getPrimaryDisplay();
  5058. const w = new BrowserWindow({
  5059. ...display.bounds,
  5060. frame: false,
  5061. transparent: true,
  5062. show: true
  5063. });
  5064. w.loadURL('about:blank');
  5065. await emittedOnce(w, 'ready-to-show');
  5066. expect(w.isMaximized()).to.be.true();
  5067. // Fails when the transparent HWND is in an invalid maximized state.
  5068. expect(w.getBounds()).to.deep.equal(display.workArea);
  5069. const newBounds = { width: 256, height: 256, x: 0, y: 0 };
  5070. w.setBounds(newBounds);
  5071. expect(w.getBounds()).to.deep.equal(newBounds);
  5072. });
  5073. // Linux and arm64 platforms (WOA and macOS) do not return any capture sources
  5074. ifit(process.platform === 'darwin' && process.arch === 'x64')('should not display a visible background', async () => {
  5075. const display = screen.getPrimaryDisplay();
  5076. const backgroundWindow = new BrowserWindow({
  5077. ...display.bounds,
  5078. frame: false,
  5079. backgroundColor: HexColors.GREEN,
  5080. hasShadow: false
  5081. });
  5082. await backgroundWindow.loadURL('about:blank');
  5083. const foregroundWindow = new BrowserWindow({
  5084. ...display.bounds,
  5085. show: true,
  5086. transparent: true,
  5087. frame: false,
  5088. hasShadow: false
  5089. });
  5090. const colorFile = path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html');
  5091. await foregroundWindow.loadFile(colorFile);
  5092. await delay(1000);
  5093. const screenCapture = await captureScreen();
  5094. const leftHalfColor = getPixelColor(screenCapture, {
  5095. x: display.size.width / 4,
  5096. y: display.size.height / 2
  5097. });
  5098. const rightHalfColor = getPixelColor(screenCapture, {
  5099. x: display.size.width - (display.size.width / 4),
  5100. y: display.size.height / 2
  5101. });
  5102. expect(areColorsSimilar(leftHalfColor, HexColors.GREEN)).to.be.true();
  5103. expect(areColorsSimilar(rightHalfColor, HexColors.RED)).to.be.true();
  5104. });
  5105. ifit(process.platform === 'darwin')('Allows setting a transparent window via CSS', async () => {
  5106. const display = screen.getPrimaryDisplay();
  5107. const backgroundWindow = new BrowserWindow({
  5108. ...display.bounds,
  5109. frame: false,
  5110. backgroundColor: HexColors.PURPLE,
  5111. hasShadow: false
  5112. });
  5113. await backgroundWindow.loadURL('about:blank');
  5114. const foregroundWindow = new BrowserWindow({
  5115. ...display.bounds,
  5116. frame: false,
  5117. transparent: true,
  5118. hasShadow: false,
  5119. webPreferences: {
  5120. contextIsolation: false,
  5121. nodeIntegration: true
  5122. }
  5123. });
  5124. foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'css-transparent.html'));
  5125. await emittedOnce(ipcMain, 'set-transparent');
  5126. await delay();
  5127. const screenCapture = await captureScreen();
  5128. const centerColor = getPixelColor(screenCapture, {
  5129. x: display.size.width / 2,
  5130. y: display.size.height / 2
  5131. });
  5132. expect(areColorsSimilar(centerColor, HexColors.PURPLE)).to.be.true();
  5133. });
  5134. // Linux and arm64 platforms (WOA and macOS) do not return any capture sources
  5135. ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make background transparent if falsy', async () => {
  5136. const display = screen.getPrimaryDisplay();
  5137. for (const transparent of [false, undefined]) {
  5138. const window = new BrowserWindow({
  5139. ...display.bounds,
  5140. transparent
  5141. });
  5142. await emittedOnce(window, 'show');
  5143. await window.webContents.loadURL('data:text/html,<head><meta name="color-scheme" content="dark"></head>');
  5144. await delay(500);
  5145. const screenCapture = await captureScreen();
  5146. const centerColor = getPixelColor(screenCapture, {
  5147. x: display.size.width / 2,
  5148. y: display.size.height / 2
  5149. });
  5150. window.close();
  5151. // color-scheme is set to dark so background should not be white
  5152. expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false();
  5153. }
  5154. });
  5155. });
  5156. describe('"backgroundColor" option', () => {
  5157. afterEach(closeAllWindows);
  5158. // Linux/WOA doesn't return any capture sources.
  5159. ifit(process.platform === 'darwin')('should display the set color', async () => {
  5160. const display = screen.getPrimaryDisplay();
  5161. const w = new BrowserWindow({
  5162. ...display.bounds,
  5163. show: true,
  5164. backgroundColor: HexColors.BLUE
  5165. });
  5166. w.loadURL('about:blank');
  5167. await emittedOnce(w, 'ready-to-show');
  5168. const screenCapture = await captureScreen();
  5169. const centerColor = getPixelColor(screenCapture, {
  5170. x: display.size.width / 2,
  5171. y: display.size.height / 2
  5172. });
  5173. expect(areColorsSimilar(centerColor, HexColors.BLUE)).to.be.true();
  5174. });
  5175. });
  5176. });