api-browser-window-spec.ts 199 KB

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