api-browser-window-spec.ts 183 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144
  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 os from 'os';
  6. import * as qs from 'querystring';
  7. import * as http from 'http';
  8. import * as semver from 'semver';
  9. import { AddressInfo } from 'net';
  10. import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main';
  11. import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers';
  12. import { ifit, ifdescribe, defer, delay } from './spec-helpers';
  13. import { closeWindow, closeAllWindows } from './window-helpers';
  14. const features = process._linkedBinding('electron_common_features');
  15. const fixtures = path.resolve(__dirname, '..', 'spec', '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. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  523. type: 'mousePressed',
  524. x: 10,
  525. y: 10,
  526. clickCount: 1,
  527. button: 'left'
  528. }, sessionId);
  529. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  530. type: 'mouseReleased',
  531. x: 10,
  532. y: 10,
  533. clickCount: 1,
  534. button: 'left'
  535. }, sessionId);
  536. let willNavigateEmitted = false;
  537. w.webContents.on('will-navigate', () => {
  538. willNavigateEmitted = true;
  539. });
  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. });
  1089. describe('BrowserWindow.getNormalBounds()', () => {
  1090. describe('Normal state', () => {
  1091. it('checks normal bounds after resize', async () => {
  1092. const size = [300, 400];
  1093. const resize = emittedOnce(w, 'resize');
  1094. w.setSize(size[0], size[1]);
  1095. await resize;
  1096. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  1097. });
  1098. it('checks normal bounds after move', async () => {
  1099. const pos = [10, 10];
  1100. const move = emittedOnce(w, 'move');
  1101. w.setPosition(pos[0], pos[1]);
  1102. await move;
  1103. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  1104. });
  1105. });
  1106. ifdescribe(process.platform !== 'linux')('Maximized state', () => {
  1107. it('checks normal bounds when maximized', async () => {
  1108. const bounds = w.getBounds();
  1109. const maximize = emittedOnce(w, 'maximize');
  1110. w.show();
  1111. w.maximize();
  1112. await maximize;
  1113. expectBoundsEqual(w.getNormalBounds(), bounds);
  1114. });
  1115. it('checks normal bounds when unmaximized', async () => {
  1116. const bounds = w.getBounds();
  1117. w.once('maximize', () => {
  1118. w.unmaximize();
  1119. });
  1120. const unmaximize = emittedOnce(w, 'unmaximize');
  1121. w.show();
  1122. w.maximize();
  1123. await unmaximize;
  1124. expectBoundsEqual(w.getNormalBounds(), bounds);
  1125. });
  1126. it('does not change size for a frameless window with min size', async () => {
  1127. w.destroy();
  1128. w = new BrowserWindow({
  1129. show: false,
  1130. frame: false,
  1131. width: 300,
  1132. height: 300,
  1133. minWidth: 300,
  1134. minHeight: 300
  1135. });
  1136. const bounds = w.getBounds();
  1137. w.once('maximize', () => {
  1138. w.unmaximize();
  1139. });
  1140. const unmaximize = emittedOnce(w, 'unmaximize');
  1141. w.show();
  1142. w.maximize();
  1143. await unmaximize;
  1144. expectBoundsEqual(w.getNormalBounds(), bounds);
  1145. });
  1146. it('correctly checks transparent window maximization state', async () => {
  1147. w.destroy();
  1148. w = new BrowserWindow({
  1149. show: false,
  1150. width: 300,
  1151. height: 300,
  1152. transparent: true
  1153. });
  1154. const maximize = emittedOnce(w, 'maximize');
  1155. w.show();
  1156. w.maximize();
  1157. await maximize;
  1158. expect(w.isMaximized()).to.equal(true);
  1159. const unmaximize = emittedOnce(w, 'unmaximize');
  1160. w.unmaximize();
  1161. await unmaximize;
  1162. expect(w.isMaximized()).to.equal(false);
  1163. });
  1164. it('returns the correct value for windows with an aspect ratio', async () => {
  1165. w.destroy();
  1166. w = new BrowserWindow({
  1167. show: false,
  1168. fullscreenable: false
  1169. });
  1170. w.setAspectRatio(16 / 11);
  1171. const maximize = emittedOnce(w, 'resize');
  1172. w.show();
  1173. w.maximize();
  1174. await maximize;
  1175. expect(w.isMaximized()).to.equal(true);
  1176. w.resizable = false;
  1177. expect(w.isMaximized()).to.equal(true);
  1178. });
  1179. });
  1180. ifdescribe(process.platform !== 'linux')('Minimized state', () => {
  1181. it('checks normal bounds when minimized', async () => {
  1182. const bounds = w.getBounds();
  1183. const minimize = emittedOnce(w, 'minimize');
  1184. w.show();
  1185. w.minimize();
  1186. await minimize;
  1187. expectBoundsEqual(w.getNormalBounds(), bounds);
  1188. });
  1189. it('checks normal bounds when restored', async () => {
  1190. const bounds = w.getBounds();
  1191. w.once('minimize', () => {
  1192. w.restore();
  1193. });
  1194. const restore = emittedOnce(w, 'restore');
  1195. w.show();
  1196. w.minimize();
  1197. await restore;
  1198. expectBoundsEqual(w.getNormalBounds(), bounds);
  1199. });
  1200. it('does not change size for a frameless window with min size', async () => {
  1201. w.destroy();
  1202. w = new BrowserWindow({
  1203. show: false,
  1204. frame: false,
  1205. width: 300,
  1206. height: 300,
  1207. minWidth: 300,
  1208. minHeight: 300
  1209. });
  1210. const bounds = w.getBounds();
  1211. w.once('minimize', () => {
  1212. w.restore();
  1213. });
  1214. const restore = emittedOnce(w, 'restore');
  1215. w.show();
  1216. w.minimize();
  1217. await restore;
  1218. expectBoundsEqual(w.getNormalBounds(), bounds);
  1219. });
  1220. });
  1221. ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
  1222. it('with properties', () => {
  1223. it('can be set with the fullscreen constructor option', () => {
  1224. w = new BrowserWindow({ fullscreen: true });
  1225. expect(w.fullScreen).to.be.true();
  1226. });
  1227. it('can be changed', () => {
  1228. w.fullScreen = false;
  1229. expect(w.fullScreen).to.be.false();
  1230. w.fullScreen = true;
  1231. expect(w.fullScreen).to.be.true();
  1232. });
  1233. it('checks normal bounds when fullscreen\'ed', async () => {
  1234. const bounds = w.getBounds();
  1235. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1236. w.show();
  1237. w.fullScreen = true;
  1238. await enterFullScreen;
  1239. expectBoundsEqual(w.getNormalBounds(), bounds);
  1240. });
  1241. it('checks normal bounds when unfullscreen\'ed', async () => {
  1242. const bounds = w.getBounds();
  1243. w.once('enter-full-screen', () => {
  1244. w.fullScreen = false;
  1245. });
  1246. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1247. w.show();
  1248. w.fullScreen = true;
  1249. await leaveFullScreen;
  1250. expectBoundsEqual(w.getNormalBounds(), bounds);
  1251. });
  1252. });
  1253. it('with functions', () => {
  1254. it('can be set with the fullscreen constructor option', () => {
  1255. w = new BrowserWindow({ fullscreen: true });
  1256. expect(w.isFullScreen()).to.be.true();
  1257. });
  1258. it('can be changed', () => {
  1259. w.setFullScreen(false);
  1260. expect(w.isFullScreen()).to.be.false();
  1261. w.setFullScreen(true);
  1262. expect(w.isFullScreen()).to.be.true();
  1263. });
  1264. it('checks normal bounds when fullscreen\'ed', async () => {
  1265. const bounds = w.getBounds();
  1266. w.show();
  1267. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1268. w.setFullScreen(true);
  1269. await enterFullScreen;
  1270. expectBoundsEqual(w.getNormalBounds(), bounds);
  1271. });
  1272. it('checks normal bounds when unfullscreen\'ed', async () => {
  1273. const bounds = w.getBounds();
  1274. w.show();
  1275. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1276. w.setFullScreen(true);
  1277. await enterFullScreen;
  1278. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1279. w.setFullScreen(false);
  1280. await leaveFullScreen;
  1281. expectBoundsEqual(w.getNormalBounds(), bounds);
  1282. });
  1283. });
  1284. });
  1285. });
  1286. });
  1287. ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
  1288. let w = null as unknown as BrowserWindow;
  1289. beforeEach(() => {
  1290. w = new BrowserWindow({ show: false });
  1291. });
  1292. afterEach(async () => {
  1293. await closeWindow(w);
  1294. w = null as unknown as BrowserWindow;
  1295. });
  1296. describe('BrowserWindow.selectPreviousTab()', () => {
  1297. it('does not throw', () => {
  1298. expect(() => {
  1299. w.selectPreviousTab();
  1300. }).to.not.throw();
  1301. });
  1302. });
  1303. describe('BrowserWindow.selectNextTab()', () => {
  1304. it('does not throw', () => {
  1305. expect(() => {
  1306. w.selectNextTab();
  1307. }).to.not.throw();
  1308. });
  1309. });
  1310. describe('BrowserWindow.mergeAllWindows()', () => {
  1311. it('does not throw', () => {
  1312. expect(() => {
  1313. w.mergeAllWindows();
  1314. }).to.not.throw();
  1315. });
  1316. });
  1317. describe('BrowserWindow.moveTabToNewWindow()', () => {
  1318. it('does not throw', () => {
  1319. expect(() => {
  1320. w.moveTabToNewWindow();
  1321. }).to.not.throw();
  1322. });
  1323. });
  1324. describe('BrowserWindow.toggleTabBar()', () => {
  1325. it('does not throw', () => {
  1326. expect(() => {
  1327. w.toggleTabBar();
  1328. }).to.not.throw();
  1329. });
  1330. });
  1331. describe('BrowserWindow.addTabbedWindow()', () => {
  1332. it('does not throw', async () => {
  1333. const tabbedWindow = new BrowserWindow({});
  1334. expect(() => {
  1335. w.addTabbedWindow(tabbedWindow);
  1336. }).to.not.throw();
  1337. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
  1338. await closeWindow(tabbedWindow, { assertNotWindows: false });
  1339. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
  1340. });
  1341. it('throws when called on itself', () => {
  1342. expect(() => {
  1343. w.addTabbedWindow(w);
  1344. }).to.throw('AddTabbedWindow cannot be called by a window on itself.');
  1345. });
  1346. });
  1347. });
  1348. describe('autoHideMenuBar state', () => {
  1349. afterEach(closeAllWindows);
  1350. it('for properties', () => {
  1351. it('can be set with autoHideMenuBar constructor option', () => {
  1352. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1353. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1354. });
  1355. it('can be changed', () => {
  1356. const w = new BrowserWindow({ show: false });
  1357. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1358. w.autoHideMenuBar = true;
  1359. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1360. w.autoHideMenuBar = false;
  1361. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1362. });
  1363. });
  1364. it('for functions', () => {
  1365. it('can be set with autoHideMenuBar constructor option', () => {
  1366. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1367. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1368. });
  1369. it('can be changed', () => {
  1370. const w = new BrowserWindow({ show: false });
  1371. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1372. w.setAutoHideMenuBar(true);
  1373. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1374. w.setAutoHideMenuBar(false);
  1375. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1376. });
  1377. });
  1378. });
  1379. describe('BrowserWindow.capturePage(rect)', () => {
  1380. afterEach(closeAllWindows);
  1381. it('returns a Promise with a Buffer', async () => {
  1382. const w = new BrowserWindow({ show: false });
  1383. const image = await w.capturePage({
  1384. x: 0,
  1385. y: 0,
  1386. width: 100,
  1387. height: 100
  1388. });
  1389. expect(image.isEmpty()).to.equal(true);
  1390. });
  1391. it('resolves after the window is hidden', async () => {
  1392. const w = new BrowserWindow({ show: false });
  1393. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  1394. await emittedOnce(w, 'ready-to-show');
  1395. w.show();
  1396. const visibleImage = await w.capturePage();
  1397. expect(visibleImage.isEmpty()).to.equal(false);
  1398. w.hide();
  1399. const hiddenImage = await w.capturePage();
  1400. const isEmpty = process.platform !== 'darwin';
  1401. expect(hiddenImage.isEmpty()).to.equal(isEmpty);
  1402. });
  1403. it('resolves after the window is hidden and capturer count is non-zero', async () => {
  1404. const w = new BrowserWindow({ show: false });
  1405. w.webContents.setBackgroundThrottling(false);
  1406. w.loadFile(path.join(fixtures, 'pages', 'a.html'));
  1407. await emittedOnce(w, 'ready-to-show');
  1408. w.webContents.incrementCapturerCount();
  1409. const image = await w.capturePage();
  1410. expect(image.isEmpty()).to.equal(false);
  1411. });
  1412. it('preserves transparency', async () => {
  1413. const w = new BrowserWindow({ show: false, transparent: true });
  1414. w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
  1415. await emittedOnce(w, 'ready-to-show');
  1416. w.show();
  1417. const image = await w.capturePage();
  1418. const imgBuffer = image.toPNG();
  1419. // Check the 25th byte in the PNG.
  1420. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  1421. expect(imgBuffer[25]).to.equal(6);
  1422. });
  1423. it('should increase the capturer count', () => {
  1424. const w = new BrowserWindow({ show: false });
  1425. w.webContents.incrementCapturerCount();
  1426. expect(w.webContents.isBeingCaptured()).to.be.true();
  1427. w.webContents.decrementCapturerCount();
  1428. expect(w.webContents.isBeingCaptured()).to.be.false();
  1429. });
  1430. });
  1431. describe('BrowserWindow.setProgressBar(progress)', () => {
  1432. let w = null as unknown as BrowserWindow;
  1433. before(() => {
  1434. w = new BrowserWindow({ show: false });
  1435. });
  1436. after(async () => {
  1437. await closeWindow(w);
  1438. w = null as unknown as BrowserWindow;
  1439. });
  1440. it('sets the progress', () => {
  1441. expect(() => {
  1442. if (process.platform === 'darwin') {
  1443. app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
  1444. }
  1445. w.setProgressBar(0.5);
  1446. if (process.platform === 'darwin') {
  1447. app.dock.setIcon(null as any);
  1448. }
  1449. w.setProgressBar(-1);
  1450. }).to.not.throw();
  1451. });
  1452. it('sets the progress using "paused" mode', () => {
  1453. expect(() => {
  1454. w.setProgressBar(0.5, { mode: 'paused' });
  1455. }).to.not.throw();
  1456. });
  1457. it('sets the progress using "error" mode', () => {
  1458. expect(() => {
  1459. w.setProgressBar(0.5, { mode: 'error' });
  1460. }).to.not.throw();
  1461. });
  1462. it('sets the progress using "normal" mode', () => {
  1463. expect(() => {
  1464. w.setProgressBar(0.5, { mode: 'normal' });
  1465. }).to.not.throw();
  1466. });
  1467. });
  1468. describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
  1469. let w = null as unknown as BrowserWindow;
  1470. afterEach(closeAllWindows);
  1471. beforeEach(() => {
  1472. w = new BrowserWindow({ show: true });
  1473. });
  1474. it('sets the window as always on top', () => {
  1475. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1476. w.setAlwaysOnTop(true, 'screen-saver');
  1477. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1478. w.setAlwaysOnTop(false);
  1479. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1480. w.setAlwaysOnTop(true);
  1481. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1482. });
  1483. ifit(process.platform === 'darwin')('resets the windows level on minimize', () => {
  1484. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1485. w.setAlwaysOnTop(true, 'screen-saver');
  1486. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1487. w.minimize();
  1488. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1489. w.restore();
  1490. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1491. });
  1492. it('causes the right value to be emitted on `always-on-top-changed`', async () => {
  1493. const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed');
  1494. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1495. w.setAlwaysOnTop(true);
  1496. const [, alwaysOnTop] = await alwaysOnTopChanged;
  1497. expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
  1498. });
  1499. ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => {
  1500. w = new BrowserWindow({ show: false });
  1501. const c = new BrowserWindow({ parent: w });
  1502. c.setAlwaysOnTop(true, 'screen-saver');
  1503. expect(w.isAlwaysOnTop()).to.be.false();
  1504. expect(c.isAlwaysOnTop()).to.be.true('child is not always on top');
  1505. expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver');
  1506. });
  1507. });
  1508. describe('preconnect feature', () => {
  1509. let w = null as unknown as BrowserWindow;
  1510. let server = null as unknown as http.Server;
  1511. let url = null as unknown as string;
  1512. let connections = 0;
  1513. beforeEach(async () => {
  1514. connections = 0;
  1515. server = http.createServer((req, res) => {
  1516. if (req.url === '/link') {
  1517. res.setHeader('Content-type', 'text/html');
  1518. res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
  1519. return;
  1520. }
  1521. res.end();
  1522. });
  1523. server.on('connection', () => { connections++; });
  1524. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve()));
  1525. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1526. });
  1527. afterEach(async () => {
  1528. server.close();
  1529. await closeWindow(w);
  1530. w = null as unknown as BrowserWindow;
  1531. server = null as unknown as http.Server;
  1532. });
  1533. it('calling preconnect() connects to the server', async () => {
  1534. w = new BrowserWindow({ show: false });
  1535. w.webContents.on('did-start-navigation', (event, url) => {
  1536. w.webContents.session.preconnect({ url, numSockets: 4 });
  1537. });
  1538. await w.loadURL(url);
  1539. expect(connections).to.equal(4);
  1540. });
  1541. it('does not preconnect unless requested', async () => {
  1542. w = new BrowserWindow({ show: false });
  1543. await w.loadURL(url);
  1544. expect(connections).to.equal(1);
  1545. });
  1546. it('parses <link rel=preconnect>', async () => {
  1547. w = new BrowserWindow({ show: true });
  1548. const p = emittedOnce(w.webContents.session, 'preconnect');
  1549. w.loadURL(url + '/link');
  1550. const [, preconnectUrl, allowCredentials] = await p;
  1551. expect(preconnectUrl).to.equal('http://example.com/');
  1552. expect(allowCredentials).to.be.true('allowCredentials');
  1553. });
  1554. });
  1555. describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
  1556. let w = null as unknown as BrowserWindow;
  1557. beforeEach(() => {
  1558. w = new BrowserWindow({ show: false });
  1559. });
  1560. afterEach(async () => {
  1561. await closeWindow(w);
  1562. w = null as unknown as BrowserWindow;
  1563. });
  1564. ifit(process.platform === 'darwin')('on macOS', () => {
  1565. it('allows changing cursor auto-hiding', () => {
  1566. expect(() => {
  1567. w.setAutoHideCursor(false);
  1568. w.setAutoHideCursor(true);
  1569. }).to.not.throw();
  1570. });
  1571. });
  1572. ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
  1573. it('is not available', () => {
  1574. expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
  1575. });
  1576. });
  1577. });
  1578. ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
  1579. afterEach(closeAllWindows);
  1580. it('does not throw', () => {
  1581. const w = new BrowserWindow({ show: false });
  1582. expect(() => {
  1583. w.setWindowButtonVisibility(true);
  1584. w.setWindowButtonVisibility(false);
  1585. }).to.not.throw();
  1586. });
  1587. it('changes window button visibility for normal window', () => {
  1588. const w = new BrowserWindow({ show: false });
  1589. expect(w._getWindowButtonVisibility()).to.equal(true);
  1590. w.setWindowButtonVisibility(false);
  1591. expect(w._getWindowButtonVisibility()).to.equal(false);
  1592. w.setWindowButtonVisibility(true);
  1593. expect(w._getWindowButtonVisibility()).to.equal(true);
  1594. });
  1595. it('changes window button visibility for frameless window', () => {
  1596. const w = new BrowserWindow({ show: false, frame: false });
  1597. expect(w._getWindowButtonVisibility()).to.equal(false);
  1598. w.setWindowButtonVisibility(true);
  1599. expect(w._getWindowButtonVisibility()).to.equal(true);
  1600. w.setWindowButtonVisibility(false);
  1601. expect(w._getWindowButtonVisibility()).to.equal(false);
  1602. });
  1603. it('changes window button visibility for hiddenInset window', () => {
  1604. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' });
  1605. expect(w._getWindowButtonVisibility()).to.equal(true);
  1606. w.setWindowButtonVisibility(false);
  1607. expect(w._getWindowButtonVisibility()).to.equal(false);
  1608. w.setWindowButtonVisibility(true);
  1609. expect(w._getWindowButtonVisibility()).to.equal(true);
  1610. });
  1611. // Buttons of customButtonsOnHover are always hidden unless hovered.
  1612. it('does not change window button visibility for customButtonsOnHover window', () => {
  1613. const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' });
  1614. expect(w._getWindowButtonVisibility()).to.equal(false);
  1615. w.setWindowButtonVisibility(true);
  1616. expect(w._getWindowButtonVisibility()).to.equal(false);
  1617. w.setWindowButtonVisibility(false);
  1618. expect(w._getWindowButtonVisibility()).to.equal(false);
  1619. });
  1620. });
  1621. ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
  1622. let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined;
  1623. afterEach(() => {
  1624. if (appProcess && !appProcess.killed) {
  1625. appProcess.kill();
  1626. appProcess = undefined;
  1627. }
  1628. closeAllWindows();
  1629. });
  1630. it('allows setting, changing, and removing the vibrancy', () => {
  1631. const w = new BrowserWindow({ show: false });
  1632. expect(() => {
  1633. w.setVibrancy('light');
  1634. w.setVibrancy('dark');
  1635. w.setVibrancy(null);
  1636. w.setVibrancy('ultra-dark');
  1637. w.setVibrancy('' as any);
  1638. }).to.not.throw();
  1639. });
  1640. it('does not crash if vibrancy is set to an invalid value', () => {
  1641. const w = new BrowserWindow({ show: false });
  1642. expect(() => {
  1643. w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any);
  1644. }).to.not.throw();
  1645. });
  1646. it('Allows setting a transparent window via CSS', async () => {
  1647. const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent');
  1648. appProcess = childProcess.spawn(process.execPath, [appPath]);
  1649. const [code] = await emittedOnce(appProcess, 'exit');
  1650. expect(code).to.equal(0);
  1651. });
  1652. });
  1653. ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => {
  1654. const pos = { x: 10, y: 10 };
  1655. afterEach(closeAllWindows);
  1656. describe('BrowserWindow.getTrafficLightPosition(pos)', () => {
  1657. it('gets position property for "hidden" titleBarStyle', () => {
  1658. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1659. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1660. });
  1661. it('gets position property for "customButtonsOnHover" titleBarStyle', () => {
  1662. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1663. expect(w.getTrafficLightPosition()).to.deep.equal(pos);
  1664. });
  1665. });
  1666. describe('BrowserWindow.setTrafficLightPosition(pos)', () => {
  1667. it('sets position property for "hidden" titleBarStyle', () => {
  1668. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1669. const newPos = { x: 20, y: 20 };
  1670. w.setTrafficLightPosition(newPos);
  1671. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1672. });
  1673. it('sets position property for "customButtonsOnHover" titleBarStyle', () => {
  1674. const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos });
  1675. const newPos = { x: 20, y: 20 };
  1676. w.setTrafficLightPosition(newPos);
  1677. expect(w.getTrafficLightPosition()).to.deep.equal(newPos);
  1678. });
  1679. });
  1680. });
  1681. ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
  1682. afterEach(closeAllWindows);
  1683. it('supports setting the app details', () => {
  1684. const w = new BrowserWindow({ show: false });
  1685. const iconPath = path.join(fixtures, 'assets', 'icon.ico');
  1686. expect(() => {
  1687. w.setAppDetails({ appId: 'my.app.id' });
  1688. w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
  1689. w.setAppDetails({ appIconPath: iconPath });
  1690. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
  1691. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
  1692. w.setAppDetails({ relaunchDisplayName: 'My app name' });
  1693. w.setAppDetails({
  1694. appId: 'my.app.id',
  1695. appIconPath: iconPath,
  1696. appIconIndex: 0,
  1697. relaunchCommand: 'my-app.exe arg1 arg2',
  1698. relaunchDisplayName: 'My app name'
  1699. });
  1700. w.setAppDetails({});
  1701. }).to.not.throw();
  1702. expect(() => {
  1703. (w.setAppDetails as any)();
  1704. }).to.throw('Insufficient number of arguments.');
  1705. });
  1706. });
  1707. describe('BrowserWindow.fromId(id)', () => {
  1708. afterEach(closeAllWindows);
  1709. it('returns the window with id', () => {
  1710. const w = new BrowserWindow({ show: false });
  1711. expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id);
  1712. });
  1713. });
  1714. describe('BrowserWindow.fromWebContents(webContents)', () => {
  1715. afterEach(closeAllWindows);
  1716. it('returns the window with the webContents', () => {
  1717. const w = new BrowserWindow({ show: false });
  1718. const found = BrowserWindow.fromWebContents(w.webContents);
  1719. expect(found!.id).to.equal(w.id);
  1720. });
  1721. it('returns null for webContents without a BrowserWindow', () => {
  1722. const contents = (webContents as any).create({});
  1723. try {
  1724. expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
  1725. } finally {
  1726. contents.destroy();
  1727. }
  1728. });
  1729. it('returns the correct window for a BrowserView webcontents', async () => {
  1730. const w = new BrowserWindow({ show: false });
  1731. const bv = new BrowserView();
  1732. w.setBrowserView(bv);
  1733. defer(() => {
  1734. w.removeBrowserView(bv);
  1735. (bv.webContents as any).destroy();
  1736. });
  1737. await bv.webContents.loadURL('about:blank');
  1738. expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
  1739. });
  1740. it('returns the correct window for a WebView webcontents', async () => {
  1741. const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } });
  1742. w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>');
  1743. // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for
  1744. // https://github.com/electron/electron/issues/25413, and is not integral
  1745. // to the test.
  1746. const p = emittedOnce(w.webContents, 'did-attach-webview');
  1747. const [, webviewContents] = await emittedOnce(app, 'web-contents-created');
  1748. expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id);
  1749. await p;
  1750. });
  1751. });
  1752. describe('BrowserWindow.openDevTools()', () => {
  1753. afterEach(closeAllWindows);
  1754. it('does not crash for frameless window', () => {
  1755. const w = new BrowserWindow({ show: false, frame: false });
  1756. w.webContents.openDevTools();
  1757. });
  1758. });
  1759. describe('BrowserWindow.fromBrowserView(browserView)', () => {
  1760. afterEach(closeAllWindows);
  1761. it('returns the window with the BrowserView', () => {
  1762. const w = new BrowserWindow({ show: false });
  1763. const bv = new BrowserView();
  1764. w.setBrowserView(bv);
  1765. defer(() => {
  1766. w.removeBrowserView(bv);
  1767. (bv.webContents as any).destroy();
  1768. });
  1769. expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
  1770. });
  1771. it('returns the window when there are multiple BrowserViews', () => {
  1772. const w = new BrowserWindow({ show: false });
  1773. const bv1 = new BrowserView();
  1774. w.addBrowserView(bv1);
  1775. const bv2 = new BrowserView();
  1776. w.addBrowserView(bv2);
  1777. defer(() => {
  1778. w.removeBrowserView(bv1);
  1779. w.removeBrowserView(bv2);
  1780. (bv1.webContents as any).destroy();
  1781. (bv2.webContents as any).destroy();
  1782. });
  1783. expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
  1784. expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
  1785. });
  1786. it('returns undefined if not attached', () => {
  1787. const bv = new BrowserView();
  1788. defer(() => {
  1789. (bv.webContents as any).destroy();
  1790. });
  1791. expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
  1792. });
  1793. });
  1794. describe('BrowserWindow.setOpacity(opacity)', () => {
  1795. afterEach(closeAllWindows);
  1796. ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
  1797. it('make window with initial opacity', () => {
  1798. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  1799. expect(w.getOpacity()).to.equal(0.5);
  1800. });
  1801. it('allows setting the opacity', () => {
  1802. const w = new BrowserWindow({ show: false });
  1803. expect(() => {
  1804. w.setOpacity(0.0);
  1805. expect(w.getOpacity()).to.equal(0.0);
  1806. w.setOpacity(0.5);
  1807. expect(w.getOpacity()).to.equal(0.5);
  1808. w.setOpacity(1.0);
  1809. expect(w.getOpacity()).to.equal(1.0);
  1810. }).to.not.throw();
  1811. });
  1812. it('clamps opacity to [0.0...1.0]', () => {
  1813. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  1814. w.setOpacity(100);
  1815. expect(w.getOpacity()).to.equal(1.0);
  1816. w.setOpacity(-100);
  1817. expect(w.getOpacity()).to.equal(0.0);
  1818. });
  1819. });
  1820. ifdescribe(process.platform === 'linux')(('Linux'), () => {
  1821. it('sets 1 regardless of parameter', () => {
  1822. const w = new BrowserWindow({ show: false });
  1823. w.setOpacity(0);
  1824. expect(w.getOpacity()).to.equal(1.0);
  1825. w.setOpacity(0.5);
  1826. expect(w.getOpacity()).to.equal(1.0);
  1827. });
  1828. });
  1829. });
  1830. describe('BrowserWindow.setShape(rects)', () => {
  1831. afterEach(closeAllWindows);
  1832. it('allows setting shape', () => {
  1833. const w = new BrowserWindow({ show: false });
  1834. expect(() => {
  1835. w.setShape([]);
  1836. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
  1837. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
  1838. w.setShape([]);
  1839. }).to.not.throw();
  1840. });
  1841. });
  1842. describe('"useContentSize" option', () => {
  1843. afterEach(closeAllWindows);
  1844. it('make window created with content size when used', () => {
  1845. const w = new BrowserWindow({
  1846. show: false,
  1847. width: 400,
  1848. height: 400,
  1849. useContentSize: true
  1850. });
  1851. const contentSize = w.getContentSize();
  1852. expect(contentSize).to.deep.equal([400, 400]);
  1853. });
  1854. it('make window created with window size when not used', () => {
  1855. const w = new BrowserWindow({
  1856. show: false,
  1857. width: 400,
  1858. height: 400
  1859. });
  1860. const size = w.getSize();
  1861. expect(size).to.deep.equal([400, 400]);
  1862. });
  1863. it('works for a frameless window', () => {
  1864. const w = new BrowserWindow({
  1865. show: false,
  1866. frame: false,
  1867. width: 400,
  1868. height: 400,
  1869. useContentSize: true
  1870. });
  1871. const contentSize = w.getContentSize();
  1872. expect(contentSize).to.deep.equal([400, 400]);
  1873. const size = w.getSize();
  1874. expect(size).to.deep.equal([400, 400]);
  1875. });
  1876. });
  1877. ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => {
  1878. const testWindowsOverlay = async (style: any) => {
  1879. const w = new BrowserWindow({
  1880. show: false,
  1881. width: 400,
  1882. height: 400,
  1883. titleBarStyle: style,
  1884. webPreferences: {
  1885. nodeIntegration: true,
  1886. contextIsolation: false
  1887. },
  1888. titleBarOverlay: true
  1889. });
  1890. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  1891. if (process.platform === 'darwin') {
  1892. await w.loadFile(overlayHTML);
  1893. } else {
  1894. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  1895. await w.loadFile(overlayHTML);
  1896. await overlayReady;
  1897. }
  1898. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  1899. expect(overlayEnabled).to.be.true('overlayEnabled');
  1900. const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  1901. expect(overlayRect.y).to.equal(0);
  1902. if (process.platform === 'darwin') {
  1903. expect(overlayRect.x).to.be.greaterThan(0);
  1904. } else {
  1905. expect(overlayRect.x).to.equal(0);
  1906. }
  1907. expect(overlayRect.width).to.be.greaterThan(0);
  1908. expect(overlayRect.height).to.be.greaterThan(0);
  1909. const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();');
  1910. expect(cssOverlayRect).to.deep.equal(overlayRect);
  1911. const geometryChange = emittedOnce(ipcMain, 'geometrychange');
  1912. w.setBounds({ width: 800 });
  1913. const [, newOverlayRect] = await geometryChange;
  1914. expect(newOverlayRect.width).to.equal(overlayRect.width + 400);
  1915. };
  1916. afterEach(closeAllWindows);
  1917. afterEach(() => { ipcMain.removeAllListeners('geometrychange'); });
  1918. it('creates browser window with hidden title bar', () => {
  1919. const w = new BrowserWindow({
  1920. show: false,
  1921. width: 400,
  1922. height: 400,
  1923. titleBarStyle: 'hidden'
  1924. });
  1925. const contentSize = w.getContentSize();
  1926. expect(contentSize).to.deep.equal([400, 400]);
  1927. });
  1928. ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => {
  1929. const w = new BrowserWindow({
  1930. show: false,
  1931. width: 400,
  1932. height: 400,
  1933. titleBarStyle: 'hiddenInset'
  1934. });
  1935. const contentSize = w.getContentSize();
  1936. expect(contentSize).to.deep.equal([400, 400]);
  1937. });
  1938. it('sets Window Control Overlay with hidden title bar', async () => {
  1939. await testWindowsOverlay('hidden');
  1940. });
  1941. ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => {
  1942. await testWindowsOverlay('hiddenInset');
  1943. });
  1944. ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => {
  1945. let w: BrowserWindow;
  1946. beforeEach(() => {
  1947. w = new BrowserWindow({
  1948. show: false,
  1949. webPreferences: {
  1950. nodeIntegration: true,
  1951. contextIsolation: false
  1952. },
  1953. titleBarOverlay: {
  1954. color: '#0000f0',
  1955. symbolColor: '#ffffff'
  1956. },
  1957. titleBarStyle: 'hiddenInset'
  1958. });
  1959. });
  1960. afterEach(async () => {
  1961. await closeAllWindows();
  1962. });
  1963. it('does not crash changing minimizability ', () => {
  1964. expect(() => {
  1965. w.setMinimizable(false);
  1966. }).to.not.throw();
  1967. });
  1968. it('does not crash changing maximizability', () => {
  1969. expect(() => {
  1970. w.setMaximizable(false);
  1971. }).to.not.throw();
  1972. });
  1973. });
  1974. });
  1975. ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => {
  1976. const testWindowsOverlayHeight = async (size: any) => {
  1977. const w = new BrowserWindow({
  1978. show: false,
  1979. width: 400,
  1980. height: 400,
  1981. titleBarStyle: 'hidden',
  1982. webPreferences: {
  1983. nodeIntegration: true,
  1984. contextIsolation: false
  1985. },
  1986. titleBarOverlay: {
  1987. height: size
  1988. }
  1989. });
  1990. const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html');
  1991. if (process.platform === 'darwin') {
  1992. await w.loadFile(overlayHTML);
  1993. } else {
  1994. const overlayReady = emittedOnce(ipcMain, 'geometrychange');
  1995. await w.loadFile(overlayHTML);
  1996. await overlayReady;
  1997. }
  1998. const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible');
  1999. expect(overlayEnabled).to.be.true('overlayEnabled');
  2000. const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2001. await w.maximize();
  2002. const max = await w.isMaximized();
  2003. expect(max).to.equal(true);
  2004. const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()');
  2005. expect(overlayRectPreMax.y).to.equal(0);
  2006. if (process.platform === 'darwin') {
  2007. expect(overlayRectPreMax.x).to.be.greaterThan(0);
  2008. } else {
  2009. expect(overlayRectPreMax.x).to.equal(0);
  2010. }
  2011. expect(overlayRectPreMax.width).to.be.greaterThan(0);
  2012. expect(overlayRectPreMax.height).to.equal(size);
  2013. // Confirm that maximization only affected the height of the buttons and not the title bar
  2014. expect(overlayRectPostMax.height).to.equal(size);
  2015. };
  2016. afterEach(closeAllWindows);
  2017. afterEach(() => { ipcMain.removeAllListeners('geometrychange'); });
  2018. it('sets Window Control Overlay with title bar height of 40', async () => {
  2019. await testWindowsOverlayHeight(40);
  2020. });
  2021. });
  2022. ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
  2023. afterEach(closeAllWindows);
  2024. it('can move the window out of screen', () => {
  2025. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2026. w.setPosition(-10, 50);
  2027. const after = w.getPosition();
  2028. expect(after).to.deep.equal([-10, 50]);
  2029. });
  2030. it('cannot move the window behind menu bar', () => {
  2031. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2032. w.setPosition(-10, -10);
  2033. const after = w.getPosition();
  2034. expect(after[1]).to.be.at.least(0);
  2035. });
  2036. it('can move the window behind menu bar if it has no frame', () => {
  2037. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
  2038. w.setPosition(-10, -10);
  2039. const after = w.getPosition();
  2040. expect(after[0]).to.be.equal(-10);
  2041. expect(after[1]).to.be.equal(-10);
  2042. });
  2043. it('without it, cannot move the window out of screen', () => {
  2044. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2045. w.setPosition(-10, -10);
  2046. const after = w.getPosition();
  2047. expect(after[1]).to.be.at.least(0);
  2048. });
  2049. it('can set the window larger than screen', () => {
  2050. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  2051. const size = screen.getPrimaryDisplay().size;
  2052. size.width += 100;
  2053. size.height += 100;
  2054. w.setSize(size.width, size.height);
  2055. expectBoundsEqual(w.getSize(), [size.width, size.height]);
  2056. });
  2057. it('without it, cannot set the window larger than screen', () => {
  2058. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  2059. const size = screen.getPrimaryDisplay().size;
  2060. size.width += 100;
  2061. size.height += 100;
  2062. w.setSize(size.width, size.height);
  2063. expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
  2064. });
  2065. });
  2066. ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
  2067. afterEach(closeAllWindows);
  2068. it('sets the window width to the page width when used', () => {
  2069. const w = new BrowserWindow({
  2070. show: false,
  2071. width: 500,
  2072. height: 400,
  2073. zoomToPageWidth: true
  2074. });
  2075. w.maximize();
  2076. expect(w.getSize()[0]).to.equal(500);
  2077. });
  2078. });
  2079. describe('"tabbingIdentifier" option', () => {
  2080. afterEach(closeAllWindows);
  2081. it('can be set on a window', () => {
  2082. expect(() => {
  2083. /* eslint-disable no-new */
  2084. new BrowserWindow({
  2085. tabbingIdentifier: 'group1'
  2086. });
  2087. new BrowserWindow({
  2088. tabbingIdentifier: 'group2',
  2089. frame: false
  2090. });
  2091. /* eslint-enable no-new */
  2092. }).not.to.throw();
  2093. });
  2094. });
  2095. describe('"webPreferences" option', () => {
  2096. afterEach(() => { ipcMain.removeAllListeners('answer'); });
  2097. afterEach(closeAllWindows);
  2098. describe('"preload" option', () => {
  2099. const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
  2100. it(name, async () => {
  2101. const w = new BrowserWindow({
  2102. webPreferences: {
  2103. ...webPrefs,
  2104. preload: path.resolve(fixtures, 'module', 'empty.js')
  2105. },
  2106. show: false
  2107. });
  2108. w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
  2109. const [, result] = await emittedOnce(ipcMain, 'leak-result');
  2110. expect(result).to.have.property('require', 'undefined');
  2111. expect(result).to.have.property('exports', 'undefined');
  2112. expect(result).to.have.property('windowExports', 'undefined');
  2113. expect(result).to.have.property('windowPreload', 'undefined');
  2114. expect(result).to.have.property('windowRequire', 'undefined');
  2115. });
  2116. };
  2117. doesNotLeakSpec('does not leak require', {
  2118. nodeIntegration: false,
  2119. sandbox: false,
  2120. contextIsolation: false
  2121. });
  2122. doesNotLeakSpec('does not leak require when sandbox is enabled', {
  2123. nodeIntegration: false,
  2124. sandbox: true,
  2125. contextIsolation: false
  2126. });
  2127. doesNotLeakSpec('does not leak require when context isolation is enabled', {
  2128. nodeIntegration: false,
  2129. sandbox: false,
  2130. contextIsolation: true
  2131. });
  2132. doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
  2133. nodeIntegration: false,
  2134. sandbox: true,
  2135. contextIsolation: true
  2136. });
  2137. it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
  2138. let w = new BrowserWindow({
  2139. webPreferences: {
  2140. contextIsolation: false,
  2141. nodeIntegration: false,
  2142. preload: path.resolve(fixtures, 'module', 'empty.js')
  2143. },
  2144. show: false
  2145. });
  2146. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2147. const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result');
  2148. expect(notIsolated).to.have.property('globals');
  2149. w.destroy();
  2150. w = new BrowserWindow({
  2151. webPreferences: {
  2152. contextIsolation: true,
  2153. nodeIntegration: false,
  2154. preload: path.resolve(fixtures, 'module', 'empty.js')
  2155. },
  2156. show: false
  2157. });
  2158. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  2159. const [, isolated] = await emittedOnce(ipcMain, 'leak-result');
  2160. expect(isolated).to.have.property('globals');
  2161. const notIsolatedGlobals = new Set(notIsolated.globals);
  2162. for (const isolatedGlobal of isolated.globals) {
  2163. notIsolatedGlobals.delete(isolatedGlobal);
  2164. }
  2165. expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals');
  2166. });
  2167. it('loads the script before other scripts in window', async () => {
  2168. const preload = path.join(fixtures, 'module', 'set-global.js');
  2169. const w = new BrowserWindow({
  2170. show: false,
  2171. webPreferences: {
  2172. nodeIntegration: true,
  2173. contextIsolation: false,
  2174. preload
  2175. }
  2176. });
  2177. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2178. const [, test] = await emittedOnce(ipcMain, 'answer');
  2179. expect(test).to.eql('preload');
  2180. });
  2181. it('has synchronous access to all eventual window APIs', async () => {
  2182. const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
  2183. const w = new BrowserWindow({
  2184. show: false,
  2185. webPreferences: {
  2186. nodeIntegration: true,
  2187. contextIsolation: false,
  2188. preload
  2189. }
  2190. });
  2191. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2192. const [, test] = await emittedOnce(ipcMain, 'answer');
  2193. expect(test).to.be.an('object');
  2194. expect(test.atPreload).to.be.an('array');
  2195. expect(test.atLoad).to.be.an('array');
  2196. expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
  2197. });
  2198. });
  2199. describe('session preload scripts', function () {
  2200. const preloads = [
  2201. path.join(fixtures, 'module', 'set-global-preload-1.js'),
  2202. path.join(fixtures, 'module', 'set-global-preload-2.js'),
  2203. path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
  2204. ];
  2205. const defaultSession = session.defaultSession;
  2206. beforeEach(() => {
  2207. expect(defaultSession.getPreloads()).to.deep.equal([]);
  2208. defaultSession.setPreloads(preloads);
  2209. });
  2210. afterEach(() => {
  2211. defaultSession.setPreloads([]);
  2212. });
  2213. it('can set multiple session preload script', () => {
  2214. expect(defaultSession.getPreloads()).to.deep.equal(preloads);
  2215. });
  2216. const generateSpecs = (description: string, sandbox: boolean) => {
  2217. describe(description, () => {
  2218. it('loads the script before other scripts in window including normal preloads', async () => {
  2219. const w = new BrowserWindow({
  2220. show: false,
  2221. webPreferences: {
  2222. sandbox,
  2223. preload: path.join(fixtures, 'module', 'get-global-preload.js'),
  2224. contextIsolation: false
  2225. }
  2226. });
  2227. w.loadURL('about:blank');
  2228. const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars');
  2229. expect(preload1).to.equal('preload-1');
  2230. expect(preload2).to.equal('preload-1-2');
  2231. expect(preload3).to.be.undefined('preload 3');
  2232. });
  2233. });
  2234. };
  2235. generateSpecs('without sandbox', false);
  2236. generateSpecs('with sandbox', true);
  2237. });
  2238. describe('"additionalArguments" option', () => {
  2239. it('adds extra args to process.argv in the renderer process', async () => {
  2240. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  2241. const w = new BrowserWindow({
  2242. show: false,
  2243. webPreferences: {
  2244. nodeIntegration: true,
  2245. preload,
  2246. additionalArguments: ['--my-magic-arg']
  2247. }
  2248. });
  2249. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2250. const [, argv] = await emittedOnce(ipcMain, 'answer');
  2251. expect(argv).to.include('--my-magic-arg');
  2252. });
  2253. it('adds extra value args to process.argv in the renderer process', async () => {
  2254. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  2255. const w = new BrowserWindow({
  2256. show: false,
  2257. webPreferences: {
  2258. nodeIntegration: true,
  2259. preload,
  2260. additionalArguments: ['--my-magic-arg=foo']
  2261. }
  2262. });
  2263. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2264. const [, argv] = await emittedOnce(ipcMain, 'answer');
  2265. expect(argv).to.include('--my-magic-arg=foo');
  2266. });
  2267. });
  2268. describe('"node-integration" option', () => {
  2269. it('disables node integration by default', async () => {
  2270. const preload = path.join(fixtures, 'module', 'send-later.js');
  2271. const w = new BrowserWindow({
  2272. show: false,
  2273. webPreferences: {
  2274. preload,
  2275. contextIsolation: false
  2276. }
  2277. });
  2278. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  2279. const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer');
  2280. expect(typeofProcess).to.equal('undefined');
  2281. expect(typeofBuffer).to.equal('undefined');
  2282. });
  2283. });
  2284. describe('"sandbox" option', () => {
  2285. const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
  2286. let server: http.Server = null as unknown as http.Server;
  2287. let serverUrl: string = null as unknown as string;
  2288. before((done) => {
  2289. server = http.createServer((request, response) => {
  2290. switch (request.url) {
  2291. case '/cross-site':
  2292. response.end(`<html><body><h1>${request.url}</h1></body></html>`);
  2293. break;
  2294. default:
  2295. throw new Error(`unsupported endpoint: ${request.url}`);
  2296. }
  2297. }).listen(0, '127.0.0.1', () => {
  2298. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  2299. done();
  2300. });
  2301. });
  2302. after(() => {
  2303. server.close();
  2304. });
  2305. it('exposes ipcRenderer to preload script', async () => {
  2306. const w = new BrowserWindow({
  2307. show: false,
  2308. webPreferences: {
  2309. sandbox: true,
  2310. preload,
  2311. contextIsolation: false
  2312. }
  2313. });
  2314. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2315. const [, test] = await emittedOnce(ipcMain, 'answer');
  2316. expect(test).to.equal('preload');
  2317. });
  2318. it('exposes ipcRenderer to preload script (path has special chars)', async () => {
  2319. const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
  2320. const w = new BrowserWindow({
  2321. show: false,
  2322. webPreferences: {
  2323. sandbox: true,
  2324. preload: preloadSpecialChars,
  2325. contextIsolation: false
  2326. }
  2327. });
  2328. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2329. const [, test] = await emittedOnce(ipcMain, 'answer');
  2330. expect(test).to.equal('preload');
  2331. });
  2332. it('exposes "loaded" event to preload script', async () => {
  2333. const w = new BrowserWindow({
  2334. show: false,
  2335. webPreferences: {
  2336. sandbox: true,
  2337. preload
  2338. }
  2339. });
  2340. w.loadURL('about:blank');
  2341. await emittedOnce(ipcMain, 'process-loaded');
  2342. });
  2343. it('exposes "exit" event to preload script', async () => {
  2344. const w = new BrowserWindow({
  2345. show: false,
  2346. webPreferences: {
  2347. sandbox: true,
  2348. preload,
  2349. contextIsolation: false
  2350. }
  2351. });
  2352. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
  2353. const pageUrl = 'file://' + htmlPath;
  2354. w.loadURL(pageUrl);
  2355. const [, url] = await emittedOnce(ipcMain, 'answer');
  2356. const expectedUrl = process.platform === 'win32'
  2357. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2358. : pageUrl;
  2359. expect(url).to.equal(expectedUrl);
  2360. });
  2361. it('should open windows in same domain with cross-scripting enabled', async () => {
  2362. const w = new BrowserWindow({
  2363. show: true,
  2364. webPreferences: {
  2365. sandbox: true,
  2366. preload,
  2367. contextIsolation: false
  2368. }
  2369. });
  2370. w.webContents.setWindowOpenHandler(() => ({
  2371. action: 'allow',
  2372. overrideBrowserWindowOptions: {
  2373. webPreferences: {
  2374. preload
  2375. }
  2376. }
  2377. }));
  2378. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
  2379. const pageUrl = 'file://' + htmlPath;
  2380. const answer = emittedOnce(ipcMain, 'answer');
  2381. w.loadURL(pageUrl);
  2382. const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window');
  2383. const expectedUrl = process.platform === 'win32'
  2384. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  2385. : pageUrl;
  2386. expect(url).to.equal(expectedUrl);
  2387. expect(frameName).to.equal('popup!');
  2388. expect(options.width).to.equal(500);
  2389. expect(options.height).to.equal(600);
  2390. const [, html] = await answer;
  2391. expect(html).to.equal('<h1>scripting from opener</h1>');
  2392. });
  2393. it('should open windows in another domain with cross-scripting disabled', async () => {
  2394. const w = new BrowserWindow({
  2395. show: true,
  2396. webPreferences: {
  2397. sandbox: true,
  2398. preload,
  2399. contextIsolation: false
  2400. }
  2401. });
  2402. w.webContents.setWindowOpenHandler(() => ({
  2403. action: 'allow',
  2404. overrideBrowserWindowOptions: {
  2405. webPreferences: {
  2406. preload
  2407. }
  2408. }
  2409. }));
  2410. w.loadFile(
  2411. path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
  2412. { search: 'window-open-external' }
  2413. );
  2414. // Wait for a message from the main window saying that it's ready.
  2415. await emittedOnce(ipcMain, 'opener-loaded');
  2416. // Ask the opener to open a popup with window.opener.
  2417. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
  2418. w.webContents.send('open-the-popup', expectedPopupUrl);
  2419. // The page is going to open a popup that it won't be able to close.
  2420. // We have to close it from here later.
  2421. const [, popupWindow] = await emittedOnce(app, 'browser-window-created');
  2422. // Ask the popup window for details.
  2423. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded');
  2424. popupWindow.webContents.send('provide-details');
  2425. const [, openerIsNull, , locationHref] = await detailsAnswer;
  2426. expect(openerIsNull).to.be.false('window.opener is null');
  2427. expect(locationHref).to.equal(expectedPopupUrl);
  2428. // Ask the page to access the popup.
  2429. const touchPopupResult = emittedOnce(ipcMain, 'answer');
  2430. w.webContents.send('touch-the-popup');
  2431. const [, popupAccessMessage] = await touchPopupResult;
  2432. // Ask the popup to access the opener.
  2433. const touchOpenerResult = emittedOnce(ipcMain, 'answer');
  2434. popupWindow.webContents.send('touch-the-opener');
  2435. const [, openerAccessMessage] = await touchOpenerResult;
  2436. // We don't need the popup anymore, and its parent page can't close it,
  2437. // so let's close it from here before we run any checks.
  2438. await closeWindow(popupWindow, { assertNotWindows: false });
  2439. expect(popupAccessMessage).to.be.a('string',
  2440. 'child\'s .document is accessible from its parent window');
  2441. expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
  2442. expect(openerAccessMessage).to.be.a('string',
  2443. 'opener .document is accessible from a popup window');
  2444. expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
  2445. });
  2446. it('should inherit the sandbox setting in opened windows', async () => {
  2447. const w = new BrowserWindow({
  2448. show: false,
  2449. webPreferences: {
  2450. sandbox: true
  2451. }
  2452. });
  2453. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2454. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } }));
  2455. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2456. const [, { argv }] = await emittedOnce(ipcMain, 'answer');
  2457. expect(argv).to.include('--enable-sandbox');
  2458. });
  2459. it('should open windows with the options configured via new-window event listeners', async () => {
  2460. const w = new BrowserWindow({
  2461. show: false,
  2462. webPreferences: {
  2463. sandbox: true
  2464. }
  2465. });
  2466. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2467. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } }));
  2468. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2469. const [[, childWebContents]] = await Promise.all([
  2470. emittedOnce(app, 'web-contents-created'),
  2471. emittedOnce(ipcMain, 'answer')
  2472. ]);
  2473. const webPreferences = childWebContents.getLastWebPreferences();
  2474. expect(webPreferences.contextIsolation).to.equal(false);
  2475. });
  2476. it('should set ipc event sender correctly', async () => {
  2477. const w = new BrowserWindow({
  2478. show: false,
  2479. webPreferences: {
  2480. sandbox: true,
  2481. preload,
  2482. contextIsolation: false
  2483. }
  2484. });
  2485. let childWc: WebContents | null = null;
  2486. w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } }));
  2487. w.webContents.on('did-create-window', (win) => {
  2488. childWc = win.webContents;
  2489. expect(w.webContents).to.not.equal(childWc);
  2490. });
  2491. ipcMain.once('parent-ready', function (event) {
  2492. expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
  2493. event.sender.send('verified');
  2494. });
  2495. ipcMain.once('child-ready', function (event) {
  2496. expect(childWc).to.not.be.null('child webcontents should be available');
  2497. expect(event.sender).to.equal(childWc, 'sender should be the child');
  2498. event.sender.send('verified');
  2499. });
  2500. const done = Promise.all([
  2501. 'parent-answer',
  2502. 'child-answer'
  2503. ].map(name => emittedOnce(ipcMain, name)));
  2504. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
  2505. await done;
  2506. });
  2507. describe('event handling', () => {
  2508. let w: BrowserWindow = null as unknown as BrowserWindow;
  2509. beforeEach(() => {
  2510. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  2511. });
  2512. it('works for window events', async () => {
  2513. const pageTitleUpdated = emittedOnce(w, 'page-title-updated');
  2514. w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
  2515. await pageTitleUpdated;
  2516. });
  2517. it('works for stop events', async () => {
  2518. const done = Promise.all([
  2519. 'did-navigate',
  2520. 'did-fail-load',
  2521. 'did-stop-loading'
  2522. ].map(name => emittedOnce(w.webContents, name)));
  2523. w.loadURL('data:text/html,<script>stop()</script>');
  2524. await done;
  2525. });
  2526. it('works for web contents events', async () => {
  2527. const done = Promise.all([
  2528. 'did-finish-load',
  2529. 'did-frame-finish-load',
  2530. 'did-navigate-in-page',
  2531. 'will-navigate',
  2532. 'did-start-loading',
  2533. 'did-stop-loading',
  2534. 'did-frame-finish-load',
  2535. 'dom-ready'
  2536. ].map(name => emittedOnce(w.webContents, name)));
  2537. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
  2538. await done;
  2539. });
  2540. });
  2541. it('supports calling preventDefault on new-window events', (done) => {
  2542. const w = new BrowserWindow({
  2543. show: false,
  2544. webPreferences: {
  2545. sandbox: true
  2546. }
  2547. });
  2548. const initialWebContents = webContents.getAllWebContents().map((i) => i.id);
  2549. w.webContents.once('new-window', (e) => {
  2550. e.preventDefault();
  2551. // We need to give it some time so the windows get properly disposed (at least on OSX).
  2552. setTimeout(() => {
  2553. const currentWebContents = webContents.getAllWebContents().map((i) => i.id);
  2554. try {
  2555. expect(currentWebContents).to.deep.equal(initialWebContents);
  2556. done();
  2557. } catch (error) {
  2558. done(e);
  2559. }
  2560. }, 100);
  2561. });
  2562. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  2563. });
  2564. it('validates process APIs access in sandboxed renderer', async () => {
  2565. const w = new BrowserWindow({
  2566. show: false,
  2567. webPreferences: {
  2568. sandbox: true,
  2569. preload,
  2570. contextIsolation: false
  2571. }
  2572. });
  2573. w.webContents.once('preload-error', (event, preloadPath, error) => {
  2574. throw error;
  2575. });
  2576. process.env.sandboxmain = 'foo';
  2577. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2578. const [, test] = await emittedOnce(ipcMain, 'answer');
  2579. expect(test.hasCrash).to.be.true('has crash');
  2580. expect(test.hasHang).to.be.true('has hang');
  2581. expect(test.heapStatistics).to.be.an('object');
  2582. expect(test.blinkMemoryInfo).to.be.an('object');
  2583. expect(test.processMemoryInfo).to.be.an('object');
  2584. expect(test.systemVersion).to.be.a('string');
  2585. expect(test.cpuUsage).to.be.an('object');
  2586. expect(test.ioCounters).to.be.an('object');
  2587. expect(test.uptime).to.be.a('number');
  2588. expect(test.arch).to.equal(process.arch);
  2589. expect(test.platform).to.equal(process.platform);
  2590. expect(test.env).to.deep.equal(process.env);
  2591. expect(test.execPath).to.equal(process.helperExecPath);
  2592. expect(test.sandboxed).to.be.true('sandboxed');
  2593. expect(test.contextIsolated).to.be.false('contextIsolated');
  2594. expect(test.type).to.equal('renderer');
  2595. expect(test.version).to.equal(process.version);
  2596. expect(test.versions).to.deep.equal(process.versions);
  2597. expect(test.contextId).to.be.a('string');
  2598. if (process.platform === 'linux' && test.osSandbox) {
  2599. expect(test.creationTime).to.be.null('creation time');
  2600. expect(test.systemMemoryInfo).to.be.null('system memory info');
  2601. } else {
  2602. expect(test.creationTime).to.be.a('number');
  2603. expect(test.systemMemoryInfo).to.be.an('object');
  2604. }
  2605. });
  2606. it('webview in sandbox renderer', async () => {
  2607. const w = new BrowserWindow({
  2608. show: false,
  2609. webPreferences: {
  2610. sandbox: true,
  2611. preload,
  2612. webviewTag: true,
  2613. contextIsolation: false
  2614. }
  2615. });
  2616. const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
  2617. const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready');
  2618. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  2619. const [, webContents] = await didAttachWebview;
  2620. const [, id] = await webviewDomReady;
  2621. expect(webContents.id).to.equal(id);
  2622. });
  2623. });
  2624. describe('nativeWindowOpen option', () => {
  2625. let w: BrowserWindow = null as unknown as BrowserWindow;
  2626. beforeEach(() => {
  2627. w = new BrowserWindow({
  2628. show: false,
  2629. webPreferences: {
  2630. nodeIntegration: true,
  2631. nativeWindowOpen: true,
  2632. // tests relies on preloads in opened windows
  2633. nodeIntegrationInSubFrames: true,
  2634. contextIsolation: false
  2635. }
  2636. });
  2637. });
  2638. it('opens window of about:blank with cross-scripting enabled', async () => {
  2639. const answer = emittedOnce(ipcMain, 'answer');
  2640. w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
  2641. const [, content] = await answer;
  2642. expect(content).to.equal('Hello');
  2643. });
  2644. it('opens window of same domain with cross-scripting enabled', async () => {
  2645. const answer = emittedOnce(ipcMain, 'answer');
  2646. w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
  2647. const [, content] = await answer;
  2648. expect(content).to.equal('Hello');
  2649. });
  2650. it('blocks accessing cross-origin frames', async () => {
  2651. const answer = emittedOnce(ipcMain, 'answer');
  2652. w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
  2653. const [, content] = await answer;
  2654. expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
  2655. });
  2656. it('opens window from <iframe> tags', async () => {
  2657. const answer = emittedOnce(ipcMain, 'answer');
  2658. w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
  2659. const [, content] = await answer;
  2660. expect(content).to.equal('Hello');
  2661. });
  2662. ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
  2663. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
  2664. {
  2665. const [, content] = await emittedOnce(ipcMain, 'answer');
  2666. expect(content).to.equal('function');
  2667. }
  2668. w.reload();
  2669. {
  2670. const [, content] = await emittedOnce(ipcMain, 'answer');
  2671. expect(content).to.equal('function');
  2672. }
  2673. });
  2674. it('<webview> works in a scriptable popup', async () => {
  2675. const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
  2676. const w = new BrowserWindow({
  2677. show: false,
  2678. webPreferences: {
  2679. nodeIntegrationInSubFrames: true,
  2680. nativeWindowOpen: true,
  2681. webviewTag: true,
  2682. contextIsolation: false,
  2683. preload
  2684. }
  2685. });
  2686. w.webContents.setWindowOpenHandler(() => ({
  2687. action: 'allow',
  2688. overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nativeWindowOpen: true, nodeIntegrationInSubFrames: true } }
  2689. }));
  2690. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2691. options.show = false;
  2692. });
  2693. const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded');
  2694. w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
  2695. await webviewLoaded;
  2696. });
  2697. it('should inherit the nativeWindowOpen setting in opened windows', async () => {
  2698. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2699. w.webContents.setWindowOpenHandler(() => ({
  2700. action: 'allow',
  2701. overrideBrowserWindowOptions: {
  2702. webPreferences: {
  2703. preload: preloadPath
  2704. }
  2705. }
  2706. }));
  2707. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2708. const [, { nativeWindowOpen }] = await emittedOnce(ipcMain, 'answer');
  2709. expect(nativeWindowOpen).to.be.true();
  2710. });
  2711. it('should open windows with the options configured via new-window event listeners', async () => {
  2712. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2713. w.webContents.setWindowOpenHandler(() => ({
  2714. action: 'allow',
  2715. overrideBrowserWindowOptions: {
  2716. webPreferences: {
  2717. preload: preloadPath,
  2718. contextIsolation: false
  2719. }
  2720. }
  2721. }));
  2722. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2723. const [[, childWebContents]] = await Promise.all([
  2724. emittedOnce(app, 'web-contents-created'),
  2725. emittedOnce(ipcMain, 'answer')
  2726. ]);
  2727. const webPreferences = childWebContents.getLastWebPreferences();
  2728. expect(webPreferences.contextIsolation).to.equal(false);
  2729. });
  2730. describe('window.location', () => {
  2731. const protocols = [
  2732. ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
  2733. ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
  2734. ];
  2735. beforeEach(() => {
  2736. for (const [scheme, path] of protocols) {
  2737. protocol.registerBufferProtocol(scheme, (request, callback) => {
  2738. callback({
  2739. mimeType: 'text/html',
  2740. data: fs.readFileSync(path)
  2741. });
  2742. });
  2743. }
  2744. });
  2745. afterEach(() => {
  2746. for (const [scheme] of protocols) {
  2747. protocol.unregisterProtocol(scheme);
  2748. }
  2749. });
  2750. it('retains the original web preferences when window.location is changed to a new origin', async () => {
  2751. const w = new BrowserWindow({
  2752. show: false,
  2753. webPreferences: {
  2754. nativeWindowOpen: true,
  2755. // test relies on preloads in opened window
  2756. nodeIntegrationInSubFrames: true,
  2757. contextIsolation: false
  2758. }
  2759. });
  2760. w.webContents.setWindowOpenHandler(() => ({
  2761. action: 'allow',
  2762. overrideBrowserWindowOptions: {
  2763. webPreferences: {
  2764. preload: path.join(fixtures, 'api', 'window-open-preload.js'),
  2765. contextIsolation: false,
  2766. nodeIntegrationInSubFrames: true
  2767. }
  2768. }
  2769. }));
  2770. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  2771. const [, { nodeIntegration, nativeWindowOpen, typeofProcess }] = await emittedOnce(ipcMain, 'answer');
  2772. expect(nodeIntegration).to.be.false();
  2773. expect(nativeWindowOpen).to.be.true();
  2774. expect(typeofProcess).to.eql('undefined');
  2775. });
  2776. it('window.opener is not null when window.location is changed to a new origin', async () => {
  2777. const w = new BrowserWindow({
  2778. show: false,
  2779. webPreferences: {
  2780. nativeWindowOpen: true,
  2781. // test relies on preloads in opened window
  2782. nodeIntegrationInSubFrames: true
  2783. }
  2784. });
  2785. w.webContents.setWindowOpenHandler(() => ({
  2786. action: 'allow',
  2787. overrideBrowserWindowOptions: {
  2788. webPreferences: {
  2789. preload: path.join(fixtures, 'api', 'window-open-preload.js')
  2790. }
  2791. }
  2792. }));
  2793. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  2794. const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer');
  2795. expect(windowOpenerIsNull).to.be.false('window.opener is null');
  2796. });
  2797. });
  2798. });
  2799. describe('"disableHtmlFullscreenWindowResize" option', () => {
  2800. it('prevents window from resizing when set', async () => {
  2801. const w = new BrowserWindow({
  2802. show: false,
  2803. webPreferences: {
  2804. disableHtmlFullscreenWindowResize: true
  2805. }
  2806. });
  2807. await w.loadURL('about:blank');
  2808. const size = w.getSize();
  2809. const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen');
  2810. w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  2811. await enterHtmlFullScreen;
  2812. expect(w.getSize()).to.deep.equal(size);
  2813. });
  2814. });
  2815. });
  2816. describe('nativeWindowOpen + contextIsolation options', () => {
  2817. afterEach(closeAllWindows);
  2818. it('opens window with cross-scripting enabled from isolated context', async () => {
  2819. const w = new BrowserWindow({
  2820. show: false,
  2821. webPreferences: {
  2822. nativeWindowOpen: true,
  2823. contextIsolation: true,
  2824. preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
  2825. }
  2826. });
  2827. w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
  2828. const [, content] = await emittedOnce(ipcMain, 'answer');
  2829. expect(content).to.equal('Hello');
  2830. });
  2831. });
  2832. describe('beforeunload handler', function () {
  2833. let w: BrowserWindow = null as unknown as BrowserWindow;
  2834. beforeEach(() => {
  2835. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  2836. });
  2837. afterEach(closeAllWindows);
  2838. it('returning undefined would not prevent close', async () => {
  2839. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  2840. const wait = emittedOnce(w, 'closed');
  2841. w.close();
  2842. await wait;
  2843. });
  2844. it('returning false would prevent close', async () => {
  2845. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  2846. w.close();
  2847. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  2848. expect(proceed).to.equal(false);
  2849. });
  2850. it('returning empty string would prevent close', async () => {
  2851. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
  2852. w.close();
  2853. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  2854. expect(proceed).to.equal(false);
  2855. });
  2856. it('emits for each close attempt', async () => {
  2857. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2858. const destroyListener = () => { expect.fail('Close was not prevented'); };
  2859. w.webContents.once('destroyed', destroyListener);
  2860. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2861. // The renderer needs to report the status of beforeunload handler
  2862. // back to main process, so wait for next console message, which means
  2863. // the SuddenTerminationStatus message have been flushed.
  2864. await emittedOnce(w.webContents, 'console-message');
  2865. w.close();
  2866. await emittedOnce(w.webContents, 'before-unload-fired');
  2867. w.close();
  2868. await emittedOnce(w.webContents, 'before-unload-fired');
  2869. w.webContents.removeListener('destroyed', destroyListener);
  2870. const wait = emittedOnce(w, 'closed');
  2871. w.close();
  2872. await wait;
  2873. });
  2874. it('emits for each reload attempt', async () => {
  2875. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2876. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  2877. w.webContents.once('did-start-navigation', navigationListener);
  2878. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2879. // The renderer needs to report the status of beforeunload handler
  2880. // back to main process, so wait for next console message, which means
  2881. // the SuddenTerminationStatus message have been flushed.
  2882. await emittedOnce(w.webContents, 'console-message');
  2883. w.reload();
  2884. // Chromium does not emit 'before-unload-fired' on WebContents for
  2885. // navigations, so we have to use other ways to know if beforeunload
  2886. // is fired.
  2887. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2888. w.reload();
  2889. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2890. w.webContents.removeListener('did-start-navigation', navigationListener);
  2891. w.reload();
  2892. await emittedOnce(w.webContents, 'did-finish-load');
  2893. });
  2894. it('emits for each navigation attempt', async () => {
  2895. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2896. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  2897. w.webContents.once('did-start-navigation', navigationListener);
  2898. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2899. // The renderer needs to report the status of beforeunload handler
  2900. // back to main process, so wait for next console message, which means
  2901. // the SuddenTerminationStatus message have been flushed.
  2902. await emittedOnce(w.webContents, 'console-message');
  2903. w.loadURL('about:blank');
  2904. // Chromium does not emit 'before-unload-fired' on WebContents for
  2905. // navigations, so we have to use other ways to know if beforeunload
  2906. // is fired.
  2907. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2908. w.loadURL('about:blank');
  2909. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2910. w.webContents.removeListener('did-start-navigation', navigationListener);
  2911. await w.loadURL('about:blank');
  2912. });
  2913. });
  2914. describe('document.visibilityState/hidden', () => {
  2915. afterEach(closeAllWindows);
  2916. it('visibilityState is initially visible despite window being hidden', async () => {
  2917. const w = new BrowserWindow({
  2918. show: false,
  2919. width: 100,
  2920. height: 100,
  2921. webPreferences: {
  2922. nodeIntegration: true,
  2923. contextIsolation: false
  2924. }
  2925. });
  2926. let readyToShow = false;
  2927. w.once('ready-to-show', () => {
  2928. readyToShow = true;
  2929. });
  2930. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2931. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2932. expect(readyToShow).to.be.false('ready to show');
  2933. expect(visibilityState).to.equal('visible');
  2934. expect(hidden).to.be.false('hidden');
  2935. });
  2936. // TODO(nornagon): figure out why this is failing on windows
  2937. ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
  2938. const w = new BrowserWindow({
  2939. width: 100,
  2940. height: 100,
  2941. webPreferences: {
  2942. nodeIntegration: true,
  2943. contextIsolation: false
  2944. }
  2945. });
  2946. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2947. {
  2948. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2949. expect(visibilityState).to.equal('visible');
  2950. expect(hidden).to.be.false('hidden');
  2951. }
  2952. w.hide();
  2953. {
  2954. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2955. expect(visibilityState).to.equal('hidden');
  2956. expect(hidden).to.be.true('hidden');
  2957. }
  2958. });
  2959. // TODO(nornagon): figure out why this is failing on windows
  2960. ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
  2961. const w = new BrowserWindow({
  2962. width: 100,
  2963. height: 100,
  2964. webPreferences: {
  2965. nodeIntegration: true,
  2966. contextIsolation: false
  2967. }
  2968. });
  2969. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2970. if (process.platform === 'darwin') {
  2971. // See https://github.com/electron/electron/issues/8664
  2972. await emittedOnce(w, 'show');
  2973. }
  2974. w.hide();
  2975. w.show();
  2976. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  2977. expect(visibilityState).to.equal('visible');
  2978. });
  2979. ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
  2980. const w = new BrowserWindow({
  2981. width: 100,
  2982. height: 100,
  2983. webPreferences: {
  2984. nodeIntegration: true,
  2985. contextIsolation: false
  2986. }
  2987. });
  2988. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2989. if (process.platform === 'darwin') {
  2990. // See https://github.com/electron/electron/issues/8664
  2991. await emittedOnce(w, 'show');
  2992. }
  2993. w.hide();
  2994. w.showInactive();
  2995. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  2996. expect(visibilityState).to.equal('visible');
  2997. });
  2998. // TODO(nornagon): figure out why this is failing on windows
  2999. ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
  3000. const w = new BrowserWindow({
  3001. width: 100,
  3002. height: 100,
  3003. webPreferences: {
  3004. nodeIntegration: true,
  3005. contextIsolation: false
  3006. }
  3007. });
  3008. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3009. {
  3010. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3011. expect(visibilityState).to.equal('visible');
  3012. expect(hidden).to.be.false('hidden');
  3013. }
  3014. w.minimize();
  3015. {
  3016. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3017. expect(visibilityState).to.equal('hidden');
  3018. expect(hidden).to.be.true('hidden');
  3019. }
  3020. });
  3021. // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
  3022. // when we introduced the compositor recycling patch. Should figure out how to fix this
  3023. it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => {
  3024. const w = new BrowserWindow({
  3025. show: false,
  3026. width: 100,
  3027. height: 100,
  3028. webPreferences: {
  3029. backgroundThrottling: false,
  3030. nodeIntegration: true
  3031. }
  3032. });
  3033. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  3034. {
  3035. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  3036. expect(visibilityState).to.equal('visible');
  3037. expect(hidden).to.be.false('hidden');
  3038. }
  3039. ipcMain.once('pong', (event, visibilityState, hidden) => {
  3040. throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
  3041. });
  3042. try {
  3043. const shown1 = emittedOnce(w, 'show');
  3044. w.show();
  3045. await shown1;
  3046. const hidden = emittedOnce(w, 'hide');
  3047. w.hide();
  3048. await hidden;
  3049. const shown2 = emittedOnce(w, 'show');
  3050. w.show();
  3051. await shown2;
  3052. } finally {
  3053. ipcMain.removeAllListeners('pong');
  3054. }
  3055. });
  3056. });
  3057. describe('new-window event', () => {
  3058. afterEach(closeAllWindows);
  3059. it('emits when window.open is called', (done) => {
  3060. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  3061. w.webContents.once('new-window', (e, url, frameName, disposition, options) => {
  3062. e.preventDefault();
  3063. try {
  3064. expect(url).to.equal('http://host/');
  3065. expect(frameName).to.equal('host');
  3066. expect((options as any)['this-is-not-a-standard-feature']).to.equal(true);
  3067. done();
  3068. } catch (e) {
  3069. done(e);
  3070. }
  3071. });
  3072. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  3073. });
  3074. it('emits when window.open is called with no webPreferences', (done) => {
  3075. const w = new BrowserWindow({ show: false });
  3076. w.webContents.once('new-window', function (e, url, frameName, disposition, options) {
  3077. e.preventDefault();
  3078. try {
  3079. expect(url).to.equal('http://host/');
  3080. expect(frameName).to.equal('host');
  3081. expect((options as any)['this-is-not-a-standard-feature']).to.equal(true);
  3082. done();
  3083. } catch (e) {
  3084. done(e);
  3085. }
  3086. });
  3087. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  3088. });
  3089. it('emits when link with target is called', (done) => {
  3090. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  3091. w.webContents.once('new-window', (e, url, frameName) => {
  3092. e.preventDefault();
  3093. try {
  3094. expect(url).to.equal('http://host/');
  3095. expect(frameName).to.equal('target');
  3096. done();
  3097. } catch (e) {
  3098. done(e);
  3099. }
  3100. });
  3101. w.loadFile(path.join(fixtures, 'pages', 'target-name.html'));
  3102. });
  3103. it('includes all properties', async () => {
  3104. const w = new BrowserWindow({ show: false });
  3105. const p = new Promise<{
  3106. url: string,
  3107. frameName: string,
  3108. disposition: string,
  3109. options: BrowserWindowConstructorOptions,
  3110. additionalFeatures: string[],
  3111. referrer: Electron.Referrer,
  3112. postBody: Electron.PostBody
  3113. }>((resolve) => {
  3114. w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => {
  3115. e.preventDefault();
  3116. resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody });
  3117. });
  3118. });
  3119. w.loadURL(`data:text/html,${encodeURIComponent(`
  3120. <form target="_blank" method="POST" id="form" action="http://example.com/test">
  3121. <input type="text" name="post-test-key" value="post-test-value"></input>
  3122. </form>
  3123. <script>form.submit()</script>
  3124. `)}`);
  3125. const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p;
  3126. expect(url).to.equal('http://example.com/test');
  3127. expect(frameName).to.equal('');
  3128. expect(disposition).to.equal('foreground-tab');
  3129. expect(options).to.be.an('object').not.null();
  3130. expect(referrer.policy).to.equal('strict-origin-when-cross-origin');
  3131. expect(referrer.url).to.equal('');
  3132. expect(additionalFeatures).to.deep.equal([]);
  3133. expect(postBody.data).to.have.length(1);
  3134. expect(postBody.data[0].type).to.equal('rawData');
  3135. expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value'));
  3136. expect(postBody.contentType).to.equal('application/x-www-form-urlencoded');
  3137. });
  3138. });
  3139. ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
  3140. afterEach(closeAllWindows);
  3141. it('emits an event when window is maximized', async () => {
  3142. const w = new BrowserWindow({ show: false });
  3143. const maximize = emittedOnce(w, 'maximize');
  3144. w.show();
  3145. w.maximize();
  3146. await maximize;
  3147. });
  3148. it('emits an event when a transparent window is maximized', async () => {
  3149. const w = new BrowserWindow({
  3150. show: false,
  3151. frame: false,
  3152. transparent: true
  3153. });
  3154. const maximize = emittedOnce(w, 'maximize');
  3155. w.show();
  3156. w.maximize();
  3157. await maximize;
  3158. });
  3159. it('emits only one event when frameless window is maximized', () => {
  3160. const w = new BrowserWindow({ show: false, frame: false });
  3161. let emitted = 0;
  3162. w.on('maximize', () => emitted++);
  3163. w.show();
  3164. w.maximize();
  3165. expect(emitted).to.equal(1);
  3166. });
  3167. it('emits an event when window is unmaximized', async () => {
  3168. const w = new BrowserWindow({ show: false });
  3169. const unmaximize = emittedOnce(w, 'unmaximize');
  3170. w.show();
  3171. w.maximize();
  3172. w.unmaximize();
  3173. await unmaximize;
  3174. });
  3175. it('emits an event when a transparent window is unmaximized', async () => {
  3176. const w = new BrowserWindow({
  3177. show: false,
  3178. frame: false,
  3179. transparent: true
  3180. });
  3181. const maximize = emittedOnce(w, 'maximize');
  3182. const unmaximize = emittedOnce(w, 'unmaximize');
  3183. w.show();
  3184. w.maximize();
  3185. await maximize;
  3186. w.unmaximize();
  3187. await unmaximize;
  3188. });
  3189. it('emits an event when window is minimized', async () => {
  3190. const w = new BrowserWindow({ show: false });
  3191. const minimize = emittedOnce(w, 'minimize');
  3192. w.show();
  3193. w.minimize();
  3194. await minimize;
  3195. });
  3196. });
  3197. describe('beginFrameSubscription method', () => {
  3198. it('does not crash when callback returns nothing', (done) => {
  3199. const w = new BrowserWindow({ show: false });
  3200. let called = false;
  3201. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3202. w.webContents.on('dom-ready', () => {
  3203. w.webContents.beginFrameSubscription(function () {
  3204. // This callback might be called twice.
  3205. if (called) return;
  3206. called = true;
  3207. // Pending endFrameSubscription to next tick can reliably reproduce
  3208. // a crash which happens when nothing is returned in the callback.
  3209. setTimeout(() => {
  3210. w.webContents.endFrameSubscription();
  3211. done();
  3212. });
  3213. });
  3214. });
  3215. });
  3216. it('subscribes to frame updates', (done) => {
  3217. const w = new BrowserWindow({ show: false });
  3218. let called = false;
  3219. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3220. w.webContents.on('dom-ready', () => {
  3221. w.webContents.beginFrameSubscription(function (data) {
  3222. // This callback might be called twice.
  3223. if (called) return;
  3224. called = true;
  3225. try {
  3226. expect(data.constructor.name).to.equal('NativeImage');
  3227. expect(data.isEmpty()).to.be.false('data is empty');
  3228. done();
  3229. } catch (e) {
  3230. done(e);
  3231. } finally {
  3232. w.webContents.endFrameSubscription();
  3233. }
  3234. });
  3235. });
  3236. });
  3237. it('subscribes to frame updates (only dirty rectangle)', (done) => {
  3238. const w = new BrowserWindow({ show: false });
  3239. let called = false;
  3240. let gotInitialFullSizeFrame = false;
  3241. const [contentWidth, contentHeight] = w.getContentSize();
  3242. w.webContents.on('did-finish-load', () => {
  3243. w.webContents.beginFrameSubscription(true, (image, rect) => {
  3244. if (image.isEmpty()) {
  3245. // Chromium sometimes sends a 0x0 frame at the beginning of the
  3246. // page load.
  3247. return;
  3248. }
  3249. if (rect.height === contentHeight && rect.width === contentWidth &&
  3250. !gotInitialFullSizeFrame) {
  3251. // The initial frame is full-size, but we're looking for a call
  3252. // with just the dirty-rect. The next frame should be a smaller
  3253. // rect.
  3254. gotInitialFullSizeFrame = true;
  3255. return;
  3256. }
  3257. // This callback might be called twice.
  3258. if (called) return;
  3259. // We asked for just the dirty rectangle, so we expect to receive a
  3260. // rect smaller than the full size.
  3261. // TODO(jeremy): this is failing on windows currently; investigate.
  3262. // assert(rect.width < contentWidth || rect.height < contentHeight)
  3263. called = true;
  3264. try {
  3265. const expectedSize = rect.width * rect.height * 4;
  3266. expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
  3267. done();
  3268. } catch (e) {
  3269. done(e);
  3270. } finally {
  3271. w.webContents.endFrameSubscription();
  3272. }
  3273. });
  3274. });
  3275. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  3276. });
  3277. it('throws error when subscriber is not well defined', () => {
  3278. const w = new BrowserWindow({ show: false });
  3279. expect(() => {
  3280. w.webContents.beginFrameSubscription(true, true as any);
  3281. // TODO(zcbenz): gin is weak at guessing parameter types, we should
  3282. // upstream native_mate's implementation to gin.
  3283. }).to.throw('Error processing argument at index 1, conversion failure from ');
  3284. });
  3285. });
  3286. describe('savePage method', () => {
  3287. const savePageDir = path.join(fixtures, 'save_page');
  3288. const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
  3289. const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
  3290. const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
  3291. afterEach(() => {
  3292. closeAllWindows();
  3293. try {
  3294. fs.unlinkSync(savePageCssPath);
  3295. fs.unlinkSync(savePageJsPath);
  3296. fs.unlinkSync(savePageHtmlPath);
  3297. fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
  3298. fs.rmdirSync(savePageDir);
  3299. } catch {}
  3300. });
  3301. it('should throw when passing relative paths', async () => {
  3302. const w = new BrowserWindow({ show: false });
  3303. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3304. await expect(
  3305. w.webContents.savePage('save_page.html', 'HTMLComplete')
  3306. ).to.eventually.be.rejectedWith('Path must be absolute');
  3307. await expect(
  3308. w.webContents.savePage('save_page.html', 'HTMLOnly')
  3309. ).to.eventually.be.rejectedWith('Path must be absolute');
  3310. await expect(
  3311. w.webContents.savePage('save_page.html', 'MHTML')
  3312. ).to.eventually.be.rejectedWith('Path must be absolute');
  3313. });
  3314. it('should save page to disk with HTMLOnly', async () => {
  3315. const w = new BrowserWindow({ show: false });
  3316. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3317. await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly');
  3318. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3319. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  3320. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  3321. });
  3322. it('should save page to disk with MHTML', async () => {
  3323. const w = new BrowserWindow({ show: false });
  3324. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3325. await w.webContents.savePage(savePageHtmlPath, 'MHTML');
  3326. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3327. expect(fs.existsSync(savePageJsPath)).to.be.false('js path');
  3328. expect(fs.existsSync(savePageCssPath)).to.be.false('css path');
  3329. });
  3330. it('should save page to disk with HTMLComplete', async () => {
  3331. const w = new BrowserWindow({ show: false });
  3332. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  3333. await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
  3334. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  3335. expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
  3336. expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
  3337. });
  3338. });
  3339. describe('BrowserWindow options argument is optional', () => {
  3340. afterEach(closeAllWindows);
  3341. it('should create a window with default size (800x600)', () => {
  3342. const w = new BrowserWindow();
  3343. expect(w.getSize()).to.deep.equal([800, 600]);
  3344. });
  3345. });
  3346. describe('BrowserWindow.restore()', () => {
  3347. afterEach(closeAllWindows);
  3348. it('should restore the previous window size', () => {
  3349. const w = new BrowserWindow({
  3350. minWidth: 800,
  3351. width: 800
  3352. });
  3353. const initialSize = w.getSize();
  3354. w.minimize();
  3355. w.restore();
  3356. expectBoundsEqual(w.getSize(), initialSize);
  3357. });
  3358. it('does not crash when restoring hidden minimized window', () => {
  3359. const w = new BrowserWindow({});
  3360. w.minimize();
  3361. w.hide();
  3362. w.show();
  3363. });
  3364. });
  3365. // TODO(dsanders11): Enable once maximize event works on Linux again on CI
  3366. ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => {
  3367. afterEach(closeAllWindows);
  3368. it('should show the window if it is not currently shown', async () => {
  3369. const w = new BrowserWindow({ show: false });
  3370. const hidden = emittedOnce(w, 'hide');
  3371. let shown = emittedOnce(w, 'show');
  3372. const maximize = emittedOnce(w, 'maximize');
  3373. expect(w.isVisible()).to.be.false('visible');
  3374. w.maximize();
  3375. await maximize;
  3376. await shown;
  3377. expect(w.isMaximized()).to.be.true('maximized');
  3378. expect(w.isVisible()).to.be.true('visible');
  3379. // Even if the window is already maximized
  3380. w.hide();
  3381. await hidden;
  3382. expect(w.isVisible()).to.be.false('visible');
  3383. shown = emittedOnce(w, 'show');
  3384. w.maximize();
  3385. await shown;
  3386. expect(w.isVisible()).to.be.true('visible');
  3387. });
  3388. });
  3389. describe('BrowserWindow.unmaximize()', () => {
  3390. afterEach(closeAllWindows);
  3391. it('should restore the previous window position', () => {
  3392. const w = new BrowserWindow();
  3393. const initialPosition = w.getPosition();
  3394. w.maximize();
  3395. w.unmaximize();
  3396. expectBoundsEqual(w.getPosition(), initialPosition);
  3397. });
  3398. // TODO(dsanders11): Enable once minimize event works on Linux again.
  3399. // See https://github.com/electron/electron/issues/28699
  3400. ifit(process.platform !== 'linux')('should not restore a minimized window', async () => {
  3401. const w = new BrowserWindow();
  3402. const minimize = emittedOnce(w, 'minimize');
  3403. w.minimize();
  3404. await minimize;
  3405. w.unmaximize();
  3406. await delay(1000);
  3407. expect(w.isMinimized()).to.be.true();
  3408. });
  3409. it('should not change the size or position of a normal window', async () => {
  3410. const w = new BrowserWindow();
  3411. const initialSize = w.getSize();
  3412. const initialPosition = w.getPosition();
  3413. w.unmaximize();
  3414. await delay(1000);
  3415. expectBoundsEqual(w.getSize(), initialSize);
  3416. expectBoundsEqual(w.getPosition(), initialPosition);
  3417. });
  3418. ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => {
  3419. const { workArea } = screen.getPrimaryDisplay();
  3420. const bounds = {
  3421. x: workArea.x,
  3422. y: workArea.y,
  3423. width: workArea.width,
  3424. height: workArea.height
  3425. };
  3426. const w = new BrowserWindow(bounds);
  3427. w.unmaximize();
  3428. await delay(1000);
  3429. expectBoundsEqual(w.getBounds(), bounds);
  3430. });
  3431. });
  3432. describe('setFullScreen(false)', () => {
  3433. afterEach(closeAllWindows);
  3434. // only applicable to windows: https://github.com/electron/electron/issues/6036
  3435. ifdescribe(process.platform === 'win32')('on windows', () => {
  3436. it('should restore a normal visible window from a fullscreen startup state', async () => {
  3437. const w = new BrowserWindow({ show: false });
  3438. await w.loadURL('about:blank');
  3439. const shown = emittedOnce(w, 'show');
  3440. // start fullscreen and hidden
  3441. w.setFullScreen(true);
  3442. w.show();
  3443. await shown;
  3444. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3445. w.setFullScreen(false);
  3446. await leftFullScreen;
  3447. expect(w.isVisible()).to.be.true('visible');
  3448. expect(w.isFullScreen()).to.be.false('fullscreen');
  3449. });
  3450. it('should keep window hidden if already in hidden state', async () => {
  3451. const w = new BrowserWindow({ show: false });
  3452. await w.loadURL('about:blank');
  3453. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  3454. w.setFullScreen(false);
  3455. await leftFullScreen;
  3456. expect(w.isVisible()).to.be.false('visible');
  3457. expect(w.isFullScreen()).to.be.false('fullscreen');
  3458. });
  3459. });
  3460. ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
  3461. it('exits HTML fullscreen when window leaves fullscreen', async () => {
  3462. const w = new BrowserWindow();
  3463. await w.loadURL('about:blank');
  3464. await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  3465. await emittedOnce(w, 'enter-full-screen');
  3466. // Wait a tick for the full-screen state to 'stick'
  3467. await delay();
  3468. w.setFullScreen(false);
  3469. await emittedOnce(w, 'leave-html-full-screen');
  3470. });
  3471. });
  3472. });
  3473. describe('parent window', () => {
  3474. afterEach(closeAllWindows);
  3475. ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => {
  3476. const w = new BrowserWindow();
  3477. const sheetBegin = emittedOnce(w, 'sheet-begin');
  3478. // eslint-disable-next-line no-new
  3479. new BrowserWindow({
  3480. modal: true,
  3481. parent: w
  3482. });
  3483. await sheetBegin;
  3484. });
  3485. ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => {
  3486. const w = new BrowserWindow();
  3487. const sheet = new BrowserWindow({
  3488. modal: true,
  3489. parent: w
  3490. });
  3491. const sheetEnd = emittedOnce(w, 'sheet-end');
  3492. sheet.close();
  3493. await sheetEnd;
  3494. });
  3495. describe('parent option', () => {
  3496. it('sets parent window', () => {
  3497. const w = new BrowserWindow({ show: false });
  3498. const c = new BrowserWindow({ show: false, parent: w });
  3499. expect(c.getParentWindow()).to.equal(w);
  3500. });
  3501. it('adds window to child windows of parent', () => {
  3502. const w = new BrowserWindow({ show: false });
  3503. const c = new BrowserWindow({ show: false, parent: w });
  3504. expect(w.getChildWindows()).to.deep.equal([c]);
  3505. });
  3506. it('removes from child windows of parent when window is closed', async () => {
  3507. const w = new BrowserWindow({ show: false });
  3508. const c = new BrowserWindow({ show: false, parent: w });
  3509. const closed = emittedOnce(c, 'closed');
  3510. c.close();
  3511. await closed;
  3512. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3513. await delay();
  3514. expect(w.getChildWindows().length).to.equal(0);
  3515. });
  3516. it('closes a grandchild window when a middle child window is destroyed', (done) => {
  3517. const w = new BrowserWindow();
  3518. w.loadFile(path.join(fixtures, 'pages', 'base-page.html'));
  3519. w.webContents.executeJavaScript('window.open("")');
  3520. w.webContents.on('did-create-window', async (window) => {
  3521. const childWindow = new BrowserWindow({ parent: window });
  3522. await delay();
  3523. window.close();
  3524. childWindow.on('closed', () => {
  3525. expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw();
  3526. done();
  3527. });
  3528. });
  3529. });
  3530. it('should not affect the show option', () => {
  3531. const w = new BrowserWindow({ show: false });
  3532. const c = new BrowserWindow({ show: false, parent: w });
  3533. expect(c.isVisible()).to.be.false('child is visible');
  3534. expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible');
  3535. });
  3536. });
  3537. describe('win.setParentWindow(parent)', () => {
  3538. it('sets parent window', () => {
  3539. const w = new BrowserWindow({ show: false });
  3540. const c = new BrowserWindow({ show: false });
  3541. expect(w.getParentWindow()).to.be.null('w.parent');
  3542. expect(c.getParentWindow()).to.be.null('c.parent');
  3543. c.setParentWindow(w);
  3544. expect(c.getParentWindow()).to.equal(w);
  3545. c.setParentWindow(null);
  3546. expect(c.getParentWindow()).to.be.null('c.parent');
  3547. });
  3548. it('adds window to child windows of parent', () => {
  3549. const w = new BrowserWindow({ show: false });
  3550. const c = new BrowserWindow({ show: false });
  3551. expect(w.getChildWindows()).to.deep.equal([]);
  3552. c.setParentWindow(w);
  3553. expect(w.getChildWindows()).to.deep.equal([c]);
  3554. c.setParentWindow(null);
  3555. expect(w.getChildWindows()).to.deep.equal([]);
  3556. });
  3557. it('removes from child windows of parent when window is closed', async () => {
  3558. const w = new BrowserWindow({ show: false });
  3559. const c = new BrowserWindow({ show: false });
  3560. const closed = emittedOnce(c, 'closed');
  3561. c.setParentWindow(w);
  3562. c.close();
  3563. await closed;
  3564. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3565. await delay();
  3566. expect(w.getChildWindows().length).to.equal(0);
  3567. });
  3568. });
  3569. describe('modal option', () => {
  3570. it('does not freeze or crash', async () => {
  3571. const parentWindow = new BrowserWindow();
  3572. const createTwo = async () => {
  3573. const two = new BrowserWindow({
  3574. width: 300,
  3575. height: 200,
  3576. parent: parentWindow,
  3577. modal: true,
  3578. show: false
  3579. });
  3580. const twoShown = emittedOnce(two, 'show');
  3581. two.show();
  3582. await twoShown;
  3583. setTimeout(() => two.close(), 500);
  3584. await emittedOnce(two, 'closed');
  3585. };
  3586. const one = new BrowserWindow({
  3587. width: 600,
  3588. height: 400,
  3589. parent: parentWindow,
  3590. modal: true,
  3591. show: false
  3592. });
  3593. const oneShown = emittedOnce(one, 'show');
  3594. one.show();
  3595. await oneShown;
  3596. setTimeout(() => one.destroy(), 500);
  3597. await emittedOnce(one, 'closed');
  3598. await createTwo();
  3599. });
  3600. ifit(process.platform !== 'darwin')('disables parent window', () => {
  3601. const w = new BrowserWindow({ show: false });
  3602. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3603. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3604. c.show();
  3605. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3606. });
  3607. ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
  3608. const w = new BrowserWindow({ show: false });
  3609. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3610. const closed = emittedOnce(c, 'closed');
  3611. c.show();
  3612. c.close();
  3613. await closed;
  3614. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3615. });
  3616. ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
  3617. const w = new BrowserWindow({ show: false });
  3618. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3619. const closed = emittedOnce(c, 'closed');
  3620. w.setEnabled(false);
  3621. c.show();
  3622. c.close();
  3623. await closed;
  3624. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3625. });
  3626. ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
  3627. const w = new BrowserWindow({ show: false });
  3628. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3629. const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
  3630. c.show();
  3631. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3632. c2.show();
  3633. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3634. c.destroy();
  3635. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3636. c2.destroy();
  3637. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3638. });
  3639. });
  3640. });
  3641. describe('window states', () => {
  3642. afterEach(closeAllWindows);
  3643. it('does not resize frameless windows when states change', () => {
  3644. const w = new BrowserWindow({
  3645. frame: false,
  3646. width: 300,
  3647. height: 200,
  3648. show: false
  3649. });
  3650. w.minimizable = false;
  3651. w.minimizable = true;
  3652. expect(w.getSize()).to.deep.equal([300, 200]);
  3653. w.resizable = false;
  3654. w.resizable = true;
  3655. expect(w.getSize()).to.deep.equal([300, 200]);
  3656. w.maximizable = false;
  3657. w.maximizable = true;
  3658. expect(w.getSize()).to.deep.equal([300, 200]);
  3659. w.fullScreenable = false;
  3660. w.fullScreenable = true;
  3661. expect(w.getSize()).to.deep.equal([300, 200]);
  3662. w.closable = false;
  3663. w.closable = true;
  3664. expect(w.getSize()).to.deep.equal([300, 200]);
  3665. });
  3666. describe('resizable state', () => {
  3667. it('with properties', () => {
  3668. it('can be set with resizable constructor option', () => {
  3669. const w = new BrowserWindow({ show: false, resizable: false });
  3670. expect(w.resizable).to.be.false('resizable');
  3671. if (process.platform === 'darwin') {
  3672. expect(w.maximizable).to.to.true('maximizable');
  3673. }
  3674. });
  3675. it('can be changed', () => {
  3676. const w = new BrowserWindow({ show: false });
  3677. expect(w.resizable).to.be.true('resizable');
  3678. w.resizable = false;
  3679. expect(w.resizable).to.be.false('resizable');
  3680. w.resizable = true;
  3681. expect(w.resizable).to.be.true('resizable');
  3682. });
  3683. });
  3684. it('with functions', () => {
  3685. it('can be set with resizable constructor option', () => {
  3686. const w = new BrowserWindow({ show: false, resizable: false });
  3687. expect(w.isResizable()).to.be.false('resizable');
  3688. if (process.platform === 'darwin') {
  3689. expect(w.isMaximizable()).to.to.true('maximizable');
  3690. }
  3691. });
  3692. it('can be changed', () => {
  3693. const w = new BrowserWindow({ show: false });
  3694. expect(w.isResizable()).to.be.true('resizable');
  3695. w.setResizable(false);
  3696. expect(w.isResizable()).to.be.false('resizable');
  3697. w.setResizable(true);
  3698. expect(w.isResizable()).to.be.true('resizable');
  3699. });
  3700. });
  3701. it('works for a frameless window', () => {
  3702. const w = new BrowserWindow({ show: false, frame: false });
  3703. expect(w.resizable).to.be.true('resizable');
  3704. if (process.platform === 'win32') {
  3705. const w = new BrowserWindow({ show: false, thickFrame: false });
  3706. expect(w.resizable).to.be.false('resizable');
  3707. }
  3708. });
  3709. // On Linux there is no "resizable" property of a window.
  3710. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => {
  3711. const w = new BrowserWindow({ show: false });
  3712. expect(w.resizable).to.be.true('resizable');
  3713. expect(w.maximizable).to.be.true('maximizable');
  3714. w.resizable = false;
  3715. expect(w.maximizable).to.be.false('not maximizable');
  3716. w.resizable = true;
  3717. expect(w.maximizable).to.be.true('maximizable');
  3718. });
  3719. ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
  3720. const w = new BrowserWindow({
  3721. show: false,
  3722. frame: false,
  3723. resizable: false,
  3724. transparent: true
  3725. });
  3726. w.setContentSize(60, 60);
  3727. expectBoundsEqual(w.getContentSize(), [60, 60]);
  3728. w.setContentSize(30, 30);
  3729. expectBoundsEqual(w.getContentSize(), [30, 30]);
  3730. w.setContentSize(10, 10);
  3731. expectBoundsEqual(w.getContentSize(), [10, 10]);
  3732. });
  3733. });
  3734. describe('loading main frame state', () => {
  3735. let server: http.Server = null as unknown as http.Server;
  3736. let serverUrl: string = null as unknown as string;
  3737. before((done) => {
  3738. server = http.createServer((request, response) => {
  3739. response.end();
  3740. }).listen(0, '127.0.0.1', () => {
  3741. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  3742. done();
  3743. });
  3744. });
  3745. after(() => {
  3746. server.close();
  3747. });
  3748. it('is true when the main frame is loading', async () => {
  3749. const w = new BrowserWindow({ show: false });
  3750. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3751. w.webContents.loadURL(serverUrl);
  3752. await didStartLoading;
  3753. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3754. });
  3755. it('is false when only a subframe is loading', async () => {
  3756. const w = new BrowserWindow({ show: false });
  3757. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3758. w.webContents.loadURL(serverUrl);
  3759. await didStopLoading;
  3760. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3761. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3762. w.webContents.executeJavaScript(`
  3763. var iframe = document.createElement('iframe')
  3764. iframe.src = '${serverUrl}/page2'
  3765. document.body.appendChild(iframe)
  3766. `);
  3767. await didStartLoading;
  3768. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3769. });
  3770. it('is true when navigating to pages from the same origin', async () => {
  3771. const w = new BrowserWindow({ show: false });
  3772. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3773. w.webContents.loadURL(serverUrl);
  3774. await didStopLoading;
  3775. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3776. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3777. w.webContents.loadURL(`${serverUrl}/page2`);
  3778. await didStartLoading;
  3779. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3780. });
  3781. });
  3782. });
  3783. ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
  3784. // Not implemented on Linux.
  3785. afterEach(closeAllWindows);
  3786. describe('movable state', () => {
  3787. it('with properties', () => {
  3788. it('can be set with movable constructor option', () => {
  3789. const w = new BrowserWindow({ show: false, movable: false });
  3790. expect(w.movable).to.be.false('movable');
  3791. });
  3792. it('can be changed', () => {
  3793. const w = new BrowserWindow({ show: false });
  3794. expect(w.movable).to.be.true('movable');
  3795. w.movable = false;
  3796. expect(w.movable).to.be.false('movable');
  3797. w.movable = true;
  3798. expect(w.movable).to.be.true('movable');
  3799. });
  3800. });
  3801. it('with functions', () => {
  3802. it('can be set with movable constructor option', () => {
  3803. const w = new BrowserWindow({ show: false, movable: false });
  3804. expect(w.isMovable()).to.be.false('movable');
  3805. });
  3806. it('can be changed', () => {
  3807. const w = new BrowserWindow({ show: false });
  3808. expect(w.isMovable()).to.be.true('movable');
  3809. w.setMovable(false);
  3810. expect(w.isMovable()).to.be.false('movable');
  3811. w.setMovable(true);
  3812. expect(w.isMovable()).to.be.true('movable');
  3813. });
  3814. });
  3815. });
  3816. describe('visibleOnAllWorkspaces state', () => {
  3817. it('with properties', () => {
  3818. it('can be changed', () => {
  3819. const w = new BrowserWindow({ show: false });
  3820. expect(w.visibleOnAllWorkspaces).to.be.false();
  3821. w.visibleOnAllWorkspaces = true;
  3822. expect(w.visibleOnAllWorkspaces).to.be.true();
  3823. });
  3824. });
  3825. it('with functions', () => {
  3826. it('can be changed', () => {
  3827. const w = new BrowserWindow({ show: false });
  3828. expect(w.isVisibleOnAllWorkspaces()).to.be.false();
  3829. w.setVisibleOnAllWorkspaces(true);
  3830. expect(w.isVisibleOnAllWorkspaces()).to.be.true();
  3831. });
  3832. });
  3833. });
  3834. ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
  3835. it('with properties', () => {
  3836. it('can be changed', () => {
  3837. const w = new BrowserWindow({ show: false });
  3838. expect(w.documentEdited).to.be.false();
  3839. w.documentEdited = true;
  3840. expect(w.documentEdited).to.be.true();
  3841. });
  3842. });
  3843. it('with functions', () => {
  3844. it('can be changed', () => {
  3845. const w = new BrowserWindow({ show: false });
  3846. expect(w.isDocumentEdited()).to.be.false();
  3847. w.setDocumentEdited(true);
  3848. expect(w.isDocumentEdited()).to.be.true();
  3849. });
  3850. });
  3851. });
  3852. ifdescribe(process.platform === 'darwin')('representedFilename', () => {
  3853. it('with properties', () => {
  3854. it('can be changed', () => {
  3855. const w = new BrowserWindow({ show: false });
  3856. expect(w.representedFilename).to.eql('');
  3857. w.representedFilename = 'a name';
  3858. expect(w.representedFilename).to.eql('a name');
  3859. });
  3860. });
  3861. it('with functions', () => {
  3862. it('can be changed', () => {
  3863. const w = new BrowserWindow({ show: false });
  3864. expect(w.getRepresentedFilename()).to.eql('');
  3865. w.setRepresentedFilename('a name');
  3866. expect(w.getRepresentedFilename()).to.eql('a name');
  3867. });
  3868. });
  3869. });
  3870. describe('native window title', () => {
  3871. it('with properties', () => {
  3872. it('can be set with title constructor option', () => {
  3873. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  3874. expect(w.title).to.eql('mYtItLe');
  3875. });
  3876. it('can be changed', () => {
  3877. const w = new BrowserWindow({ show: false });
  3878. expect(w.title).to.eql('Electron Test Main');
  3879. w.title = 'NEW TITLE';
  3880. expect(w.title).to.eql('NEW TITLE');
  3881. });
  3882. });
  3883. it('with functions', () => {
  3884. it('can be set with minimizable constructor option', () => {
  3885. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  3886. expect(w.getTitle()).to.eql('mYtItLe');
  3887. });
  3888. it('can be changed', () => {
  3889. const w = new BrowserWindow({ show: false });
  3890. expect(w.getTitle()).to.eql('Electron Test Main');
  3891. w.setTitle('NEW TITLE');
  3892. expect(w.getTitle()).to.eql('NEW TITLE');
  3893. });
  3894. });
  3895. });
  3896. describe('minimizable state', () => {
  3897. it('with properties', () => {
  3898. it('can be set with minimizable constructor option', () => {
  3899. const w = new BrowserWindow({ show: false, minimizable: false });
  3900. expect(w.minimizable).to.be.false('minimizable');
  3901. });
  3902. it('can be changed', () => {
  3903. const w = new BrowserWindow({ show: false });
  3904. expect(w.minimizable).to.be.true('minimizable');
  3905. w.minimizable = false;
  3906. expect(w.minimizable).to.be.false('minimizable');
  3907. w.minimizable = true;
  3908. expect(w.minimizable).to.be.true('minimizable');
  3909. });
  3910. });
  3911. it('with functions', () => {
  3912. it('can be set with minimizable constructor option', () => {
  3913. const w = new BrowserWindow({ show: false, minimizable: false });
  3914. expect(w.isMinimizable()).to.be.false('movable');
  3915. });
  3916. it('can be changed', () => {
  3917. const w = new BrowserWindow({ show: false });
  3918. expect(w.isMinimizable()).to.be.true('isMinimizable');
  3919. w.setMinimizable(false);
  3920. expect(w.isMinimizable()).to.be.false('isMinimizable');
  3921. w.setMinimizable(true);
  3922. expect(w.isMinimizable()).to.be.true('isMinimizable');
  3923. });
  3924. });
  3925. });
  3926. describe('maximizable state (property)', () => {
  3927. it('with properties', () => {
  3928. it('can be set with maximizable constructor option', () => {
  3929. const w = new BrowserWindow({ show: false, maximizable: false });
  3930. expect(w.maximizable).to.be.false('maximizable');
  3931. });
  3932. it('can be changed', () => {
  3933. const w = new BrowserWindow({ show: false });
  3934. expect(w.maximizable).to.be.true('maximizable');
  3935. w.maximizable = false;
  3936. expect(w.maximizable).to.be.false('maximizable');
  3937. w.maximizable = true;
  3938. expect(w.maximizable).to.be.true('maximizable');
  3939. });
  3940. it('is not affected when changing other states', () => {
  3941. const w = new BrowserWindow({ show: false });
  3942. w.maximizable = false;
  3943. expect(w.maximizable).to.be.false('maximizable');
  3944. w.minimizable = false;
  3945. expect(w.maximizable).to.be.false('maximizable');
  3946. w.closable = false;
  3947. expect(w.maximizable).to.be.false('maximizable');
  3948. w.maximizable = true;
  3949. expect(w.maximizable).to.be.true('maximizable');
  3950. w.closable = true;
  3951. expect(w.maximizable).to.be.true('maximizable');
  3952. w.fullScreenable = false;
  3953. expect(w.maximizable).to.be.true('maximizable');
  3954. });
  3955. });
  3956. it('with functions', () => {
  3957. it('can be set with maximizable constructor option', () => {
  3958. const w = new BrowserWindow({ show: false, maximizable: false });
  3959. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3960. });
  3961. it('can be changed', () => {
  3962. const w = new BrowserWindow({ show: false });
  3963. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3964. w.setMaximizable(false);
  3965. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3966. w.setMaximizable(true);
  3967. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3968. });
  3969. it('is not affected when changing other states', () => {
  3970. const w = new BrowserWindow({ show: false });
  3971. w.setMaximizable(false);
  3972. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3973. w.setMinimizable(false);
  3974. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3975. w.setClosable(false);
  3976. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3977. w.setMaximizable(true);
  3978. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3979. w.setClosable(true);
  3980. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3981. w.setFullScreenable(false);
  3982. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3983. });
  3984. });
  3985. });
  3986. ifdescribe(process.platform === 'win32')('maximizable state', () => {
  3987. it('with properties', () => {
  3988. it('is reset to its former state', () => {
  3989. const w = new BrowserWindow({ show: false });
  3990. w.maximizable = false;
  3991. w.resizable = false;
  3992. w.resizable = true;
  3993. expect(w.maximizable).to.be.false('maximizable');
  3994. w.maximizable = true;
  3995. w.resizable = false;
  3996. w.resizable = true;
  3997. expect(w.maximizable).to.be.true('maximizable');
  3998. });
  3999. });
  4000. it('with functions', () => {
  4001. it('is reset to its former state', () => {
  4002. const w = new BrowserWindow({ show: false });
  4003. w.setMaximizable(false);
  4004. w.setResizable(false);
  4005. w.setResizable(true);
  4006. expect(w.isMaximizable()).to.be.false('isMaximizable');
  4007. w.setMaximizable(true);
  4008. w.setResizable(false);
  4009. w.setResizable(true);
  4010. expect(w.isMaximizable()).to.be.true('isMaximizable');
  4011. });
  4012. });
  4013. });
  4014. ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
  4015. describe('with properties', () => {
  4016. it('can be changed', () => {
  4017. const w = new BrowserWindow({ show: false });
  4018. expect(w.menuBarVisible).to.be.true();
  4019. w.menuBarVisible = false;
  4020. expect(w.menuBarVisible).to.be.false();
  4021. w.menuBarVisible = true;
  4022. expect(w.menuBarVisible).to.be.true();
  4023. });
  4024. });
  4025. describe('with functions', () => {
  4026. it('can be changed', () => {
  4027. const w = new BrowserWindow({ show: false });
  4028. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4029. w.setMenuBarVisibility(false);
  4030. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  4031. w.setMenuBarVisibility(true);
  4032. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  4033. });
  4034. });
  4035. });
  4036. ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
  4037. it('with functions', () => {
  4038. it('can be set with fullscreenable constructor option', () => {
  4039. const w = new BrowserWindow({ show: false, fullscreenable: false });
  4040. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4041. });
  4042. it('can be changed', () => {
  4043. const w = new BrowserWindow({ show: false });
  4044. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4045. w.setFullScreenable(false);
  4046. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  4047. w.setFullScreenable(true);
  4048. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  4049. });
  4050. });
  4051. });
  4052. // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
  4053. ifdescribe(process.platform === 'darwin')('kiosk state', () => {
  4054. it('with properties', () => {
  4055. it('can be set with a constructor property', () => {
  4056. const w = new BrowserWindow({ kiosk: true });
  4057. expect(w.kiosk).to.be.true();
  4058. });
  4059. it('can be changed ', async () => {
  4060. const w = new BrowserWindow();
  4061. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4062. w.kiosk = true;
  4063. expect(w.isKiosk()).to.be.true('isKiosk');
  4064. await enterFullScreen;
  4065. await delay();
  4066. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4067. w.kiosk = false;
  4068. expect(w.isKiosk()).to.be.false('isKiosk');
  4069. await leaveFullScreen;
  4070. });
  4071. });
  4072. it('with functions', () => {
  4073. it('can be set with a constructor property', () => {
  4074. const w = new BrowserWindow({ kiosk: true });
  4075. expect(w.isKiosk()).to.be.true();
  4076. });
  4077. it('can be changed ', async () => {
  4078. const w = new BrowserWindow();
  4079. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4080. w.setKiosk(true);
  4081. expect(w.isKiosk()).to.be.true('isKiosk');
  4082. await enterFullScreen;
  4083. await delay();
  4084. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4085. w.setKiosk(false);
  4086. expect(w.isKiosk()).to.be.false('isKiosk');
  4087. await leaveFullScreen;
  4088. });
  4089. });
  4090. });
  4091. ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
  4092. it('resizable flag should be set to true and restored', async () => {
  4093. const w = new BrowserWindow({ resizable: false });
  4094. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4095. w.setFullScreen(true);
  4096. await enterFullScreen;
  4097. expect(w.resizable).to.be.true('resizable');
  4098. await delay();
  4099. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4100. w.setFullScreen(false);
  4101. await leaveFullScreen;
  4102. expect(w.resizable).to.be.false('resizable');
  4103. });
  4104. });
  4105. ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
  4106. it('should not cause a crash if called when exiting fullscreen', async () => {
  4107. const w = new BrowserWindow();
  4108. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4109. w.setFullScreen(true);
  4110. await enterFullScreen;
  4111. await delay();
  4112. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4113. w.setFullScreen(false);
  4114. await leaveFullScreen;
  4115. });
  4116. it('can be changed with setFullScreen method', async () => {
  4117. const w = new BrowserWindow();
  4118. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4119. w.setFullScreen(true);
  4120. await enterFullScreen;
  4121. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4122. await delay();
  4123. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4124. w.setFullScreen(false);
  4125. await leaveFullScreen;
  4126. expect(w.isFullScreen()).to.be.false('isFullScreen');
  4127. });
  4128. it('handles several transitions starting with fullscreen', async () => {
  4129. const w = new BrowserWindow({ fullscreen: true, show: true });
  4130. expect(w.isFullScreen()).to.be.true('not fullscreen');
  4131. w.setFullScreen(false);
  4132. w.setFullScreen(true);
  4133. const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
  4134. await enterFullScreen;
  4135. expect(w.isFullScreen()).to.be.true('not fullscreen');
  4136. await delay();
  4137. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4138. w.setFullScreen(false);
  4139. await leaveFullScreen;
  4140. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4141. });
  4142. it('handles several transitions in close proximity', async () => {
  4143. const w = new BrowserWindow();
  4144. expect(w.isFullScreen()).to.be.false('is fullscreen');
  4145. w.setFullScreen(true);
  4146. w.setFullScreen(false);
  4147. w.setFullScreen(true);
  4148. const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2);
  4149. await enterFullScreen;
  4150. expect(w.isFullScreen()).to.be.true('not fullscreen');
  4151. });
  4152. it('does not crash when exiting simpleFullScreen (properties)', async () => {
  4153. const w = new BrowserWindow();
  4154. w.setSimpleFullScreen(true);
  4155. await delay(1000);
  4156. w.setFullScreen(!w.isFullScreen());
  4157. });
  4158. it('does not crash when exiting simpleFullScreen (functions)', async () => {
  4159. const w = new BrowserWindow();
  4160. w.simpleFullScreen = true;
  4161. await delay(1000);
  4162. w.setFullScreen(!w.isFullScreen());
  4163. });
  4164. it('should not be changed by setKiosk method', async () => {
  4165. const w = new BrowserWindow();
  4166. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4167. w.setFullScreen(true);
  4168. await enterFullScreen;
  4169. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4170. await delay();
  4171. w.setKiosk(true);
  4172. await delay();
  4173. w.setKiosk(false);
  4174. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4175. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  4176. w.setFullScreen(false);
  4177. await leaveFullScreen;
  4178. expect(w.isFullScreen()).to.be.false('isFullScreen');
  4179. });
  4180. // FIXME: https://github.com/electron/electron/issues/30140
  4181. xit('multiple windows inherit correct fullscreen state', async () => {
  4182. const w = new BrowserWindow();
  4183. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  4184. w.setFullScreen(true);
  4185. await enterFullScreen;
  4186. expect(w.isFullScreen()).to.be.true('isFullScreen');
  4187. await delay();
  4188. const w2 = new BrowserWindow({ show: false });
  4189. const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen');
  4190. w2.show();
  4191. await enterFullScreen2;
  4192. expect(w2.isFullScreen()).to.be.true('isFullScreen');
  4193. });
  4194. });
  4195. describe('closable state', () => {
  4196. it('with properties', () => {
  4197. it('can be set with closable constructor option', () => {
  4198. const w = new BrowserWindow({ show: false, closable: false });
  4199. expect(w.closable).to.be.false('closable');
  4200. });
  4201. it('can be changed', () => {
  4202. const w = new BrowserWindow({ show: false });
  4203. expect(w.closable).to.be.true('closable');
  4204. w.closable = false;
  4205. expect(w.closable).to.be.false('closable');
  4206. w.closable = true;
  4207. expect(w.closable).to.be.true('closable');
  4208. });
  4209. });
  4210. it('with functions', () => {
  4211. it('can be set with closable constructor option', () => {
  4212. const w = new BrowserWindow({ show: false, closable: false });
  4213. expect(w.isClosable()).to.be.false('isClosable');
  4214. });
  4215. it('can be changed', () => {
  4216. const w = new BrowserWindow({ show: false });
  4217. expect(w.isClosable()).to.be.true('isClosable');
  4218. w.setClosable(false);
  4219. expect(w.isClosable()).to.be.false('isClosable');
  4220. w.setClosable(true);
  4221. expect(w.isClosable()).to.be.true('isClosable');
  4222. });
  4223. });
  4224. });
  4225. describe('hasShadow state', () => {
  4226. it('with properties', () => {
  4227. it('returns a boolean on all platforms', () => {
  4228. const w = new BrowserWindow({ show: false });
  4229. expect(w.shadow).to.be.a('boolean');
  4230. });
  4231. // On Windows there's no shadow by default & it can't be changed dynamically.
  4232. it('can be changed with hasShadow option', () => {
  4233. const hasShadow = process.platform !== 'darwin';
  4234. const w = new BrowserWindow({ show: false, hasShadow });
  4235. expect(w.shadow).to.equal(hasShadow);
  4236. });
  4237. it('can be changed with setHasShadow method', () => {
  4238. const w = new BrowserWindow({ show: false });
  4239. w.shadow = false;
  4240. expect(w.shadow).to.be.false('hasShadow');
  4241. w.shadow = true;
  4242. expect(w.shadow).to.be.true('hasShadow');
  4243. w.shadow = false;
  4244. expect(w.shadow).to.be.false('hasShadow');
  4245. });
  4246. });
  4247. describe('with functions', () => {
  4248. it('returns a boolean on all platforms', () => {
  4249. const w = new BrowserWindow({ show: false });
  4250. const hasShadow = w.hasShadow();
  4251. expect(hasShadow).to.be.a('boolean');
  4252. });
  4253. // On Windows there's no shadow by default & it can't be changed dynamically.
  4254. it('can be changed with hasShadow option', () => {
  4255. const hasShadow = process.platform !== 'darwin';
  4256. const w = new BrowserWindow({ show: false, hasShadow });
  4257. expect(w.hasShadow()).to.equal(hasShadow);
  4258. });
  4259. it('can be changed with setHasShadow method', () => {
  4260. const w = new BrowserWindow({ show: false });
  4261. w.setHasShadow(false);
  4262. expect(w.hasShadow()).to.be.false('hasShadow');
  4263. w.setHasShadow(true);
  4264. expect(w.hasShadow()).to.be.true('hasShadow');
  4265. w.setHasShadow(false);
  4266. expect(w.hasShadow()).to.be.false('hasShadow');
  4267. });
  4268. });
  4269. });
  4270. });
  4271. describe('window.getMediaSourceId()', () => {
  4272. afterEach(closeAllWindows);
  4273. it('returns valid source id', async () => {
  4274. const w = new BrowserWindow({ show: false });
  4275. const shown = emittedOnce(w, 'show');
  4276. w.show();
  4277. await shown;
  4278. // Check format 'window:1234:0'.
  4279. const sourceId = w.getMediaSourceId();
  4280. expect(sourceId).to.match(/^window:\d+:\d+$/);
  4281. });
  4282. });
  4283. ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
  4284. afterEach(closeAllWindows);
  4285. it('returns valid handle', () => {
  4286. const w = new BrowserWindow({ show: false });
  4287. // The module's source code is hosted at
  4288. // https://github.com/electron/node-is-valid-window
  4289. const isValidWindow = require('is-valid-window');
  4290. expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
  4291. });
  4292. });
  4293. ifdescribe(process.platform === 'darwin')('previewFile', () => {
  4294. afterEach(closeAllWindows);
  4295. it('opens the path in Quick Look on macOS', () => {
  4296. const w = new BrowserWindow({ show: false });
  4297. expect(() => {
  4298. w.previewFile(__filename);
  4299. w.closeFilePreview();
  4300. }).to.not.throw();
  4301. });
  4302. });
  4303. describe('contextIsolation option with and without sandbox option', () => {
  4304. const expectedContextData = {
  4305. preloadContext: {
  4306. preloadProperty: 'number',
  4307. pageProperty: 'undefined',
  4308. typeofRequire: 'function',
  4309. typeofProcess: 'object',
  4310. typeofArrayPush: 'function',
  4311. typeofFunctionApply: 'function',
  4312. typeofPreloadExecuteJavaScriptProperty: 'undefined'
  4313. },
  4314. pageContext: {
  4315. preloadProperty: 'undefined',
  4316. pageProperty: 'string',
  4317. typeofRequire: 'undefined',
  4318. typeofProcess: 'undefined',
  4319. typeofArrayPush: 'number',
  4320. typeofFunctionApply: 'boolean',
  4321. typeofPreloadExecuteJavaScriptProperty: 'number',
  4322. typeofOpenedWindow: 'object'
  4323. }
  4324. };
  4325. afterEach(closeAllWindows);
  4326. it('separates the page context from the Electron/preload context', async () => {
  4327. const iw = new BrowserWindow({
  4328. show: false,
  4329. webPreferences: {
  4330. contextIsolation: true,
  4331. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4332. }
  4333. });
  4334. const p = emittedOnce(ipcMain, 'isolated-world');
  4335. iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4336. const [, data] = await p;
  4337. expect(data).to.deep.equal(expectedContextData);
  4338. });
  4339. it('recreates the contexts on reload', async () => {
  4340. const iw = new BrowserWindow({
  4341. show: false,
  4342. webPreferences: {
  4343. contextIsolation: true,
  4344. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4345. }
  4346. });
  4347. await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4348. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  4349. iw.webContents.reload();
  4350. const [, data] = await isolatedWorld;
  4351. expect(data).to.deep.equal(expectedContextData);
  4352. });
  4353. it('enables context isolation on child windows', async () => {
  4354. const iw = new BrowserWindow({
  4355. show: false,
  4356. webPreferences: {
  4357. contextIsolation: true,
  4358. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4359. }
  4360. });
  4361. const browserWindowCreated = emittedOnce(app, 'browser-window-created');
  4362. iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  4363. const [, window] = await browserWindowCreated;
  4364. expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
  4365. });
  4366. it('separates the page context from the Electron/preload context with sandbox on', async () => {
  4367. const ws = new BrowserWindow({
  4368. show: false,
  4369. webPreferences: {
  4370. sandbox: true,
  4371. contextIsolation: true,
  4372. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4373. }
  4374. });
  4375. const p = emittedOnce(ipcMain, 'isolated-world');
  4376. ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4377. const [, data] = await p;
  4378. expect(data).to.deep.equal(expectedContextData);
  4379. });
  4380. it('recreates the contexts on reload with sandbox on', async () => {
  4381. const ws = new BrowserWindow({
  4382. show: false,
  4383. webPreferences: {
  4384. sandbox: true,
  4385. contextIsolation: true,
  4386. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4387. }
  4388. });
  4389. await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  4390. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  4391. ws.webContents.reload();
  4392. const [, data] = await isolatedWorld;
  4393. expect(data).to.deep.equal(expectedContextData);
  4394. });
  4395. it('supports fetch api', async () => {
  4396. const fetchWindow = new BrowserWindow({
  4397. show: false,
  4398. webPreferences: {
  4399. contextIsolation: true,
  4400. preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
  4401. }
  4402. });
  4403. const p = emittedOnce(ipcMain, 'isolated-fetch-error');
  4404. fetchWindow.loadURL('about:blank');
  4405. const [, error] = await p;
  4406. expect(error).to.equal('Failed to fetch');
  4407. });
  4408. it('doesn\'t break ipc serialization', async () => {
  4409. const iw = new BrowserWindow({
  4410. show: false,
  4411. webPreferences: {
  4412. contextIsolation: true,
  4413. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  4414. }
  4415. });
  4416. const p = emittedOnce(ipcMain, 'isolated-world');
  4417. iw.loadURL('about:blank');
  4418. iw.webContents.executeJavaScript(`
  4419. const opened = window.open()
  4420. openedLocation = opened.location.href
  4421. opened.close()
  4422. window.postMessage({openedLocation}, '*')
  4423. `);
  4424. const [, data] = await p;
  4425. expect(data.pageContext.openedLocation).to.equal('about:blank');
  4426. });
  4427. it('reports process.contextIsolated', async () => {
  4428. const iw = new BrowserWindow({
  4429. show: false,
  4430. webPreferences: {
  4431. contextIsolation: true,
  4432. preload: path.join(fixtures, 'api', 'isolated-process.js')
  4433. }
  4434. });
  4435. const p = emittedOnce(ipcMain, 'context-isolation');
  4436. iw.loadURL('about:blank');
  4437. const [, contextIsolation] = await p;
  4438. expect(contextIsolation).to.be.true('contextIsolation');
  4439. });
  4440. });
  4441. it('reloading does not cause Node.js module API hangs after reload', (done) => {
  4442. const w = new BrowserWindow({
  4443. show: false,
  4444. webPreferences: {
  4445. nodeIntegration: true,
  4446. contextIsolation: false
  4447. }
  4448. });
  4449. let count = 0;
  4450. ipcMain.on('async-node-api-done', () => {
  4451. if (count === 3) {
  4452. ipcMain.removeAllListeners('async-node-api-done');
  4453. done();
  4454. } else {
  4455. count++;
  4456. w.reload();
  4457. }
  4458. });
  4459. w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
  4460. });
  4461. describe('window.webContents.focus()', () => {
  4462. afterEach(closeAllWindows);
  4463. it('focuses window', async () => {
  4464. const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
  4465. w1.loadURL('about:blank');
  4466. const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
  4467. w2.loadURL('about:blank');
  4468. const w1Focused = emittedOnce(w1, 'focus');
  4469. w1.webContents.focus();
  4470. await w1Focused;
  4471. expect(w1.webContents.isFocused()).to.be.true('focuses window');
  4472. });
  4473. });
  4474. ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
  4475. let w: BrowserWindow;
  4476. beforeEach(function () {
  4477. w = new BrowserWindow({
  4478. width: 100,
  4479. height: 100,
  4480. show: false,
  4481. webPreferences: {
  4482. backgroundThrottling: false,
  4483. offscreen: true
  4484. }
  4485. });
  4486. });
  4487. afterEach(closeAllWindows);
  4488. it('creates offscreen window with correct size', async () => {
  4489. const paint = emittedOnce(w.webContents, 'paint');
  4490. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4491. const [,, data] = await paint;
  4492. expect(data.constructor.name).to.equal('NativeImage');
  4493. expect(data.isEmpty()).to.be.false('data is empty');
  4494. const size = data.getSize();
  4495. const { scaleFactor } = screen.getPrimaryDisplay();
  4496. expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
  4497. expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
  4498. });
  4499. it('does not crash after navigation', () => {
  4500. w.webContents.loadURL('about:blank');
  4501. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4502. });
  4503. describe('window.webContents.isOffscreen()', () => {
  4504. it('is true for offscreen type', () => {
  4505. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4506. expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
  4507. });
  4508. it('is false for regular window', () => {
  4509. const c = new BrowserWindow({ show: false });
  4510. expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
  4511. c.destroy();
  4512. });
  4513. });
  4514. describe('window.webContents.isPainting()', () => {
  4515. it('returns whether is currently painting', async () => {
  4516. const paint = emittedOnce(w.webContents, 'paint');
  4517. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4518. await paint;
  4519. expect(w.webContents.isPainting()).to.be.true('isPainting');
  4520. });
  4521. });
  4522. describe('window.webContents.stopPainting()', () => {
  4523. it('stops painting', async () => {
  4524. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4525. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4526. await domReady;
  4527. w.webContents.stopPainting();
  4528. expect(w.webContents.isPainting()).to.be.false('isPainting');
  4529. });
  4530. });
  4531. describe('window.webContents.startPainting()', () => {
  4532. it('starts painting', async () => {
  4533. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4534. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4535. await domReady;
  4536. w.webContents.stopPainting();
  4537. w.webContents.startPainting();
  4538. await emittedOnce(w.webContents, 'paint');
  4539. expect(w.webContents.isPainting()).to.be.true('isPainting');
  4540. });
  4541. });
  4542. describe('frameRate APIs', () => {
  4543. it('has default frame rate (function)', async () => {
  4544. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4545. await emittedOnce(w.webContents, 'paint');
  4546. expect(w.webContents.getFrameRate()).to.equal(60);
  4547. });
  4548. it('has default frame rate (property)', async () => {
  4549. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4550. await emittedOnce(w.webContents, 'paint');
  4551. expect(w.webContents.frameRate).to.equal(60);
  4552. });
  4553. it('sets custom frame rate (function)', async () => {
  4554. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4555. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4556. await domReady;
  4557. w.webContents.setFrameRate(30);
  4558. await emittedOnce(w.webContents, 'paint');
  4559. expect(w.webContents.getFrameRate()).to.equal(30);
  4560. });
  4561. it('sets custom frame rate (property)', async () => {
  4562. const domReady = emittedOnce(w.webContents, 'dom-ready');
  4563. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  4564. await domReady;
  4565. w.webContents.frameRate = 30;
  4566. await emittedOnce(w.webContents, 'paint');
  4567. expect(w.webContents.frameRate).to.equal(30);
  4568. });
  4569. });
  4570. });
  4571. describe('"transparent" option', () => {
  4572. afterEach(closeAllWindows);
  4573. // Only applicable on Windows where transparent windows can't be maximized.
  4574. ifit(process.platform === 'win32')('can show maximized frameless window', async () => {
  4575. const display = screen.getPrimaryDisplay();
  4576. const w = new BrowserWindow({
  4577. ...display.bounds,
  4578. frame: false,
  4579. transparent: true,
  4580. show: true
  4581. });
  4582. w.loadURL('about:blank');
  4583. await emittedOnce(w, 'ready-to-show');
  4584. expect(w.isMaximized()).to.be.true();
  4585. // Fails when the transparent HWND is in an invalid maximized state.
  4586. expect(w.getBounds()).to.deep.equal(display.workArea);
  4587. const newBounds = { width: 256, height: 256, x: 0, y: 0 };
  4588. w.setBounds(newBounds);
  4589. expect(w.getBounds()).to.deep.equal(newBounds);
  4590. });
  4591. });
  4592. });