api-browser-window-spec.ts 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439
  1. import { expect } from 'chai';
  2. import * as path from 'path';
  3. import * as fs from 'fs';
  4. import * as os from 'os';
  5. import * as qs from 'querystring';
  6. import * as http from 'http';
  7. import { AddressInfo } from 'net';
  8. import { app, BrowserWindow, BrowserView, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents } from 'electron/main';
  9. import { emittedOnce, emittedUntil } from './events-helpers';
  10. import { ifit, ifdescribe, delay } from './spec-helpers';
  11. import { closeWindow, closeAllWindows } from './window-helpers';
  12. const features = process.electronBinding('features');
  13. const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures');
  14. // Is the display's scale factor possibly causing rounding of pixel coordinate
  15. // values?
  16. const isScaleFactorRounding = () => {
  17. const { scaleFactor } = screen.getPrimaryDisplay();
  18. // Return true if scale factor is non-integer value
  19. if (Math.round(scaleFactor) !== scaleFactor) return true;
  20. // Return true if scale factor is odd number above 2
  21. return scaleFactor > 2 && scaleFactor % 2 === 1;
  22. };
  23. const expectBoundsEqual = (actual: any, expected: any) => {
  24. if (!isScaleFactorRounding()) {
  25. expect(expected).to.deep.equal(actual);
  26. } else if (Array.isArray(actual)) {
  27. expect(actual[0]).to.be.closeTo(expected[0], 1);
  28. expect(actual[1]).to.be.closeTo(expected[1], 1);
  29. } else {
  30. expect(actual.x).to.be.closeTo(expected.x, 1);
  31. expect(actual.y).to.be.closeTo(expected.y, 1);
  32. expect(actual.width).to.be.closeTo(expected.width, 1);
  33. expect(actual.height).to.be.closeTo(expected.height, 1);
  34. }
  35. };
  36. const isBeforeUnload = (event: Event, level: number, message: string) => {
  37. return (message === 'beforeunload');
  38. };
  39. describe('BrowserWindow module', () => {
  40. describe('BrowserWindow constructor', () => {
  41. it('allows passing void 0 as the webContents', async () => {
  42. expect(() => {
  43. const w = new BrowserWindow({
  44. show: false,
  45. // apparently void 0 had different behaviour from undefined in the
  46. // issue that this test is supposed to catch.
  47. webContents: void 0 // eslint-disable-line no-void
  48. } as any);
  49. w.destroy();
  50. }).not.to.throw();
  51. });
  52. });
  53. describe('garbage collection', () => {
  54. const v8Util = process.electronBinding('v8_util');
  55. afterEach(closeAllWindows);
  56. it('window does not get garbage collected when opened', async () => {
  57. const w = new BrowserWindow({ show: false });
  58. // Keep a weak reference to the window.
  59. // eslint-disable-next-line no-undef
  60. const wr = new (globalThis as any).WeakRef(w);
  61. await delay();
  62. // Do garbage collection, since |w| is not referenced in this closure
  63. // it would be gone after next call if there is no other reference.
  64. v8Util.requestGarbageCollectionForTesting();
  65. await delay();
  66. expect(wr.deref()).to.not.be.undefined();
  67. });
  68. });
  69. describe('BrowserWindow.close()', () => {
  70. let w = null as unknown as BrowserWindow;
  71. beforeEach(() => {
  72. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  73. });
  74. afterEach(async () => {
  75. await closeWindow(w);
  76. w = null as unknown as BrowserWindow;
  77. });
  78. it('should emit unload handler', async () => {
  79. await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
  80. const closed = emittedOnce(w, 'closed');
  81. w.close();
  82. await closed;
  83. const test = path.join(fixtures, 'api', 'unload');
  84. const content = fs.readFileSync(test);
  85. fs.unlinkSync(test);
  86. expect(String(content)).to.equal('unload');
  87. });
  88. it('should emit beforeunload handler', async () => {
  89. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  90. w.close();
  91. await emittedOnce(w.webContents, 'before-unload-fired');
  92. });
  93. it('should not crash when keyboard event is sent before closing', async () => {
  94. await w.loadURL('data:text/html,pls no crash');
  95. const closed = emittedOnce(w, 'closed');
  96. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
  97. w.close();
  98. await closed;
  99. });
  100. describe('when invoked synchronously inside navigation observer', () => {
  101. let server: http.Server = null as unknown as http.Server;
  102. let url: string = null as unknown as string;
  103. before((done) => {
  104. server = http.createServer((request, response) => {
  105. switch (request.url) {
  106. case '/net-error':
  107. response.destroy();
  108. break;
  109. case '/301':
  110. response.statusCode = 301;
  111. response.setHeader('Location', '/200');
  112. response.end();
  113. break;
  114. case '/200':
  115. response.statusCode = 200;
  116. response.end('hello');
  117. break;
  118. case '/title':
  119. response.statusCode = 200;
  120. response.end('<title>Hello</title>');
  121. break;
  122. default:
  123. throw new Error(`unsupported endpoint: ${request.url}`);
  124. }
  125. }).listen(0, '127.0.0.1', () => {
  126. url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  127. done();
  128. });
  129. });
  130. after(() => {
  131. server.close();
  132. });
  133. const events = [
  134. { name: 'did-start-loading', path: '/200' },
  135. { name: 'dom-ready', path: '/200' },
  136. { name: 'page-title-updated', path: '/title' },
  137. { name: 'did-stop-loading', path: '/200' },
  138. { name: 'did-finish-load', path: '/200' },
  139. { name: 'did-frame-finish-load', path: '/200' },
  140. { name: 'did-fail-load', path: '/net-error' }
  141. ];
  142. for (const { name, path } of events) {
  143. it(`should not crash when closed during ${name}`, async () => {
  144. const w = new BrowserWindow({ show: false });
  145. w.webContents.once((name as any), () => {
  146. w.close();
  147. });
  148. const destroyed = emittedOnce(w.webContents, 'destroyed');
  149. w.webContents.loadURL(url + path);
  150. await destroyed;
  151. });
  152. }
  153. });
  154. });
  155. describe('window.close()', () => {
  156. let w = null as unknown as BrowserWindow;
  157. beforeEach(() => {
  158. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  159. });
  160. afterEach(async () => {
  161. await closeWindow(w);
  162. w = null as unknown as BrowserWindow;
  163. });
  164. it('should emit unload event', async () => {
  165. w.loadFile(path.join(fixtures, 'api', 'close.html'));
  166. await emittedOnce(w, 'closed');
  167. const test = path.join(fixtures, 'api', 'close');
  168. const content = fs.readFileSync(test).toString();
  169. fs.unlinkSync(test);
  170. expect(content).to.equal('close');
  171. });
  172. it('should emit beforeunload event', async function () {
  173. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  174. w.webContents.executeJavaScript('window.close()', true);
  175. await emittedOnce(w.webContents, 'before-unload-fired');
  176. });
  177. });
  178. describe('BrowserWindow.destroy()', () => {
  179. let w = null as unknown as BrowserWindow;
  180. beforeEach(() => {
  181. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  182. });
  183. afterEach(async () => {
  184. await closeWindow(w);
  185. w = null as unknown as BrowserWindow;
  186. });
  187. it('prevents users to access methods of webContents', async () => {
  188. const contents = w.webContents;
  189. w.destroy();
  190. await new Promise(setImmediate);
  191. expect(() => {
  192. contents.getProcessId();
  193. }).to.throw('Object has been destroyed');
  194. });
  195. it('should not crash when destroying windows with pending events', () => {
  196. const focusListener = () => { };
  197. app.on('browser-window-focus', focusListener);
  198. const windowCount = 3;
  199. const windowOptions = {
  200. show: false,
  201. width: 400,
  202. height: 400,
  203. webPreferences: {
  204. backgroundThrottling: false
  205. }
  206. };
  207. const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
  208. windows.forEach(win => win.show());
  209. windows.forEach(win => win.focus());
  210. windows.forEach(win => win.destroy());
  211. app.removeListener('browser-window-focus', focusListener);
  212. });
  213. });
  214. describe('BrowserWindow.loadURL(url)', () => {
  215. let w = null as unknown as BrowserWindow;
  216. const scheme = 'other';
  217. const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
  218. before(() => {
  219. protocol.registerFileProtocol(scheme, (request, callback) => {
  220. callback(srcPath);
  221. });
  222. });
  223. after(() => {
  224. protocol.unregisterProtocol(scheme);
  225. });
  226. beforeEach(() => {
  227. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  228. });
  229. afterEach(async () => {
  230. await closeWindow(w);
  231. w = null as unknown as BrowserWindow;
  232. });
  233. let server = null as unknown as http.Server;
  234. let url = null as unknown as string;
  235. let postData = null as any;
  236. before((done) => {
  237. const filePath = path.join(fixtures, 'pages', 'a.html');
  238. const fileStats = fs.statSync(filePath);
  239. postData = [
  240. {
  241. type: 'rawData',
  242. bytes: Buffer.from('username=test&file=')
  243. },
  244. {
  245. type: 'file',
  246. filePath: filePath,
  247. offset: 0,
  248. length: fileStats.size,
  249. modificationTime: fileStats.mtime.getTime() / 1000
  250. }
  251. ];
  252. server = http.createServer((req, res) => {
  253. function respond () {
  254. if (req.method === 'POST') {
  255. let body = '';
  256. req.on('data', (data) => {
  257. if (data) body += data;
  258. });
  259. req.on('end', () => {
  260. const parsedData = qs.parse(body);
  261. fs.readFile(filePath, (err, data) => {
  262. if (err) return;
  263. if (parsedData.username === 'test' &&
  264. parsedData.file === data.toString()) {
  265. res.end();
  266. }
  267. });
  268. });
  269. } else if (req.url === '/302') {
  270. res.setHeader('Location', '/200');
  271. res.statusCode = 302;
  272. res.end();
  273. } else {
  274. res.end();
  275. }
  276. }
  277. setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0);
  278. });
  279. server.listen(0, '127.0.0.1', () => {
  280. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  281. done();
  282. });
  283. });
  284. after(() => {
  285. server.close();
  286. });
  287. it('should emit did-start-loading event', (done) => {
  288. w.webContents.on('did-start-loading', () => { done(); });
  289. w.loadURL('about:blank');
  290. });
  291. it('should emit ready-to-show event', (done) => {
  292. w.on('ready-to-show', () => { done(); });
  293. w.loadURL('about:blank');
  294. });
  295. // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
  296. // changed and adjust the test.
  297. it.skip('should emit did-fail-load event for files that do not exist', async () => {
  298. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  299. w.loadURL('file://a.txt');
  300. const [, code, desc,, isMainFrame] = await didFailLoad;
  301. expect(code).to.equal(-6);
  302. expect(desc).to.equal('ERR_FILE_NOT_FOUND');
  303. expect(isMainFrame).to.equal(true);
  304. });
  305. it('should emit did-fail-load event for invalid URL', async () => {
  306. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  307. w.loadURL('http://example:port');
  308. const [, code, desc,, isMainFrame] = await didFailLoad;
  309. expect(desc).to.equal('ERR_INVALID_URL');
  310. expect(code).to.equal(-300);
  311. expect(isMainFrame).to.equal(true);
  312. });
  313. it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
  314. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  315. w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
  316. const [,,,, isMainFrame] = await didFailLoad;
  317. expect(isMainFrame).to.equal(false);
  318. });
  319. it('does not crash in did-fail-provisional-load handler', (done) => {
  320. w.webContents.once('did-fail-provisional-load', () => {
  321. w.loadURL('http://127.0.0.1:11111');
  322. done();
  323. });
  324. w.loadURL('http://127.0.0.1:11111');
  325. });
  326. it('should emit did-fail-load event for URL exceeding character limit', async () => {
  327. const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
  328. const didFailLoad = emittedOnce(w.webContents, 'did-fail-load');
  329. w.loadURL(`data:image/png;base64,${data}`);
  330. const [, code, desc,, isMainFrame] = await didFailLoad;
  331. expect(desc).to.equal('ERR_INVALID_URL');
  332. expect(code).to.equal(-300);
  333. expect(isMainFrame).to.equal(true);
  334. });
  335. it('should return a promise', () => {
  336. const p = w.loadURL('about:blank');
  337. expect(p).to.have.property('then');
  338. });
  339. it('should return a promise that resolves', async () => {
  340. await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
  341. });
  342. it('should return a promise that rejects on a load failure', async () => {
  343. const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
  344. const p = w.loadURL(`data:image/png;base64,${data}`);
  345. await expect(p).to.eventually.be.rejected;
  346. });
  347. it('should return a promise that resolves even if pushState occurs during navigation', async () => {
  348. const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
  349. await expect(p).to.eventually.be.fulfilled;
  350. });
  351. // FIXME(robo/nornagon): re-enable these once service workers work
  352. describe.skip('POST navigations', () => {
  353. afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
  354. it('supports specifying POST data', async () => {
  355. await w.loadURL(url, { postData });
  356. });
  357. it('sets the content type header on URL encoded forms', async () => {
  358. await w.loadURL(url);
  359. const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
  360. w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
  361. resolve(details);
  362. });
  363. });
  364. w.webContents.executeJavaScript(`
  365. form = document.createElement('form')
  366. document.body.appendChild(form)
  367. form.method = 'POST'
  368. form.submit()
  369. `);
  370. const details = await requestDetails;
  371. expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
  372. });
  373. it('sets the content type header on multi part forms', async () => {
  374. await w.loadURL(url);
  375. const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
  376. w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
  377. resolve(details);
  378. });
  379. });
  380. w.webContents.executeJavaScript(`
  381. form = document.createElement('form')
  382. document.body.appendChild(form)
  383. form.method = 'POST'
  384. form.enctype = 'multipart/form-data'
  385. file = document.createElement('input')
  386. file.type = 'file'
  387. file.name = 'file'
  388. form.appendChild(file)
  389. form.submit()
  390. `);
  391. const details = await requestDetails;
  392. expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
  393. });
  394. });
  395. it('should support support base url for data urls', async () => {
  396. const answer = emittedOnce(ipcMain, 'answer');
  397. w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
  398. const [, test] = await answer;
  399. expect(test).to.equal('test');
  400. });
  401. });
  402. for (const sandbox of [false, true]) {
  403. describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
  404. let w = null as unknown as BrowserWindow;
  405. beforeEach(() => {
  406. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
  407. });
  408. afterEach(async () => {
  409. await closeWindow(w);
  410. w = null as unknown as BrowserWindow;
  411. });
  412. describe('will-navigate event', () => {
  413. let server = null as unknown as http.Server;
  414. let url = null as unknown as string;
  415. before((done) => {
  416. server = http.createServer((req, res) => {
  417. if (req.url === '/navigate-top') {
  418. res.end('<a target=_top href="/">navigate _top</a>');
  419. } else {
  420. res.end('');
  421. }
  422. });
  423. server.listen(0, '127.0.0.1', () => {
  424. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
  425. done();
  426. });
  427. });
  428. after(() => {
  429. server.close();
  430. });
  431. it('allows the window to be closed from the event listener', (done) => {
  432. w.webContents.once('will-navigate', () => {
  433. w.close();
  434. done();
  435. });
  436. w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
  437. });
  438. it('can be prevented', (done) => {
  439. let willNavigate = false;
  440. w.webContents.once('will-navigate', (e) => {
  441. willNavigate = true;
  442. e.preventDefault();
  443. });
  444. w.webContents.on('did-stop-loading', () => {
  445. if (willNavigate) {
  446. // i.e. it shouldn't have had '?navigated' appended to it.
  447. try {
  448. expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
  449. done();
  450. } catch (e) {
  451. done(e);
  452. }
  453. }
  454. });
  455. w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
  456. });
  457. it('is triggered when navigating from file: to http:', async () => {
  458. await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  459. w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
  460. const navigatedTo = await new Promise(resolve => {
  461. w.webContents.once('will-navigate', (e, url) => {
  462. e.preventDefault();
  463. resolve(url);
  464. });
  465. });
  466. expect(navigatedTo).to.equal(url);
  467. expect(w.webContents.getURL()).to.match(/^file:/);
  468. });
  469. it('is triggered when navigating from about:blank to http:', async () => {
  470. await w.loadURL('about:blank');
  471. w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
  472. const navigatedTo = await new Promise(resolve => {
  473. w.webContents.once('will-navigate', (e, url) => {
  474. e.preventDefault();
  475. resolve(url);
  476. });
  477. });
  478. expect(navigatedTo).to.equal(url);
  479. expect(w.webContents.getURL()).to.equal('about:blank');
  480. });
  481. it('is triggered when a cross-origin iframe navigates _top', async () => {
  482. await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
  483. await delay(1000);
  484. w.webContents.debugger.attach('1.1');
  485. const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
  486. const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
  487. const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
  488. targetId: iframeTarget.targetId,
  489. flatten: true
  490. });
  491. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  492. type: 'mousePressed',
  493. x: 10,
  494. y: 10,
  495. clickCount: 1,
  496. button: 'left'
  497. }, sessionId);
  498. await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
  499. type: 'mouseReleased',
  500. x: 10,
  501. y: 10,
  502. clickCount: 1,
  503. button: 'left'
  504. }, sessionId);
  505. let willNavigateEmitted = false;
  506. w.webContents.on('will-navigate', () => {
  507. willNavigateEmitted = true;
  508. });
  509. await emittedOnce(w.webContents, 'did-navigate');
  510. expect(willNavigateEmitted).to.be.true();
  511. });
  512. });
  513. describe('will-redirect event', () => {
  514. let server = null as unknown as http.Server;
  515. let url = null as unknown as string;
  516. before((done) => {
  517. server = http.createServer((req, res) => {
  518. if (req.url === '/302') {
  519. res.setHeader('Location', '/200');
  520. res.statusCode = 302;
  521. res.end();
  522. } else if (req.url === '/navigate-302') {
  523. res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
  524. } else {
  525. res.end();
  526. }
  527. });
  528. server.listen(0, '127.0.0.1', () => {
  529. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  530. done();
  531. });
  532. });
  533. after(() => {
  534. server.close();
  535. });
  536. it('is emitted on redirects', (done) => {
  537. w.webContents.on('will-redirect', () => {
  538. done();
  539. });
  540. w.loadURL(`${url}/302`);
  541. });
  542. it('is emitted after will-navigate on redirects', async () => {
  543. let navigateCalled = false;
  544. w.webContents.on('will-navigate', () => {
  545. navigateCalled = true;
  546. });
  547. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  548. w.loadURL(`${url}/navigate-302`);
  549. await willRedirect;
  550. expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
  551. });
  552. it('is emitted before did-stop-loading on redirects', async () => {
  553. let stopCalled = false;
  554. w.webContents.on('did-stop-loading', () => {
  555. stopCalled = true;
  556. });
  557. const willRedirect = emittedOnce(w.webContents, 'will-redirect');
  558. w.loadURL(`${url}/302`);
  559. await willRedirect;
  560. expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
  561. });
  562. it('allows the window to be closed from the event listener', (done) => {
  563. w.webContents.once('will-redirect', () => {
  564. w.close();
  565. done();
  566. });
  567. w.loadURL(`${url}/302`);
  568. });
  569. it('can be prevented', (done) => {
  570. w.webContents.once('will-redirect', (event) => {
  571. event.preventDefault();
  572. });
  573. w.webContents.on('will-navigate', (e, u) => {
  574. expect(u).to.equal(`${url}/302`);
  575. });
  576. w.webContents.on('did-stop-loading', () => {
  577. try {
  578. expect(w.webContents.getURL()).to.equal(
  579. `${url}/navigate-302`,
  580. 'url should not have changed after navigation event'
  581. );
  582. done();
  583. } catch (e) {
  584. done(e);
  585. }
  586. });
  587. w.webContents.on('will-redirect', (e, u) => {
  588. try {
  589. expect(u).to.equal(`${url}/200`);
  590. } catch (e) {
  591. done(e);
  592. }
  593. });
  594. w.loadURL(`${url}/navigate-302`);
  595. });
  596. });
  597. });
  598. }
  599. describe('focus and visibility', () => {
  600. let w = null as unknown as BrowserWindow;
  601. beforeEach(() => {
  602. w = new BrowserWindow({ show: false });
  603. });
  604. afterEach(async () => {
  605. await closeWindow(w);
  606. w = null as unknown as BrowserWindow;
  607. });
  608. describe('BrowserWindow.show()', () => {
  609. it('should focus on window', () => {
  610. w.show();
  611. expect(w.isFocused()).to.equal(true);
  612. });
  613. it('should make the window visible', () => {
  614. w.show();
  615. expect(w.isVisible()).to.equal(true);
  616. });
  617. it('emits when window is shown', async () => {
  618. const show = emittedOnce(w, 'show');
  619. w.show();
  620. await show;
  621. expect(w.isVisible()).to.equal(true);
  622. });
  623. });
  624. describe('BrowserWindow.hide()', () => {
  625. it('should defocus on window', () => {
  626. w.hide();
  627. expect(w.isFocused()).to.equal(false);
  628. });
  629. it('should make the window not visible', () => {
  630. w.show();
  631. w.hide();
  632. expect(w.isVisible()).to.equal(false);
  633. });
  634. it('emits when window is hidden', async () => {
  635. const shown = emittedOnce(w, 'show');
  636. w.show();
  637. await shown;
  638. const hidden = emittedOnce(w, 'hide');
  639. w.hide();
  640. await hidden;
  641. expect(w.isVisible()).to.equal(false);
  642. });
  643. });
  644. describe('BrowserWindow.showInactive()', () => {
  645. it('should not focus on window', () => {
  646. w.showInactive();
  647. expect(w.isFocused()).to.equal(false);
  648. });
  649. });
  650. describe('BrowserWindow.focus()', () => {
  651. it('does not make the window become visible', () => {
  652. expect(w.isVisible()).to.equal(false);
  653. w.focus();
  654. expect(w.isVisible()).to.equal(false);
  655. });
  656. });
  657. describe('BrowserWindow.blur()', () => {
  658. it('removes focus from window', () => {
  659. w.blur();
  660. expect(w.isFocused()).to.equal(false);
  661. });
  662. });
  663. describe('BrowserWindow.getFocusedWindow()', () => {
  664. it('returns the opener window when dev tools window is focused', async () => {
  665. w.show();
  666. w.webContents.openDevTools({ mode: 'undocked' });
  667. await emittedOnce(w.webContents, 'devtools-focused');
  668. expect(BrowserWindow.getFocusedWindow()).to.equal(w);
  669. });
  670. });
  671. describe('BrowserWindow.moveTop()', () => {
  672. it('should not steal focus', async () => {
  673. const posDelta = 50;
  674. const wShownInactive = emittedOnce(w, 'show');
  675. w.showInactive();
  676. await wShownInactive;
  677. expect(w.isFocused()).to.equal(false);
  678. const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' });
  679. const otherWindowShown = emittedOnce(otherWindow, 'show');
  680. const otherWindowFocused = emittedOnce(otherWindow, 'focus');
  681. otherWindow.show();
  682. await otherWindowShown;
  683. await otherWindowFocused;
  684. expect(otherWindow.isFocused()).to.equal(true);
  685. w.moveTop();
  686. const wPos = w.getPosition();
  687. const wMoving = emittedOnce(w, 'move');
  688. w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta);
  689. await wMoving;
  690. expect(w.isFocused()).to.equal(false);
  691. expect(otherWindow.isFocused()).to.equal(true);
  692. const wFocused = emittedOnce(w, 'focus');
  693. w.focus();
  694. await wFocused;
  695. expect(w.isFocused()).to.equal(true);
  696. otherWindow.moveTop();
  697. const otherWindowPos = otherWindow.getPosition();
  698. const otherWindowMoving = emittedOnce(otherWindow, 'move');
  699. otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta);
  700. await otherWindowMoving;
  701. expect(otherWindow.isFocused()).to.equal(false);
  702. expect(w.isFocused()).to.equal(true);
  703. await closeWindow(otherWindow, { assertNotWindows: false });
  704. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1);
  705. });
  706. });
  707. ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => {
  708. it('should throw an exception if wrong formatting', async () => {
  709. const fakeSourceIds = [
  710. 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2'
  711. ];
  712. fakeSourceIds.forEach((sourceId) => {
  713. expect(() => {
  714. w.moveAbove(sourceId);
  715. }).to.throw(/Invalid media source id/);
  716. });
  717. });
  718. it('should throw an exception if wrong type', async () => {
  719. const fakeSourceIds = [null as any, 123 as any];
  720. fakeSourceIds.forEach((sourceId) => {
  721. expect(() => {
  722. w.moveAbove(sourceId);
  723. }).to.throw(/Error processing argument at index 0 */);
  724. });
  725. });
  726. it('should throw an exception if invalid window', async () => {
  727. // It is very unlikely that these window id exist.
  728. const fakeSourceIds = ['window:99999999:0', 'window:123456:1',
  729. 'window:123456:9'];
  730. fakeSourceIds.forEach((sourceId) => {
  731. expect(() => {
  732. w.moveAbove(sourceId);
  733. }).to.throw(/Invalid media source id/);
  734. });
  735. });
  736. it('should not throw an exception', async () => {
  737. const w2 = new BrowserWindow({ show: false, title: 'window2' });
  738. const w2Shown = emittedOnce(w2, 'show');
  739. w2.show();
  740. await w2Shown;
  741. expect(() => {
  742. w.moveAbove(w2.getMediaSourceId());
  743. }).to.not.throw();
  744. await closeWindow(w2, { assertNotWindows: false });
  745. });
  746. });
  747. describe('BrowserWindow.setFocusable()', () => {
  748. it('can set unfocusable window to focusable', async () => {
  749. const w2 = new BrowserWindow({ focusable: false });
  750. const w2Focused = emittedOnce(w2, 'focus');
  751. w2.setFocusable(true);
  752. w2.focus();
  753. await w2Focused;
  754. await closeWindow(w2, { assertNotWindows: false });
  755. });
  756. });
  757. });
  758. describe('sizing', () => {
  759. let w = null as unknown as BrowserWindow;
  760. beforeEach(() => {
  761. w = new BrowserWindow({ show: false, width: 400, height: 400 });
  762. });
  763. afterEach(async () => {
  764. await closeWindow(w);
  765. w = null as unknown as BrowserWindow;
  766. });
  767. describe('BrowserWindow.setBounds(bounds[, animate])', () => {
  768. it('sets the window bounds with full bounds', () => {
  769. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  770. w.setBounds(fullBounds);
  771. expectBoundsEqual(w.getBounds(), fullBounds);
  772. });
  773. it('sets the window bounds with partial bounds', () => {
  774. const fullBounds = { x: 440, y: 225, width: 500, height: 400 };
  775. w.setBounds(fullBounds);
  776. const boundsUpdate = { width: 200 };
  777. w.setBounds(boundsUpdate as any);
  778. const expectedBounds = Object.assign(fullBounds, boundsUpdate);
  779. expectBoundsEqual(w.getBounds(), expectedBounds);
  780. });
  781. });
  782. describe('BrowserWindow.setSize(width, height)', () => {
  783. it('sets the window size', async () => {
  784. const size = [300, 400];
  785. const resized = emittedOnce(w, 'resize');
  786. w.setSize(size[0], size[1]);
  787. await resized;
  788. expectBoundsEqual(w.getSize(), size);
  789. });
  790. });
  791. describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => {
  792. it('sets the maximum and minimum size of the window', () => {
  793. expect(w.getMinimumSize()).to.deep.equal([0, 0]);
  794. expect(w.getMaximumSize()).to.deep.equal([0, 0]);
  795. w.setMinimumSize(100, 100);
  796. expectBoundsEqual(w.getMinimumSize(), [100, 100]);
  797. expectBoundsEqual(w.getMaximumSize(), [0, 0]);
  798. w.setMaximumSize(900, 600);
  799. expectBoundsEqual(w.getMinimumSize(), [100, 100]);
  800. expectBoundsEqual(w.getMaximumSize(), [900, 600]);
  801. });
  802. });
  803. describe('BrowserWindow.setAspectRatio(ratio)', () => {
  804. it('resets the behaviour when passing in 0', async () => {
  805. const size = [300, 400];
  806. w.setAspectRatio(1 / 2);
  807. w.setAspectRatio(0);
  808. const resize = emittedOnce(w, 'resize');
  809. w.setSize(size[0], size[1]);
  810. await resize;
  811. expectBoundsEqual(w.getSize(), size);
  812. });
  813. });
  814. describe('BrowserWindow.setPosition(x, y)', () => {
  815. it('sets the window position', async () => {
  816. const pos = [10, 10];
  817. const move = emittedOnce(w, 'move');
  818. w.setPosition(pos[0], pos[1]);
  819. await move;
  820. expect(w.getPosition()).to.deep.equal(pos);
  821. });
  822. });
  823. describe('BrowserWindow.setContentSize(width, height)', () => {
  824. it('sets the content size', async () => {
  825. // NB. The CI server has a very small screen. Attempting to size the window
  826. // larger than the screen will limit the window's size to the screen and
  827. // cause the test to fail.
  828. const size = [456, 567];
  829. w.setContentSize(size[0], size[1]);
  830. await new Promise(setImmediate);
  831. const after = w.getContentSize();
  832. expect(after).to.deep.equal(size);
  833. });
  834. it('works for a frameless window', async () => {
  835. w.destroy();
  836. w = new BrowserWindow({
  837. show: false,
  838. frame: false,
  839. width: 400,
  840. height: 400
  841. });
  842. const size = [456, 567];
  843. w.setContentSize(size[0], size[1]);
  844. await new Promise(setImmediate);
  845. const after = w.getContentSize();
  846. expect(after).to.deep.equal(size);
  847. });
  848. });
  849. describe('BrowserWindow.setContentBounds(bounds)', () => {
  850. it('sets the content size and position', async () => {
  851. const bounds = { x: 10, y: 10, width: 250, height: 250 };
  852. const resize = emittedOnce(w, 'resize');
  853. w.setContentBounds(bounds);
  854. await resize;
  855. await delay();
  856. expectBoundsEqual(w.getContentBounds(), bounds);
  857. });
  858. it('works for a frameless window', async () => {
  859. w.destroy();
  860. w = new BrowserWindow({
  861. show: false,
  862. frame: false,
  863. width: 300,
  864. height: 300
  865. });
  866. const bounds = { x: 10, y: 10, width: 250, height: 250 };
  867. const resize = emittedOnce(w, 'resize');
  868. w.setContentBounds(bounds);
  869. await resize;
  870. await delay();
  871. expectBoundsEqual(w.getContentBounds(), bounds);
  872. });
  873. });
  874. describe('BrowserWindow.getBackgroundColor()', () => {
  875. it('returns default value if no backgroundColor is set', () => {
  876. w.destroy();
  877. w = new BrowserWindow({});
  878. expect(w.getBackgroundColor()).to.equal('#FFFFFF');
  879. });
  880. it('returns correct value if backgroundColor is set', () => {
  881. const backgroundColor = '#BBAAFF';
  882. w.destroy();
  883. w = new BrowserWindow({
  884. backgroundColor: backgroundColor
  885. });
  886. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  887. });
  888. it('returns correct value from setBackgroundColor()', () => {
  889. const backgroundColor = '#AABBFF';
  890. w.destroy();
  891. w = new BrowserWindow({});
  892. w.setBackgroundColor(backgroundColor);
  893. expect(w.getBackgroundColor()).to.equal(backgroundColor);
  894. });
  895. });
  896. describe('BrowserWindow.getNormalBounds()', () => {
  897. describe('Normal state', () => {
  898. it('checks normal bounds after resize', async () => {
  899. const size = [300, 400];
  900. const resize = emittedOnce(w, 'resize');
  901. w.setSize(size[0], size[1]);
  902. await resize;
  903. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  904. });
  905. it('checks normal bounds after move', async () => {
  906. const pos = [10, 10];
  907. const move = emittedOnce(w, 'move');
  908. w.setPosition(pos[0], pos[1]);
  909. await move;
  910. expectBoundsEqual(w.getNormalBounds(), w.getBounds());
  911. });
  912. });
  913. ifdescribe(process.platform !== 'linux')('Maximized state', () => {
  914. it('checks normal bounds when maximized', async () => {
  915. const bounds = w.getBounds();
  916. const maximize = emittedOnce(w, 'maximize');
  917. w.show();
  918. w.maximize();
  919. await maximize;
  920. expectBoundsEqual(w.getNormalBounds(), bounds);
  921. });
  922. it('checks normal bounds when unmaximized', async () => {
  923. const bounds = w.getBounds();
  924. w.once('maximize', () => {
  925. w.unmaximize();
  926. });
  927. const unmaximize = emittedOnce(w, 'unmaximize');
  928. w.show();
  929. w.maximize();
  930. await unmaximize;
  931. expectBoundsEqual(w.getNormalBounds(), bounds);
  932. });
  933. it('does not change size for a frameless window with min size', async () => {
  934. w.destroy();
  935. w = new BrowserWindow({
  936. show: false,
  937. frame: false,
  938. width: 300,
  939. height: 300,
  940. minWidth: 300,
  941. minHeight: 300
  942. });
  943. const bounds = w.getBounds();
  944. w.once('maximize', () => {
  945. w.unmaximize();
  946. });
  947. const unmaximize = emittedOnce(w, 'unmaximize');
  948. w.show();
  949. w.maximize();
  950. await unmaximize;
  951. expectBoundsEqual(w.getNormalBounds(), bounds);
  952. });
  953. it('can check transparent window maximization', async () => {
  954. w.destroy();
  955. w = new BrowserWindow({
  956. show: false,
  957. width: 300,
  958. height: 300,
  959. transparent: true
  960. });
  961. const maximize = emittedOnce(w, 'resize');
  962. w.show();
  963. w.maximize();
  964. await maximize;
  965. expect(w.isMaximized()).to.equal(true);
  966. const unmaximize = emittedOnce(w, 'resize');
  967. w.unmaximize();
  968. await unmaximize;
  969. expect(w.isMaximized()).to.equal(false);
  970. });
  971. });
  972. ifdescribe(process.platform !== 'linux')('Minimized state', () => {
  973. it('checks normal bounds when minimized', async () => {
  974. const bounds = w.getBounds();
  975. const minimize = emittedOnce(w, 'minimize');
  976. w.show();
  977. w.minimize();
  978. await minimize;
  979. expectBoundsEqual(w.getNormalBounds(), bounds);
  980. });
  981. it('checks normal bounds when restored', async () => {
  982. const bounds = w.getBounds();
  983. w.once('minimize', () => {
  984. w.restore();
  985. });
  986. const restore = emittedOnce(w, 'restore');
  987. w.show();
  988. w.minimize();
  989. await restore;
  990. expectBoundsEqual(w.getNormalBounds(), bounds);
  991. });
  992. it('does not change size for a frameless window with min size', async () => {
  993. w.destroy();
  994. w = new BrowserWindow({
  995. show: false,
  996. frame: false,
  997. width: 300,
  998. height: 300,
  999. minWidth: 300,
  1000. minHeight: 300
  1001. });
  1002. const bounds = w.getBounds();
  1003. w.once('minimize', () => {
  1004. w.restore();
  1005. });
  1006. const restore = emittedOnce(w, 'restore');
  1007. w.show();
  1008. w.minimize();
  1009. await restore;
  1010. expectBoundsEqual(w.getNormalBounds(), bounds);
  1011. });
  1012. });
  1013. ifdescribe(process.platform === 'win32')('Fullscreen state', () => {
  1014. it('with properties', () => {
  1015. it('can be set with the fullscreen constructor option', () => {
  1016. w = new BrowserWindow({ fullscreen: true });
  1017. expect(w.fullScreen).to.be.true();
  1018. });
  1019. it('can be changed', () => {
  1020. w.fullScreen = false;
  1021. expect(w.fullScreen).to.be.false();
  1022. w.fullScreen = true;
  1023. expect(w.fullScreen).to.be.true();
  1024. });
  1025. it('checks normal bounds when fullscreen\'ed', async () => {
  1026. const bounds = w.getBounds();
  1027. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1028. w.show();
  1029. w.fullScreen = true;
  1030. await enterFullScreen;
  1031. expectBoundsEqual(w.getNormalBounds(), bounds);
  1032. });
  1033. it('checks normal bounds when unfullscreen\'ed', async () => {
  1034. const bounds = w.getBounds();
  1035. w.once('enter-full-screen', () => {
  1036. w.fullScreen = false;
  1037. });
  1038. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1039. w.show();
  1040. w.fullScreen = true;
  1041. await leaveFullScreen;
  1042. expectBoundsEqual(w.getNormalBounds(), bounds);
  1043. });
  1044. });
  1045. it('with functions', () => {
  1046. it('can be set with the fullscreen constructor option', () => {
  1047. w = new BrowserWindow({ fullscreen: true });
  1048. expect(w.isFullScreen()).to.be.true();
  1049. });
  1050. it('can be changed', () => {
  1051. w.setFullScreen(false);
  1052. expect(w.isFullScreen()).to.be.false();
  1053. w.setFullScreen(true);
  1054. expect(w.isFullScreen()).to.be.true();
  1055. });
  1056. it('checks normal bounds when fullscreen\'ed', async () => {
  1057. const bounds = w.getBounds();
  1058. w.show();
  1059. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1060. w.setFullScreen(true);
  1061. await enterFullScreen;
  1062. expectBoundsEqual(w.getNormalBounds(), bounds);
  1063. });
  1064. it('checks normal bounds when unfullscreen\'ed', async () => {
  1065. const bounds = w.getBounds();
  1066. w.show();
  1067. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  1068. w.setFullScreen(true);
  1069. await enterFullScreen;
  1070. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  1071. w.setFullScreen(false);
  1072. await leaveFullScreen;
  1073. expectBoundsEqual(w.getNormalBounds(), bounds);
  1074. });
  1075. });
  1076. });
  1077. });
  1078. });
  1079. ifdescribe(process.platform === 'darwin')('tabbed windows', () => {
  1080. let w = null as unknown as BrowserWindow;
  1081. beforeEach(() => {
  1082. w = new BrowserWindow({ show: false });
  1083. });
  1084. afterEach(async () => {
  1085. await closeWindow(w);
  1086. w = null as unknown as BrowserWindow;
  1087. });
  1088. describe('BrowserWindow.selectPreviousTab()', () => {
  1089. it('does not throw', () => {
  1090. expect(() => {
  1091. w.selectPreviousTab();
  1092. }).to.not.throw();
  1093. });
  1094. });
  1095. describe('BrowserWindow.selectNextTab()', () => {
  1096. it('does not throw', () => {
  1097. expect(() => {
  1098. w.selectNextTab();
  1099. }).to.not.throw();
  1100. });
  1101. });
  1102. describe('BrowserWindow.mergeAllWindows()', () => {
  1103. it('does not throw', () => {
  1104. expect(() => {
  1105. w.mergeAllWindows();
  1106. }).to.not.throw();
  1107. });
  1108. });
  1109. describe('BrowserWindow.moveTabToNewWindow()', () => {
  1110. it('does not throw', () => {
  1111. expect(() => {
  1112. w.moveTabToNewWindow();
  1113. }).to.not.throw();
  1114. });
  1115. });
  1116. describe('BrowserWindow.toggleTabBar()', () => {
  1117. it('does not throw', () => {
  1118. expect(() => {
  1119. w.toggleTabBar();
  1120. }).to.not.throw();
  1121. });
  1122. });
  1123. describe('BrowserWindow.addTabbedWindow()', () => {
  1124. it('does not throw', async () => {
  1125. const tabbedWindow = new BrowserWindow({});
  1126. expect(() => {
  1127. w.addTabbedWindow(tabbedWindow);
  1128. }).to.not.throw();
  1129. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow
  1130. await closeWindow(tabbedWindow, { assertNotWindows: false });
  1131. expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w
  1132. });
  1133. it('throws when called on itself', () => {
  1134. expect(() => {
  1135. w.addTabbedWindow(w);
  1136. }).to.throw('AddTabbedWindow cannot be called by a window on itself.');
  1137. });
  1138. });
  1139. });
  1140. describe('autoHideMenuBar state', () => {
  1141. afterEach(closeAllWindows);
  1142. it('for properties', () => {
  1143. it('can be set with autoHideMenuBar constructor option', () => {
  1144. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1145. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1146. });
  1147. it('can be changed', () => {
  1148. const w = new BrowserWindow({ show: false });
  1149. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1150. w.autoHideMenuBar = true;
  1151. expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar');
  1152. w.autoHideMenuBar = false;
  1153. expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar');
  1154. });
  1155. });
  1156. it('for functions', () => {
  1157. it('can be set with autoHideMenuBar constructor option', () => {
  1158. const w = new BrowserWindow({ show: false, autoHideMenuBar: true });
  1159. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1160. });
  1161. it('can be changed', () => {
  1162. const w = new BrowserWindow({ show: false });
  1163. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1164. w.setAutoHideMenuBar(true);
  1165. expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar');
  1166. w.setAutoHideMenuBar(false);
  1167. expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar');
  1168. });
  1169. });
  1170. });
  1171. describe('BrowserWindow.capturePage(rect)', () => {
  1172. afterEach(closeAllWindows);
  1173. it('returns a Promise with a Buffer', async () => {
  1174. const w = new BrowserWindow({ show: false });
  1175. const image = await w.capturePage({
  1176. x: 0,
  1177. y: 0,
  1178. width: 100,
  1179. height: 100
  1180. });
  1181. expect(image.isEmpty()).to.equal(true);
  1182. });
  1183. it('preserves transparency', async () => {
  1184. const w = new BrowserWindow({ show: false, transparent: true });
  1185. w.loadFile(path.join(fixtures, 'pages', 'theme-color.html'));
  1186. await emittedOnce(w, 'ready-to-show');
  1187. w.show();
  1188. const image = await w.capturePage();
  1189. const imgBuffer = image.toPNG();
  1190. // Check the 25th byte in the PNG.
  1191. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  1192. expect(imgBuffer[25]).to.equal(6);
  1193. });
  1194. });
  1195. describe('BrowserWindow.setProgressBar(progress)', () => {
  1196. let w = null as unknown as BrowserWindow;
  1197. before(() => {
  1198. w = new BrowserWindow({ show: false });
  1199. });
  1200. after(async () => {
  1201. await closeWindow(w);
  1202. w = null as unknown as BrowserWindow;
  1203. });
  1204. it('sets the progress', () => {
  1205. expect(() => {
  1206. if (process.platform === 'darwin') {
  1207. app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png'));
  1208. }
  1209. w.setProgressBar(0.5);
  1210. if (process.platform === 'darwin') {
  1211. app.dock.setIcon(null as any);
  1212. }
  1213. w.setProgressBar(-1);
  1214. }).to.not.throw();
  1215. });
  1216. it('sets the progress using "paused" mode', () => {
  1217. expect(() => {
  1218. w.setProgressBar(0.5, { mode: 'paused' });
  1219. }).to.not.throw();
  1220. });
  1221. it('sets the progress using "error" mode', () => {
  1222. expect(() => {
  1223. w.setProgressBar(0.5, { mode: 'error' });
  1224. }).to.not.throw();
  1225. });
  1226. it('sets the progress using "normal" mode', () => {
  1227. expect(() => {
  1228. w.setProgressBar(0.5, { mode: 'normal' });
  1229. }).to.not.throw();
  1230. });
  1231. });
  1232. describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => {
  1233. let w = null as unknown as BrowserWindow;
  1234. beforeEach(() => {
  1235. w = new BrowserWindow({ show: false });
  1236. });
  1237. afterEach(async () => {
  1238. await closeWindow(w);
  1239. w = null as unknown as BrowserWindow;
  1240. });
  1241. it('sets the window as always on top', () => {
  1242. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1243. w.setAlwaysOnTop(true, 'screen-saver');
  1244. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1245. w.setAlwaysOnTop(false);
  1246. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1247. w.setAlwaysOnTop(true);
  1248. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1249. });
  1250. ifit(process.platform === 'darwin')('resets the windows level on minimize', () => {
  1251. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1252. w.setAlwaysOnTop(true, 'screen-saver');
  1253. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1254. w.minimize();
  1255. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1256. w.restore();
  1257. expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop');
  1258. });
  1259. it('causes the right value to be emitted on `always-on-top-changed`', async () => {
  1260. const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed');
  1261. expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop');
  1262. w.setAlwaysOnTop(true);
  1263. const [, alwaysOnTop] = await alwaysOnTopChanged;
  1264. expect(alwaysOnTop).to.be.true('is not alwaysOnTop');
  1265. });
  1266. });
  1267. describe('preconnect feature', () => {
  1268. let w = null as unknown as BrowserWindow;
  1269. let server = null as unknown as http.Server;
  1270. let url = null as unknown as string;
  1271. let connections = 0;
  1272. beforeEach(async () => {
  1273. connections = 0;
  1274. server = http.createServer((req, res) => {
  1275. if (req.url === '/link') {
  1276. res.setHeader('Content-type', 'text/html');
  1277. res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>');
  1278. return;
  1279. }
  1280. res.end();
  1281. });
  1282. server.on('connection', () => { connections++; });
  1283. await new Promise(resolve => server.listen(0, '127.0.0.1', () => resolve()));
  1284. url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  1285. });
  1286. afterEach(async () => {
  1287. server.close();
  1288. await closeWindow(w);
  1289. w = null as unknown as BrowserWindow;
  1290. server = null as unknown as http.Server;
  1291. });
  1292. it('calling preconnect() connects to the server', async () => {
  1293. w = new BrowserWindow({ show: false });
  1294. w.webContents.on('did-start-navigation', (event, url) => {
  1295. w.webContents.session.preconnect({ url, numSockets: 4 });
  1296. });
  1297. await w.loadURL(url);
  1298. expect(connections).to.equal(4);
  1299. });
  1300. it('does not preconnect unless requested', async () => {
  1301. w = new BrowserWindow({ show: false });
  1302. await w.loadURL(url);
  1303. expect(connections).to.equal(1);
  1304. });
  1305. it('parses <link rel=preconnect>', async () => {
  1306. w = new BrowserWindow({ show: true });
  1307. const p = emittedOnce(w.webContents.session, 'preconnect');
  1308. w.loadURL(url + '/link');
  1309. const [, preconnectUrl, allowCredentials] = await p;
  1310. expect(preconnectUrl).to.equal('http://example.com/');
  1311. expect(allowCredentials).to.be.true('allowCredentials');
  1312. });
  1313. });
  1314. describe('BrowserWindow.setAutoHideCursor(autoHide)', () => {
  1315. let w = null as unknown as BrowserWindow;
  1316. beforeEach(() => {
  1317. w = new BrowserWindow({ show: false });
  1318. });
  1319. afterEach(async () => {
  1320. await closeWindow(w);
  1321. w = null as unknown as BrowserWindow;
  1322. });
  1323. ifit(process.platform === 'darwin')('on macOS', () => {
  1324. it('allows changing cursor auto-hiding', () => {
  1325. expect(() => {
  1326. w.setAutoHideCursor(false);
  1327. w.setAutoHideCursor(true);
  1328. }).to.not.throw();
  1329. });
  1330. });
  1331. ifit(process.platform !== 'darwin')('on non-macOS platforms', () => {
  1332. it('is not available', () => {
  1333. expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function');
  1334. });
  1335. });
  1336. });
  1337. ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => {
  1338. afterEach(closeAllWindows);
  1339. it('does not throw', () => {
  1340. const w = new BrowserWindow({ show: false });
  1341. expect(() => {
  1342. w.setWindowButtonVisibility(true);
  1343. w.setWindowButtonVisibility(false);
  1344. }).to.not.throw();
  1345. });
  1346. it('throws with custom title bar buttons', () => {
  1347. expect(() => {
  1348. const w = new BrowserWindow({
  1349. show: false,
  1350. titleBarStyle: 'customButtonsOnHover',
  1351. frame: false
  1352. });
  1353. w.setWindowButtonVisibility(true);
  1354. }).to.throw('Not supported for this window');
  1355. });
  1356. });
  1357. ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => {
  1358. afterEach(closeAllWindows);
  1359. it('allows setting, changing, and removing the vibrancy', () => {
  1360. const w = new BrowserWindow({ show: false });
  1361. expect(() => {
  1362. w.setVibrancy('light');
  1363. w.setVibrancy('dark');
  1364. w.setVibrancy(null);
  1365. w.setVibrancy('ultra-dark');
  1366. w.setVibrancy('' as any);
  1367. }).to.not.throw();
  1368. });
  1369. });
  1370. ifdescribe(process.platform === 'darwin')('BrowserWindow.getTrafficLightPosition(pos)', () => {
  1371. afterEach(closeAllWindows);
  1372. it('gets the set traffic light position property', () => {
  1373. const pos = { x: 10, y: 10 };
  1374. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1375. const currentPosition = w.getTrafficLightPosition();
  1376. expect(currentPosition).to.deep.equal(pos);
  1377. });
  1378. });
  1379. ifdescribe(process.platform === 'darwin')('BrowserWindow.setTrafficLightPosition(pos)', () => {
  1380. afterEach(closeAllWindows);
  1381. it('can set the traffic light position property', () => {
  1382. const pos = { x: 10, y: 10 };
  1383. const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos });
  1384. w.setTrafficLightPosition(pos);
  1385. const currentPosition = w.getTrafficLightPosition();
  1386. expect(currentPosition).to.deep.equal(pos);
  1387. });
  1388. });
  1389. ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => {
  1390. afterEach(closeAllWindows);
  1391. it('supports setting the app details', () => {
  1392. const w = new BrowserWindow({ show: false });
  1393. const iconPath = path.join(fixtures, 'assets', 'icon.ico');
  1394. expect(() => {
  1395. w.setAppDetails({ appId: 'my.app.id' });
  1396. w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 });
  1397. w.setAppDetails({ appIconPath: iconPath });
  1398. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' });
  1399. w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' });
  1400. w.setAppDetails({ relaunchDisplayName: 'My app name' });
  1401. w.setAppDetails({
  1402. appId: 'my.app.id',
  1403. appIconPath: iconPath,
  1404. appIconIndex: 0,
  1405. relaunchCommand: 'my-app.exe arg1 arg2',
  1406. relaunchDisplayName: 'My app name'
  1407. });
  1408. w.setAppDetails({});
  1409. }).to.not.throw();
  1410. expect(() => {
  1411. (w.setAppDetails as any)();
  1412. }).to.throw('Insufficient number of arguments.');
  1413. });
  1414. });
  1415. describe('BrowserWindow.fromId(id)', () => {
  1416. afterEach(closeAllWindows);
  1417. it('returns the window with id', () => {
  1418. const w = new BrowserWindow({ show: false });
  1419. expect(BrowserWindow.fromId(w.id).id).to.equal(w.id);
  1420. });
  1421. });
  1422. describe('BrowserWindow.fromWebContents(webContents)', () => {
  1423. afterEach(closeAllWindows);
  1424. it('returns the window with the webContents', () => {
  1425. const w = new BrowserWindow({ show: false });
  1426. const found = BrowserWindow.fromWebContents(w.webContents);
  1427. expect(found!.id).to.equal(w.id);
  1428. });
  1429. it('returns null for webContents without a BrowserWindow', () => {
  1430. const contents = (webContents as any).create({});
  1431. try {
  1432. expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)');
  1433. } finally {
  1434. contents.destroy();
  1435. }
  1436. });
  1437. });
  1438. describe('BrowserWindow.openDevTools()', () => {
  1439. afterEach(closeAllWindows);
  1440. it('does not crash for frameless window', () => {
  1441. const w = new BrowserWindow({ show: false, frame: false });
  1442. w.webContents.openDevTools();
  1443. });
  1444. });
  1445. describe('BrowserWindow.fromBrowserView(browserView)', () => {
  1446. afterEach(closeAllWindows);
  1447. it('returns the window with the browserView', () => {
  1448. const w = new BrowserWindow({ show: false });
  1449. const bv = new BrowserView();
  1450. w.setBrowserView(bv);
  1451. expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
  1452. // if BrowserView isn't explicitly destroyed, it will crash in GC later
  1453. bv.destroy();
  1454. });
  1455. it('returns undefined if not attached', () => {
  1456. const bv = new BrowserView();
  1457. expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
  1458. // if BrowserView isn't explicitly destroyed, it will crash in GC later
  1459. bv.destroy();
  1460. });
  1461. });
  1462. describe('BrowserWindow.setOpacity(opacity)', () => {
  1463. afterEach(closeAllWindows);
  1464. ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => {
  1465. it('make window with initial opacity', () => {
  1466. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  1467. expect(w.getOpacity()).to.equal(0.5);
  1468. });
  1469. it('allows setting the opacity', () => {
  1470. const w = new BrowserWindow({ show: false });
  1471. expect(() => {
  1472. w.setOpacity(0.0);
  1473. expect(w.getOpacity()).to.equal(0.0);
  1474. w.setOpacity(0.5);
  1475. expect(w.getOpacity()).to.equal(0.5);
  1476. w.setOpacity(1.0);
  1477. expect(w.getOpacity()).to.equal(1.0);
  1478. }).to.not.throw();
  1479. });
  1480. it('clamps opacity to [0.0...1.0]', () => {
  1481. const w = new BrowserWindow({ show: false, opacity: 0.5 });
  1482. w.setOpacity(100);
  1483. expect(w.getOpacity()).to.equal(1.0);
  1484. w.setOpacity(-100);
  1485. expect(w.getOpacity()).to.equal(0.0);
  1486. });
  1487. });
  1488. ifdescribe(process.platform === 'linux')(('Linux'), () => {
  1489. it('sets 1 regardless of parameter', () => {
  1490. const w = new BrowserWindow({ show: false });
  1491. w.setOpacity(0);
  1492. expect(w.getOpacity()).to.equal(1.0);
  1493. w.setOpacity(0.5);
  1494. expect(w.getOpacity()).to.equal(1.0);
  1495. });
  1496. });
  1497. });
  1498. describe('BrowserWindow.setShape(rects)', () => {
  1499. afterEach(closeAllWindows);
  1500. it('allows setting shape', () => {
  1501. const w = new BrowserWindow({ show: false });
  1502. expect(() => {
  1503. w.setShape([]);
  1504. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]);
  1505. w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]);
  1506. w.setShape([]);
  1507. }).to.not.throw();
  1508. });
  1509. });
  1510. describe('"useContentSize" option', () => {
  1511. afterEach(closeAllWindows);
  1512. it('make window created with content size when used', () => {
  1513. const w = new BrowserWindow({
  1514. show: false,
  1515. width: 400,
  1516. height: 400,
  1517. useContentSize: true
  1518. });
  1519. const contentSize = w.getContentSize();
  1520. expect(contentSize).to.deep.equal([400, 400]);
  1521. });
  1522. it('make window created with window size when not used', () => {
  1523. const w = new BrowserWindow({
  1524. show: false,
  1525. width: 400,
  1526. height: 400
  1527. });
  1528. const size = w.getSize();
  1529. expect(size).to.deep.equal([400, 400]);
  1530. });
  1531. it('works for a frameless window', () => {
  1532. const w = new BrowserWindow({
  1533. show: false,
  1534. frame: false,
  1535. width: 400,
  1536. height: 400,
  1537. useContentSize: true
  1538. });
  1539. const contentSize = w.getContentSize();
  1540. expect(contentSize).to.deep.equal([400, 400]);
  1541. const size = w.getSize();
  1542. expect(size).to.deep.equal([400, 400]);
  1543. });
  1544. });
  1545. ifdescribe(process.platform === 'darwin' && parseInt(os.release().split('.')[0]) >= 14)('"titleBarStyle" option', () => {
  1546. afterEach(closeAllWindows);
  1547. it('creates browser window with hidden title bar', () => {
  1548. const w = new BrowserWindow({
  1549. show: false,
  1550. width: 400,
  1551. height: 400,
  1552. titleBarStyle: 'hidden'
  1553. });
  1554. const contentSize = w.getContentSize();
  1555. expect(contentSize).to.deep.equal([400, 400]);
  1556. });
  1557. it('creates browser window with hidden inset title bar', () => {
  1558. const w = new BrowserWindow({
  1559. show: false,
  1560. width: 400,
  1561. height: 400,
  1562. titleBarStyle: 'hiddenInset'
  1563. });
  1564. const contentSize = w.getContentSize();
  1565. expect(contentSize).to.deep.equal([400, 400]);
  1566. });
  1567. });
  1568. ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => {
  1569. afterEach(closeAllWindows);
  1570. it('can move the window out of screen', () => {
  1571. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  1572. w.setPosition(-10, 50);
  1573. const after = w.getPosition();
  1574. expect(after).to.deep.equal([-10, 50]);
  1575. });
  1576. it('cannot move the window behind menu bar', () => {
  1577. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  1578. w.setPosition(-10, -10);
  1579. const after = w.getPosition();
  1580. expect(after[1]).to.be.at.least(0);
  1581. });
  1582. it('can move the window behind menu bar if it has no frame', () => {
  1583. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false });
  1584. w.setPosition(-10, -10);
  1585. const after = w.getPosition();
  1586. expect(after[0]).to.be.equal(-10);
  1587. expect(after[1]).to.be.equal(-10);
  1588. });
  1589. it('without it, cannot move the window out of screen', () => {
  1590. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  1591. w.setPosition(-10, -10);
  1592. const after = w.getPosition();
  1593. expect(after[1]).to.be.at.least(0);
  1594. });
  1595. it('can set the window larger than screen', () => {
  1596. const w = new BrowserWindow({ show: true, enableLargerThanScreen: true });
  1597. const size = screen.getPrimaryDisplay().size;
  1598. size.width += 100;
  1599. size.height += 100;
  1600. w.setSize(size.width, size.height);
  1601. expectBoundsEqual(w.getSize(), [size.width, size.height]);
  1602. });
  1603. it('without it, cannot set the window larger than screen', () => {
  1604. const w = new BrowserWindow({ show: true, enableLargerThanScreen: false });
  1605. const size = screen.getPrimaryDisplay().size;
  1606. size.width += 100;
  1607. size.height += 100;
  1608. w.setSize(size.width, size.height);
  1609. expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height);
  1610. });
  1611. });
  1612. ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => {
  1613. afterEach(closeAllWindows);
  1614. it('sets the window width to the page width when used', () => {
  1615. const w = new BrowserWindow({
  1616. show: false,
  1617. width: 500,
  1618. height: 400,
  1619. zoomToPageWidth: true
  1620. });
  1621. w.maximize();
  1622. expect(w.getSize()[0]).to.equal(500);
  1623. });
  1624. });
  1625. describe('"tabbingIdentifier" option', () => {
  1626. afterEach(closeAllWindows);
  1627. it('can be set on a window', () => {
  1628. expect(() => {
  1629. /* eslint-disable no-new */
  1630. new BrowserWindow({
  1631. tabbingIdentifier: 'group1'
  1632. });
  1633. new BrowserWindow({
  1634. tabbingIdentifier: 'group2',
  1635. frame: false
  1636. });
  1637. /* eslint-enable no-new */
  1638. }).not.to.throw();
  1639. });
  1640. });
  1641. describe('"webPreferences" option', () => {
  1642. afterEach(() => { ipcMain.removeAllListeners('answer'); });
  1643. afterEach(closeAllWindows);
  1644. describe('"preload" option', () => {
  1645. const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => {
  1646. it(name, async () => {
  1647. const w = new BrowserWindow({
  1648. webPreferences: {
  1649. ...webPrefs,
  1650. preload: path.resolve(fixtures, 'module', 'empty.js')
  1651. },
  1652. show: false
  1653. });
  1654. w.loadFile(path.join(fixtures, 'api', 'no-leak.html'));
  1655. const [, result] = await emittedOnce(ipcMain, 'leak-result');
  1656. expect(result).to.have.property('require', 'undefined');
  1657. expect(result).to.have.property('exports', 'undefined');
  1658. expect(result).to.have.property('windowExports', 'undefined');
  1659. expect(result).to.have.property('windowPreload', 'undefined');
  1660. expect(result).to.have.property('windowRequire', 'undefined');
  1661. });
  1662. };
  1663. doesNotLeakSpec('does not leak require', {
  1664. nodeIntegration: false,
  1665. sandbox: false,
  1666. contextIsolation: false
  1667. });
  1668. doesNotLeakSpec('does not leak require when sandbox is enabled', {
  1669. nodeIntegration: false,
  1670. sandbox: true,
  1671. contextIsolation: false
  1672. });
  1673. doesNotLeakSpec('does not leak require when context isolation is enabled', {
  1674. nodeIntegration: false,
  1675. sandbox: false,
  1676. contextIsolation: true
  1677. });
  1678. doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', {
  1679. nodeIntegration: false,
  1680. sandbox: true,
  1681. contextIsolation: true
  1682. });
  1683. it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => {
  1684. let w = new BrowserWindow({
  1685. webPreferences: {
  1686. contextIsolation: false,
  1687. nodeIntegration: false,
  1688. preload: path.resolve(fixtures, 'module', 'empty.js')
  1689. },
  1690. show: false
  1691. });
  1692. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  1693. const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result');
  1694. expect(notIsolated).to.have.property('globals');
  1695. w.destroy();
  1696. w = new BrowserWindow({
  1697. webPreferences: {
  1698. contextIsolation: true,
  1699. nodeIntegration: false,
  1700. preload: path.resolve(fixtures, 'module', 'empty.js')
  1701. },
  1702. show: false
  1703. });
  1704. w.loadFile(path.join(fixtures, 'api', 'globals.html'));
  1705. const [, isolated] = await emittedOnce(ipcMain, 'leak-result');
  1706. expect(isolated).to.have.property('globals');
  1707. const notIsolatedGlobals = new Set(notIsolated.globals);
  1708. for (const isolatedGlobal of isolated.globals) {
  1709. notIsolatedGlobals.delete(isolatedGlobal);
  1710. }
  1711. expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals');
  1712. });
  1713. it('loads the script before other scripts in window', async () => {
  1714. const preload = path.join(fixtures, 'module', 'set-global.js');
  1715. const w = new BrowserWindow({
  1716. show: false,
  1717. webPreferences: {
  1718. nodeIntegration: true,
  1719. preload
  1720. }
  1721. });
  1722. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1723. const [, test] = await emittedOnce(ipcMain, 'answer');
  1724. expect(test).to.eql('preload');
  1725. });
  1726. it('can successfully delete the Buffer global', async () => {
  1727. const preload = path.join(__dirname, 'fixtures', 'module', 'delete-buffer.js');
  1728. const w = new BrowserWindow({
  1729. show: false,
  1730. webPreferences: {
  1731. nodeIntegration: true,
  1732. enableRemoteModule: true,
  1733. preload
  1734. }
  1735. });
  1736. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1737. const [, test] = await emittedOnce(ipcMain, 'answer');
  1738. expect(test).to.eql(Buffer.from('buffer'));
  1739. });
  1740. it('has synchronous access to all eventual window APIs', async () => {
  1741. const preload = path.join(fixtures, 'module', 'access-blink-apis.js');
  1742. const w = new BrowserWindow({
  1743. show: false,
  1744. webPreferences: {
  1745. nodeIntegration: true,
  1746. preload
  1747. }
  1748. });
  1749. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1750. const [, test] = await emittedOnce(ipcMain, 'answer');
  1751. expect(test).to.be.an('object');
  1752. expect(test.atPreload).to.be.an('array');
  1753. expect(test.atLoad).to.be.an('array');
  1754. expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs');
  1755. });
  1756. });
  1757. describe('session preload scripts', function () {
  1758. const preloads = [
  1759. path.join(fixtures, 'module', 'set-global-preload-1.js'),
  1760. path.join(fixtures, 'module', 'set-global-preload-2.js'),
  1761. path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js'))
  1762. ];
  1763. const defaultSession = session.defaultSession;
  1764. beforeEach(() => {
  1765. expect(defaultSession.getPreloads()).to.deep.equal([]);
  1766. defaultSession.setPreloads(preloads);
  1767. });
  1768. afterEach(() => {
  1769. defaultSession.setPreloads([]);
  1770. });
  1771. it('can set multiple session preload script', () => {
  1772. expect(defaultSession.getPreloads()).to.deep.equal(preloads);
  1773. });
  1774. const generateSpecs = (description: string, sandbox: boolean) => {
  1775. describe(description, () => {
  1776. it('loads the script before other scripts in window including normal preloads', async () => {
  1777. const w = new BrowserWindow({
  1778. show: false,
  1779. webPreferences: {
  1780. sandbox,
  1781. preload: path.join(fixtures, 'module', 'get-global-preload.js')
  1782. }
  1783. });
  1784. w.loadURL('about:blank');
  1785. const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars');
  1786. expect(preload1).to.equal('preload-1');
  1787. expect(preload2).to.equal('preload-1-2');
  1788. expect(preload3).to.be.undefined('preload 3');
  1789. });
  1790. });
  1791. };
  1792. generateSpecs('without sandbox', false);
  1793. generateSpecs('with sandbox', true);
  1794. });
  1795. describe('"additionalArguments" option', () => {
  1796. it('adds extra args to process.argv in the renderer process', async () => {
  1797. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  1798. const w = new BrowserWindow({
  1799. show: false,
  1800. webPreferences: {
  1801. nodeIntegration: true,
  1802. preload,
  1803. additionalArguments: ['--my-magic-arg']
  1804. }
  1805. });
  1806. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1807. const [, argv] = await emittedOnce(ipcMain, 'answer');
  1808. expect(argv).to.include('--my-magic-arg');
  1809. });
  1810. it('adds extra value args to process.argv in the renderer process', async () => {
  1811. const preload = path.join(fixtures, 'module', 'check-arguments.js');
  1812. const w = new BrowserWindow({
  1813. show: false,
  1814. webPreferences: {
  1815. nodeIntegration: true,
  1816. preload,
  1817. additionalArguments: ['--my-magic-arg=foo']
  1818. }
  1819. });
  1820. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1821. const [, argv] = await emittedOnce(ipcMain, 'answer');
  1822. expect(argv).to.include('--my-magic-arg=foo');
  1823. });
  1824. });
  1825. describe('"node-integration" option', () => {
  1826. it('disables node integration by default', async () => {
  1827. const preload = path.join(fixtures, 'module', 'send-later.js');
  1828. const w = new BrowserWindow({
  1829. show: false,
  1830. webPreferences: {
  1831. preload
  1832. }
  1833. });
  1834. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1835. const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer');
  1836. expect(typeofProcess).to.equal('undefined');
  1837. expect(typeofBuffer).to.equal('undefined');
  1838. });
  1839. });
  1840. ifdescribe(features.isRemoteModuleEnabled())('"enableRemoteModule" option', () => {
  1841. const generateSpecs = (description: string, sandbox: boolean) => {
  1842. describe(description, () => {
  1843. const preload = path.join(__dirname, 'fixtures', 'module', 'preload-remote.js');
  1844. it('disables the remote module by default', async () => {
  1845. const w = new BrowserWindow({
  1846. show: false,
  1847. webPreferences: {
  1848. preload,
  1849. sandbox
  1850. }
  1851. });
  1852. const p = emittedOnce(ipcMain, 'remote');
  1853. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1854. const [, remote] = await p;
  1855. expect(remote).to.equal('undefined');
  1856. });
  1857. it('disables the remote module when false', async () => {
  1858. const w = new BrowserWindow({
  1859. show: false,
  1860. webPreferences: {
  1861. preload,
  1862. sandbox,
  1863. enableRemoteModule: false
  1864. }
  1865. });
  1866. const p = emittedOnce(ipcMain, 'remote');
  1867. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1868. const [, remote] = await p;
  1869. expect(remote).to.equal('undefined');
  1870. });
  1871. it('enables the remote module when true', async () => {
  1872. const w = new BrowserWindow({
  1873. show: false,
  1874. webPreferences: {
  1875. preload,
  1876. sandbox,
  1877. enableRemoteModule: true
  1878. }
  1879. });
  1880. const p = emittedOnce(ipcMain, 'remote');
  1881. w.loadFile(path.join(fixtures, 'api', 'blank.html'));
  1882. const [, remote] = await p;
  1883. expect(remote).to.equal('object');
  1884. });
  1885. });
  1886. };
  1887. generateSpecs('without sandbox', false);
  1888. generateSpecs('with sandbox', true);
  1889. });
  1890. describe('"sandbox" option', () => {
  1891. function waitForEvents<T> (emitter: { once: Function }, events: string[], callback: () => void) {
  1892. let count = events.length;
  1893. for (const event of events) {
  1894. emitter.once(event, () => {
  1895. if (!--count) callback();
  1896. });
  1897. }
  1898. }
  1899. const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js');
  1900. let server: http.Server = null as unknown as http.Server;
  1901. let serverUrl: string = null as unknown as string;
  1902. before((done) => {
  1903. server = http.createServer((request, response) => {
  1904. switch (request.url) {
  1905. case '/cross-site':
  1906. response.end(`<html><body><h1>${request.url}</h1></body></html>`);
  1907. break;
  1908. default:
  1909. throw new Error(`unsupported endpoint: ${request.url}`);
  1910. }
  1911. }).listen(0, '127.0.0.1', () => {
  1912. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  1913. done();
  1914. });
  1915. });
  1916. after(() => {
  1917. server.close();
  1918. });
  1919. it('exposes ipcRenderer to preload script', async () => {
  1920. const w = new BrowserWindow({
  1921. show: false,
  1922. webPreferences: {
  1923. sandbox: true,
  1924. preload
  1925. }
  1926. });
  1927. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1928. const [, test] = await emittedOnce(ipcMain, 'answer');
  1929. expect(test).to.equal('preload');
  1930. });
  1931. it('exposes ipcRenderer to preload script (path has special chars)', async () => {
  1932. const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js');
  1933. const w = new BrowserWindow({
  1934. show: false,
  1935. webPreferences: {
  1936. sandbox: true,
  1937. preload: preloadSpecialChars
  1938. }
  1939. });
  1940. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  1941. const [, test] = await emittedOnce(ipcMain, 'answer');
  1942. expect(test).to.equal('preload');
  1943. });
  1944. it('exposes "loaded" event to preload script', async () => {
  1945. const w = new BrowserWindow({
  1946. show: false,
  1947. webPreferences: {
  1948. sandbox: true,
  1949. preload
  1950. }
  1951. });
  1952. w.loadURL('about:blank');
  1953. await emittedOnce(ipcMain, 'process-loaded');
  1954. });
  1955. it('exposes "exit" event to preload script', async () => {
  1956. const w = new BrowserWindow({
  1957. show: false,
  1958. webPreferences: {
  1959. sandbox: true,
  1960. preload
  1961. }
  1962. });
  1963. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event');
  1964. const pageUrl = 'file://' + htmlPath;
  1965. w.loadURL(pageUrl);
  1966. const [, url] = await emittedOnce(ipcMain, 'answer');
  1967. const expectedUrl = process.platform === 'win32'
  1968. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  1969. : pageUrl;
  1970. expect(url).to.equal(expectedUrl);
  1971. });
  1972. it('should open windows in same domain with cross-scripting enabled', async () => {
  1973. const w = new BrowserWindow({
  1974. show: false,
  1975. webPreferences: {
  1976. sandbox: true,
  1977. preload
  1978. }
  1979. });
  1980. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  1981. options.webPreferences!.preload = preload;
  1982. });
  1983. const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open');
  1984. const pageUrl = 'file://' + htmlPath;
  1985. const answer = emittedOnce(ipcMain, 'answer');
  1986. w.loadURL(pageUrl);
  1987. const [, url, frameName, , options] = await emittedOnce(w.webContents, 'new-window');
  1988. const expectedUrl = process.platform === 'win32'
  1989. ? 'file:///' + htmlPath.replace(/\\/g, '/')
  1990. : pageUrl;
  1991. expect(url).to.equal(expectedUrl);
  1992. expect(frameName).to.equal('popup!');
  1993. expect(options.width).to.equal(500);
  1994. expect(options.height).to.equal(600);
  1995. const [, html] = await answer;
  1996. expect(html).to.equal('<h1>scripting from opener</h1>');
  1997. });
  1998. it('should open windows in another domain with cross-scripting disabled', async () => {
  1999. const w = new BrowserWindow({
  2000. show: false,
  2001. webPreferences: {
  2002. sandbox: true,
  2003. preload
  2004. }
  2005. });
  2006. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2007. options.webPreferences!.preload = preload;
  2008. });
  2009. w.loadFile(
  2010. path.join(__dirname, 'fixtures', 'api', 'sandbox.html'),
  2011. { search: 'window-open-external' }
  2012. );
  2013. // Wait for a message from the main window saying that it's ready.
  2014. await emittedOnce(ipcMain, 'opener-loaded');
  2015. // Ask the opener to open a popup with window.opener.
  2016. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html".
  2017. w.webContents.send('open-the-popup', expectedPopupUrl);
  2018. // The page is going to open a popup that it won't be able to close.
  2019. // We have to close it from here later.
  2020. const [, popupWindow] = await emittedOnce(app, 'browser-window-created');
  2021. // Ask the popup window for details.
  2022. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded');
  2023. popupWindow.webContents.send('provide-details');
  2024. const [, openerIsNull, , locationHref] = await detailsAnswer;
  2025. expect(openerIsNull).to.be.false('window.opener is null');
  2026. expect(locationHref).to.equal(expectedPopupUrl);
  2027. // Ask the page to access the popup.
  2028. const touchPopupResult = emittedOnce(ipcMain, 'answer');
  2029. w.webContents.send('touch-the-popup');
  2030. const [, popupAccessMessage] = await touchPopupResult;
  2031. // Ask the popup to access the opener.
  2032. const touchOpenerResult = emittedOnce(ipcMain, 'answer');
  2033. popupWindow.webContents.send('touch-the-opener');
  2034. const [, openerAccessMessage] = await touchOpenerResult;
  2035. // We don't need the popup anymore, and its parent page can't close it,
  2036. // so let's close it from here before we run any checks.
  2037. await closeWindow(popupWindow, { assertNotWindows: false });
  2038. expect(popupAccessMessage).to.be.a('string',
  2039. 'child\'s .document is accessible from its parent window');
  2040. expect(popupAccessMessage).to.match(/^Blocked a frame with origin/);
  2041. expect(openerAccessMessage).to.be.a('string',
  2042. 'opener .document is accessible from a popup window');
  2043. expect(openerAccessMessage).to.match(/^Blocked a frame with origin/);
  2044. });
  2045. it('should inherit the sandbox setting in opened windows', async () => {
  2046. const w = new BrowserWindow({
  2047. show: false,
  2048. webPreferences: {
  2049. sandbox: true
  2050. }
  2051. });
  2052. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2053. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2054. options.webPreferences!.preload = preloadPath;
  2055. });
  2056. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2057. const [, args] = await emittedOnce(ipcMain, 'answer');
  2058. expect(args).to.include('--enable-sandbox');
  2059. });
  2060. it('should open windows with the options configured via new-window event listeners', async () => {
  2061. const w = new BrowserWindow({
  2062. show: false,
  2063. webPreferences: {
  2064. sandbox: true
  2065. }
  2066. });
  2067. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2068. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2069. options.webPreferences!.preload = preloadPath;
  2070. const prefs = options.webPreferences as any;
  2071. prefs.foo = 'bar';
  2072. });
  2073. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2074. const [[, childWebContents]] = await Promise.all([
  2075. emittedOnce(app, 'web-contents-created'),
  2076. emittedOnce(ipcMain, 'answer')
  2077. ]);
  2078. const webPreferences = (childWebContents as any).getLastWebPreferences();
  2079. expect(webPreferences.foo).to.equal('bar');
  2080. });
  2081. it('should set ipc event sender correctly', (done) => {
  2082. const w = new BrowserWindow({
  2083. show: false,
  2084. webPreferences: {
  2085. sandbox: true,
  2086. preload
  2087. }
  2088. });
  2089. let childWc: WebContents | null = null;
  2090. w.webContents.on('new-window', (event, url, frameName, disposition, options) => {
  2091. options.webPreferences!.preload = preload;
  2092. childWc = (options as any).webContents;
  2093. expect(w.webContents).to.not.equal(childWc);
  2094. });
  2095. ipcMain.once('parent-ready', function (event) {
  2096. expect(event.sender).to.equal(w.webContents, 'sender should be the parent');
  2097. event.sender.send('verified');
  2098. });
  2099. ipcMain.once('child-ready', function (event) {
  2100. expect(childWc).to.not.be.null('child webcontents should be available');
  2101. expect(event.sender).to.equal(childWc, 'sender should be the child');
  2102. event.sender.send('verified');
  2103. });
  2104. waitForEvents(ipcMain, [
  2105. 'parent-answer',
  2106. 'child-answer'
  2107. ], done);
  2108. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' });
  2109. });
  2110. describe('event handling', () => {
  2111. let w: BrowserWindow = null as unknown as BrowserWindow;
  2112. beforeEach(() => {
  2113. w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } });
  2114. });
  2115. it('works for window events', (done) => {
  2116. waitForEvents(w, [
  2117. 'page-title-updated'
  2118. ], done);
  2119. w.loadURL('data:text/html,<script>document.title = \'changed\'</script>');
  2120. });
  2121. it('works for stop events', (done) => {
  2122. waitForEvents(w.webContents, [
  2123. 'did-navigate',
  2124. 'did-fail-load',
  2125. 'did-stop-loading'
  2126. ], done);
  2127. w.loadURL('data:text/html,<script>stop()</script>');
  2128. });
  2129. it('works for web contents events', (done) => {
  2130. waitForEvents(w.webContents, [
  2131. 'did-finish-load',
  2132. 'did-frame-finish-load',
  2133. 'did-navigate-in-page',
  2134. 'will-navigate',
  2135. 'did-start-loading',
  2136. 'did-stop-loading',
  2137. 'did-frame-finish-load',
  2138. 'dom-ready'
  2139. ], done);
  2140. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' });
  2141. });
  2142. });
  2143. it('supports calling preventDefault on new-window events', (done) => {
  2144. const w = new BrowserWindow({
  2145. show: false,
  2146. webPreferences: {
  2147. sandbox: true
  2148. }
  2149. });
  2150. const initialWebContents = webContents.getAllWebContents().map((i) => i.id);
  2151. w.webContents.once('new-window', (e) => {
  2152. e.preventDefault();
  2153. // We need to give it some time so the windows get properly disposed (at least on OSX).
  2154. setTimeout(() => {
  2155. const currentWebContents = webContents.getAllWebContents().map((i) => i.id);
  2156. try {
  2157. expect(currentWebContents).to.deep.equal(initialWebContents);
  2158. done();
  2159. } catch (error) {
  2160. done(e);
  2161. }
  2162. }, 100);
  2163. });
  2164. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  2165. });
  2166. // see #9387
  2167. ifit(features.isRemoteModuleEnabled())('properly manages remote object references after page reload', (done) => {
  2168. const w = new BrowserWindow({
  2169. show: false,
  2170. webPreferences: {
  2171. preload,
  2172. sandbox: true,
  2173. enableRemoteModule: true
  2174. }
  2175. });
  2176. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'reload-remote' });
  2177. ipcMain.on('get-remote-module-path', (event) => {
  2178. event.returnValue = path.join(fixtures, 'module', 'hello.js');
  2179. });
  2180. let reload = false;
  2181. ipcMain.on('reloaded', (event) => {
  2182. event.returnValue = reload;
  2183. reload = !reload;
  2184. });
  2185. ipcMain.once('reload', (event) => {
  2186. event.sender.reload();
  2187. });
  2188. ipcMain.once('answer', (event, arg) => {
  2189. ipcMain.removeAllListeners('reloaded');
  2190. ipcMain.removeAllListeners('get-remote-module-path');
  2191. try {
  2192. expect(arg).to.equal('hi');
  2193. done();
  2194. } catch (e) {
  2195. done(e);
  2196. }
  2197. });
  2198. });
  2199. ifit(features.isRemoteModuleEnabled())('properly manages remote object references after page reload in child window', (done) => {
  2200. const w = new BrowserWindow({
  2201. show: false,
  2202. webPreferences: {
  2203. preload,
  2204. sandbox: true,
  2205. enableRemoteModule: true
  2206. }
  2207. });
  2208. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2209. options.webPreferences!.preload = preload;
  2210. });
  2211. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'reload-remote-child' });
  2212. ipcMain.on('get-remote-module-path', (event) => {
  2213. event.returnValue = path.join(fixtures, 'module', 'hello-child.js');
  2214. });
  2215. let reload = false;
  2216. ipcMain.on('reloaded', (event) => {
  2217. event.returnValue = reload;
  2218. reload = !reload;
  2219. });
  2220. ipcMain.once('reload', (event) => {
  2221. event.sender.reload();
  2222. });
  2223. ipcMain.once('answer', (event, arg) => {
  2224. ipcMain.removeAllListeners('reloaded');
  2225. ipcMain.removeAllListeners('get-remote-module-path');
  2226. try {
  2227. expect(arg).to.equal('hi child window');
  2228. done();
  2229. } catch (e) {
  2230. done(e);
  2231. }
  2232. });
  2233. });
  2234. it('validates process APIs access in sandboxed renderer', async () => {
  2235. const w = new BrowserWindow({
  2236. show: false,
  2237. webPreferences: {
  2238. sandbox: true,
  2239. preload
  2240. }
  2241. });
  2242. w.webContents.once('preload-error', (event, preloadPath, error) => {
  2243. throw error;
  2244. });
  2245. process.env.sandboxmain = 'foo';
  2246. w.loadFile(path.join(fixtures, 'api', 'preload.html'));
  2247. const [, test] = await emittedOnce(ipcMain, 'answer');
  2248. expect(test.hasCrash).to.be.true('has crash');
  2249. expect(test.hasHang).to.be.true('has hang');
  2250. expect(test.heapStatistics).to.be.an('object');
  2251. expect(test.blinkMemoryInfo).to.be.an('object');
  2252. expect(test.processMemoryInfo).to.be.an('object');
  2253. expect(test.systemVersion).to.be.a('string');
  2254. expect(test.cpuUsage).to.be.an('object');
  2255. expect(test.ioCounters).to.be.an('object');
  2256. expect(test.arch).to.equal(process.arch);
  2257. expect(test.platform).to.equal(process.platform);
  2258. expect(test.env).to.deep.equal(process.env);
  2259. expect(test.execPath).to.equal(process.helperExecPath);
  2260. expect(test.sandboxed).to.be.true('sandboxed');
  2261. expect(test.type).to.equal('renderer');
  2262. expect(test.version).to.equal(process.version);
  2263. expect(test.versions).to.deep.equal(process.versions);
  2264. if (process.platform === 'linux' && test.osSandbox) {
  2265. expect(test.creationTime).to.be.null('creation time');
  2266. expect(test.systemMemoryInfo).to.be.null('system memory info');
  2267. } else {
  2268. expect(test.creationTime).to.be.a('number');
  2269. expect(test.systemMemoryInfo).to.be.an('object');
  2270. }
  2271. });
  2272. it('webview in sandbox renderer', async () => {
  2273. const w = new BrowserWindow({
  2274. show: false,
  2275. webPreferences: {
  2276. sandbox: true,
  2277. preload,
  2278. webviewTag: true
  2279. }
  2280. });
  2281. const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
  2282. const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready');
  2283. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  2284. const [, webContents] = await didAttachWebview;
  2285. const [, id] = await webviewDomReady;
  2286. expect(webContents.id).to.equal(id);
  2287. });
  2288. });
  2289. describe('nativeWindowOpen option', () => {
  2290. let w: BrowserWindow = null as unknown as BrowserWindow;
  2291. beforeEach(() => {
  2292. w = new BrowserWindow({
  2293. show: false,
  2294. webPreferences: {
  2295. nodeIntegration: true,
  2296. nativeWindowOpen: true,
  2297. // tests relies on preloads in opened windows
  2298. nodeIntegrationInSubFrames: true
  2299. }
  2300. });
  2301. });
  2302. it('opens window of about:blank with cross-scripting enabled', async () => {
  2303. const answer = emittedOnce(ipcMain, 'answer');
  2304. w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html'));
  2305. const [, content] = await answer;
  2306. expect(content).to.equal('Hello');
  2307. });
  2308. it('opens window of same domain with cross-scripting enabled', async () => {
  2309. const answer = emittedOnce(ipcMain, 'answer');
  2310. w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html'));
  2311. const [, content] = await answer;
  2312. expect(content).to.equal('Hello');
  2313. });
  2314. it('blocks accessing cross-origin frames', async () => {
  2315. const answer = emittedOnce(ipcMain, 'answer');
  2316. w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html'));
  2317. const [, content] = await answer;
  2318. expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.');
  2319. });
  2320. it('opens window from <iframe> tags', async () => {
  2321. const answer = emittedOnce(ipcMain, 'answer');
  2322. w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html'));
  2323. const [, content] = await answer;
  2324. expect(content).to.equal('Hello');
  2325. });
  2326. ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => {
  2327. w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html'));
  2328. {
  2329. const [, content] = await emittedOnce(ipcMain, 'answer');
  2330. expect(content).to.equal('function');
  2331. }
  2332. w.reload();
  2333. {
  2334. const [, content] = await emittedOnce(ipcMain, 'answer');
  2335. expect(content).to.equal('function');
  2336. }
  2337. });
  2338. it('<webview> works in a scriptable popup', async () => {
  2339. const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js');
  2340. const w = new BrowserWindow({
  2341. show: false,
  2342. webPreferences: {
  2343. nodeIntegrationInSubFrames: true,
  2344. nativeWindowOpen: true,
  2345. webviewTag: true,
  2346. preload
  2347. }
  2348. });
  2349. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2350. options.show = false;
  2351. });
  2352. const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded');
  2353. w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html'));
  2354. await webviewLoaded;
  2355. });
  2356. it('should inherit the nativeWindowOpen setting in opened windows', async () => {
  2357. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2358. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2359. options.webPreferences!.preload = preloadPath;
  2360. });
  2361. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2362. const [, args] = await emittedOnce(ipcMain, 'answer');
  2363. expect(args).to.include('--native-window-open');
  2364. });
  2365. it('should open windows with the options configured via new-window event listeners', async () => {
  2366. const preloadPath = path.join(fixtures, 'api', 'new-window-preload.js');
  2367. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2368. options.webPreferences!.preload = preloadPath;
  2369. const prefs = options.webPreferences! as any;
  2370. prefs.foo = 'bar';
  2371. });
  2372. w.loadFile(path.join(fixtures, 'api', 'new-window.html'));
  2373. const [[, childWebContents]] = await Promise.all([
  2374. emittedOnce(app, 'web-contents-created'),
  2375. emittedOnce(ipcMain, 'answer')
  2376. ]);
  2377. const webPreferences = (childWebContents as any).getLastWebPreferences();
  2378. expect(webPreferences.foo).to.equal('bar');
  2379. });
  2380. describe('window.location', () => {
  2381. const protocols = [
  2382. ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')],
  2383. ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')]
  2384. ];
  2385. beforeEach(() => {
  2386. for (const [scheme, path] of protocols) {
  2387. protocol.registerBufferProtocol(scheme, (request, callback) => {
  2388. callback({
  2389. mimeType: 'text/html',
  2390. data: fs.readFileSync(path)
  2391. });
  2392. });
  2393. }
  2394. });
  2395. afterEach(() => {
  2396. for (const [scheme] of protocols) {
  2397. protocol.unregisterProtocol(scheme);
  2398. }
  2399. });
  2400. it('retains the original web preferences when window.location is changed to a new origin', async () => {
  2401. const w = new BrowserWindow({
  2402. show: false,
  2403. webPreferences: {
  2404. nativeWindowOpen: true,
  2405. // test relies on preloads in opened window
  2406. nodeIntegrationInSubFrames: true
  2407. }
  2408. });
  2409. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2410. options.webPreferences!.preload = path.join(fixtures, 'api', 'window-open-preload.js');
  2411. });
  2412. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  2413. const [, args, typeofProcess] = await emittedOnce(ipcMain, 'answer');
  2414. expect(args).not.to.include('--node-integration');
  2415. expect(args).to.include('--native-window-open');
  2416. expect(typeofProcess).to.eql('undefined');
  2417. });
  2418. it('window.opener is not null when window.location is changed to a new origin', async () => {
  2419. const w = new BrowserWindow({
  2420. show: false,
  2421. webPreferences: {
  2422. nativeWindowOpen: true,
  2423. // test relies on preloads in opened window
  2424. nodeIntegrationInSubFrames: true
  2425. }
  2426. });
  2427. w.webContents.once('new-window', (event, url, frameName, disposition, options) => {
  2428. options.webPreferences!.preload = path.join(fixtures, 'api', 'window-open-preload.js');
  2429. });
  2430. w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html'));
  2431. const [, , , windowOpenerIsNull] = await emittedOnce(ipcMain, 'answer');
  2432. expect(windowOpenerIsNull).to.be.false('window.opener is null');
  2433. });
  2434. });
  2435. });
  2436. describe('"disableHtmlFullscreenWindowResize" option', () => {
  2437. it('prevents window from resizing when set', async () => {
  2438. const w = new BrowserWindow({
  2439. show: false,
  2440. webPreferences: {
  2441. disableHtmlFullscreenWindowResize: true
  2442. }
  2443. });
  2444. await w.loadURL('about:blank');
  2445. const size = w.getSize();
  2446. const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen');
  2447. w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  2448. await enterHtmlFullScreen;
  2449. expect(w.getSize()).to.deep.equal(size);
  2450. });
  2451. });
  2452. });
  2453. describe('nativeWindowOpen + contextIsolation options', () => {
  2454. afterEach(closeAllWindows);
  2455. it('opens window with cross-scripting enabled from isolated context', async () => {
  2456. const w = new BrowserWindow({
  2457. show: false,
  2458. webPreferences: {
  2459. nativeWindowOpen: true,
  2460. contextIsolation: true,
  2461. preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js')
  2462. }
  2463. });
  2464. w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html'));
  2465. const [, content] = await emittedOnce(ipcMain, 'answer');
  2466. expect(content).to.equal('Hello');
  2467. });
  2468. });
  2469. describe('beforeunload handler', function () {
  2470. let w: BrowserWindow = null as unknown as BrowserWindow;
  2471. beforeEach(() => {
  2472. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  2473. });
  2474. afterEach(closeAllWindows);
  2475. it('returning undefined would not prevent close', async () => {
  2476. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
  2477. const wait = emittedOnce(w, 'closed');
  2478. w.close();
  2479. await wait;
  2480. });
  2481. it('returning false would prevent close', async () => {
  2482. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
  2483. w.close();
  2484. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  2485. expect(proceed).to.equal(false);
  2486. });
  2487. it('returning empty string would prevent close', async () => {
  2488. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html'));
  2489. w.close();
  2490. const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired');
  2491. expect(proceed).to.equal(false);
  2492. });
  2493. it('emits for each close attempt', async () => {
  2494. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2495. const destroyListener = () => { expect.fail('Close was not prevented'); };
  2496. w.webContents.once('destroyed', destroyListener);
  2497. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2498. // The renderer needs to report the status of beforeunload handler
  2499. // back to main process, so wait for next console message, which means
  2500. // the SuddenTerminationStatus message have been flushed.
  2501. await emittedOnce(w.webContents, 'console-message');
  2502. w.close();
  2503. await emittedOnce(w.webContents, 'before-unload-fired');
  2504. w.close();
  2505. await emittedOnce(w.webContents, 'before-unload-fired');
  2506. w.webContents.removeListener('destroyed', destroyListener);
  2507. const wait = emittedOnce(w, 'closed');
  2508. w.close();
  2509. await wait;
  2510. });
  2511. it('emits for each reload attempt', async () => {
  2512. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2513. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  2514. w.webContents.once('did-start-navigation', navigationListener);
  2515. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2516. // The renderer needs to report the status of beforeunload handler
  2517. // back to main process, so wait for next console message, which means
  2518. // the SuddenTerminationStatus message have been flushed.
  2519. await emittedOnce(w.webContents, 'console-message');
  2520. w.reload();
  2521. // Chromium does not emit 'before-unload-fired' on WebContents for
  2522. // navigations, so we have to use other ways to know if beforeunload
  2523. // is fired.
  2524. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2525. w.reload();
  2526. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2527. w.webContents.removeListener('did-start-navigation', navigationListener);
  2528. w.reload();
  2529. await emittedOnce(w.webContents, 'did-finish-load');
  2530. });
  2531. it('emits for each navigation attempt', async () => {
  2532. await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html'));
  2533. const navigationListener = () => { expect.fail('Reload was not prevented'); };
  2534. w.webContents.once('did-start-navigation', navigationListener);
  2535. w.webContents.executeJavaScript('installBeforeUnload(2)', true);
  2536. // The renderer needs to report the status of beforeunload handler
  2537. // back to main process, so wait for next console message, which means
  2538. // the SuddenTerminationStatus message have been flushed.
  2539. await emittedOnce(w.webContents, 'console-message');
  2540. w.loadURL('about:blank');
  2541. // Chromium does not emit 'before-unload-fired' on WebContents for
  2542. // navigations, so we have to use other ways to know if beforeunload
  2543. // is fired.
  2544. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2545. w.loadURL('about:blank');
  2546. await emittedUntil(w.webContents, 'console-message', isBeforeUnload);
  2547. w.webContents.removeListener('did-start-navigation', navigationListener);
  2548. await w.loadURL('about:blank');
  2549. });
  2550. });
  2551. describe('document.visibilityState/hidden', () => {
  2552. afterEach(closeAllWindows);
  2553. it('visibilityState is initially visible despite window being hidden', async () => {
  2554. const w = new BrowserWindow({
  2555. show: false,
  2556. width: 100,
  2557. height: 100,
  2558. webPreferences: {
  2559. nodeIntegration: true
  2560. }
  2561. });
  2562. let readyToShow = false;
  2563. w.once('ready-to-show', () => {
  2564. readyToShow = true;
  2565. });
  2566. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2567. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2568. expect(readyToShow).to.be.false('ready to show');
  2569. expect(visibilityState).to.equal('visible');
  2570. expect(hidden).to.be.false('hidden');
  2571. });
  2572. // TODO(nornagon): figure out why this is failing on windows
  2573. ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => {
  2574. const w = new BrowserWindow({
  2575. width: 100,
  2576. height: 100,
  2577. webPreferences: {
  2578. nodeIntegration: true
  2579. }
  2580. });
  2581. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2582. {
  2583. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2584. expect(visibilityState).to.equal('visible');
  2585. expect(hidden).to.be.false('hidden');
  2586. }
  2587. w.hide();
  2588. {
  2589. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2590. expect(visibilityState).to.equal('hidden');
  2591. expect(hidden).to.be.true('hidden');
  2592. }
  2593. });
  2594. // TODO(nornagon): figure out why this is failing on windows
  2595. ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => {
  2596. const w = new BrowserWindow({
  2597. width: 100,
  2598. height: 100,
  2599. webPreferences: {
  2600. nodeIntegration: true
  2601. }
  2602. });
  2603. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2604. if (process.platform === 'darwin') {
  2605. // See https://github.com/electron/electron/issues/8664
  2606. await emittedOnce(w, 'show');
  2607. }
  2608. w.hide();
  2609. w.show();
  2610. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  2611. expect(visibilityState).to.equal('visible');
  2612. });
  2613. ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => {
  2614. const w = new BrowserWindow({
  2615. width: 100,
  2616. height: 100,
  2617. webPreferences: {
  2618. nodeIntegration: true
  2619. }
  2620. });
  2621. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2622. if (process.platform === 'darwin') {
  2623. // See https://github.com/electron/electron/issues/8664
  2624. await emittedOnce(w, 'show');
  2625. }
  2626. w.hide();
  2627. w.showInactive();
  2628. const [, visibilityState] = await emittedOnce(ipcMain, 'pong');
  2629. expect(visibilityState).to.equal('visible');
  2630. });
  2631. // TODO(nornagon): figure out why this is failing on windows
  2632. ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => {
  2633. const w = new BrowserWindow({
  2634. width: 100,
  2635. height: 100,
  2636. webPreferences: {
  2637. nodeIntegration: true
  2638. }
  2639. });
  2640. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2641. {
  2642. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2643. expect(visibilityState).to.equal('visible');
  2644. expect(hidden).to.be.false('hidden');
  2645. }
  2646. w.minimize();
  2647. {
  2648. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2649. expect(visibilityState).to.equal('hidden');
  2650. expect(hidden).to.be.true('hidden');
  2651. }
  2652. });
  2653. // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing
  2654. // when we introduced the compositor recycling patch. Should figure out how to fix this
  2655. it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => {
  2656. const w = new BrowserWindow({
  2657. show: false,
  2658. width: 100,
  2659. height: 100,
  2660. webPreferences: {
  2661. backgroundThrottling: false,
  2662. nodeIntegration: true
  2663. }
  2664. });
  2665. w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html'));
  2666. {
  2667. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  2668. expect(visibilityState).to.equal('visible');
  2669. expect(hidden).to.be.false('hidden');
  2670. }
  2671. ipcMain.once('pong', (event, visibilityState, hidden) => {
  2672. throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`);
  2673. });
  2674. try {
  2675. const shown1 = emittedOnce(w, 'show');
  2676. w.show();
  2677. await shown1;
  2678. const hidden = emittedOnce(w, 'hide');
  2679. w.hide();
  2680. await hidden;
  2681. const shown2 = emittedOnce(w, 'show');
  2682. w.show();
  2683. await shown2;
  2684. } finally {
  2685. ipcMain.removeAllListeners('pong');
  2686. }
  2687. });
  2688. });
  2689. describe('new-window event', () => {
  2690. afterEach(closeAllWindows);
  2691. it('emits when window.open is called', (done) => {
  2692. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  2693. w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures) => {
  2694. e.preventDefault();
  2695. try {
  2696. expect(url).to.equal('http://host/');
  2697. expect(frameName).to.equal('host');
  2698. expect(additionalFeatures[0]).to.equal('this-is-not-a-standard-feature');
  2699. done();
  2700. } catch (e) {
  2701. done(e);
  2702. }
  2703. });
  2704. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  2705. });
  2706. it('emits when window.open is called with no webPreferences', (done) => {
  2707. const w = new BrowserWindow({ show: false });
  2708. w.webContents.once('new-window', function (e, url, frameName, disposition, options, additionalFeatures) {
  2709. e.preventDefault();
  2710. try {
  2711. expect(url).to.equal('http://host/');
  2712. expect(frameName).to.equal('host');
  2713. expect(additionalFeatures[0]).to.equal('this-is-not-a-standard-feature');
  2714. done();
  2715. } catch (e) {
  2716. done(e);
  2717. }
  2718. });
  2719. w.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  2720. });
  2721. it('emits when link with target is called', (done) => {
  2722. const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
  2723. w.webContents.once('new-window', (e, url, frameName) => {
  2724. e.preventDefault();
  2725. try {
  2726. expect(url).to.equal('http://host/');
  2727. expect(frameName).to.equal('target');
  2728. done();
  2729. } catch (e) {
  2730. done(e);
  2731. }
  2732. });
  2733. w.loadFile(path.join(fixtures, 'pages', 'target-name.html'));
  2734. });
  2735. });
  2736. ifdescribe(process.platform !== 'linux')('max/minimize events', () => {
  2737. afterEach(closeAllWindows);
  2738. it('emits an event when window is maximized', (done) => {
  2739. const w = new BrowserWindow({ show: false });
  2740. w.once('maximize', () => { done(); });
  2741. w.show();
  2742. w.maximize();
  2743. });
  2744. it('emits only one event when frameless window is maximized', () => {
  2745. const w = new BrowserWindow({ show: false, frame: false });
  2746. let emitted = 0;
  2747. w.on('maximize', () => emitted++);
  2748. w.show();
  2749. w.maximize();
  2750. expect(emitted).to.equal(1);
  2751. });
  2752. it('emits an event when window is unmaximized', (done) => {
  2753. const w = new BrowserWindow({ show: false });
  2754. w.once('unmaximize', () => { done(); });
  2755. w.show();
  2756. w.maximize();
  2757. w.unmaximize();
  2758. });
  2759. it('emits an event when window is minimized', (done) => {
  2760. const w = new BrowserWindow({ show: false });
  2761. w.once('minimize', () => { done(); });
  2762. w.show();
  2763. w.minimize();
  2764. });
  2765. });
  2766. describe('beginFrameSubscription method', () => {
  2767. it('does not crash when callback returns nothing', (done) => {
  2768. const w = new BrowserWindow({ show: false });
  2769. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  2770. w.webContents.on('dom-ready', () => {
  2771. w.webContents.beginFrameSubscription(function () {
  2772. // Pending endFrameSubscription to next tick can reliably reproduce
  2773. // a crash which happens when nothing is returned in the callback.
  2774. setTimeout(() => {
  2775. w.webContents.endFrameSubscription();
  2776. done();
  2777. });
  2778. });
  2779. });
  2780. });
  2781. it('subscribes to frame updates', (done) => {
  2782. const w = new BrowserWindow({ show: false });
  2783. let called = false;
  2784. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  2785. w.webContents.on('dom-ready', () => {
  2786. w.webContents.beginFrameSubscription(function (data) {
  2787. // This callback might be called twice.
  2788. if (called) return;
  2789. called = true;
  2790. try {
  2791. expect(data.constructor.name).to.equal('NativeImage');
  2792. expect(data.isEmpty()).to.be.false('data is empty');
  2793. done();
  2794. } catch (e) {
  2795. done(e);
  2796. } finally {
  2797. w.webContents.endFrameSubscription();
  2798. }
  2799. });
  2800. });
  2801. });
  2802. it('subscribes to frame updates (only dirty rectangle)', (done) => {
  2803. const w = new BrowserWindow({ show: false });
  2804. let called = false;
  2805. let gotInitialFullSizeFrame = false;
  2806. const [contentWidth, contentHeight] = w.getContentSize();
  2807. w.webContents.on('did-finish-load', () => {
  2808. w.webContents.beginFrameSubscription(true, (image, rect) => {
  2809. if (image.isEmpty()) {
  2810. // Chromium sometimes sends a 0x0 frame at the beginning of the
  2811. // page load.
  2812. return;
  2813. }
  2814. if (rect.height === contentHeight && rect.width === contentWidth &&
  2815. !gotInitialFullSizeFrame) {
  2816. // The initial frame is full-size, but we're looking for a call
  2817. // with just the dirty-rect. The next frame should be a smaller
  2818. // rect.
  2819. gotInitialFullSizeFrame = true;
  2820. return;
  2821. }
  2822. // This callback might be called twice.
  2823. if (called) return;
  2824. // We asked for just the dirty rectangle, so we expect to receive a
  2825. // rect smaller than the full size.
  2826. // TODO(jeremy): this is failing on windows currently; investigate.
  2827. // assert(rect.width < contentWidth || rect.height < contentHeight)
  2828. called = true;
  2829. try {
  2830. const expectedSize = rect.width * rect.height * 4;
  2831. expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize);
  2832. done();
  2833. } catch (e) {
  2834. done(e);
  2835. } finally {
  2836. w.webContents.endFrameSubscription();
  2837. }
  2838. });
  2839. });
  2840. w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html'));
  2841. });
  2842. it('throws error when subscriber is not well defined', () => {
  2843. const w = new BrowserWindow({ show: false });
  2844. expect(() => {
  2845. w.webContents.beginFrameSubscription(true, true as any);
  2846. // TODO(zcbenz): gin is weak at guessing parameter types, we should
  2847. // upstream native_mate's implementation to gin.
  2848. }).to.throw('Error processing argument at index 1, conversion failure from ');
  2849. });
  2850. });
  2851. describe('savePage method', () => {
  2852. const savePageDir = path.join(fixtures, 'save_page');
  2853. const savePageHtmlPath = path.join(savePageDir, 'save_page.html');
  2854. const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js');
  2855. const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css');
  2856. after(() => {
  2857. try {
  2858. fs.unlinkSync(savePageCssPath);
  2859. fs.unlinkSync(savePageJsPath);
  2860. fs.unlinkSync(savePageHtmlPath);
  2861. fs.rmdirSync(path.join(savePageDir, 'save_page_files'));
  2862. fs.rmdirSync(savePageDir);
  2863. } catch (e) {
  2864. // Ignore error
  2865. }
  2866. });
  2867. afterEach(closeAllWindows);
  2868. it('should save page to disk', async () => {
  2869. const w = new BrowserWindow({ show: false });
  2870. await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html'));
  2871. await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete');
  2872. expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path');
  2873. expect(fs.existsSync(savePageJsPath)).to.be.true('js path');
  2874. expect(fs.existsSync(savePageCssPath)).to.be.true('css path');
  2875. });
  2876. });
  2877. describe('BrowserWindow options argument is optional', () => {
  2878. afterEach(closeAllWindows);
  2879. it('should create a window with default size (800x600)', () => {
  2880. const w = new BrowserWindow();
  2881. expect(w.getSize()).to.deep.equal([800, 600]);
  2882. });
  2883. });
  2884. describe('BrowserWindow.restore()', () => {
  2885. afterEach(closeAllWindows);
  2886. it('should restore the previous window size', () => {
  2887. const w = new BrowserWindow({
  2888. minWidth: 800,
  2889. width: 800
  2890. });
  2891. const initialSize = w.getSize();
  2892. w.minimize();
  2893. w.restore();
  2894. expectBoundsEqual(w.getSize(), initialSize);
  2895. });
  2896. it('does not crash when restoring hidden minimized window', () => {
  2897. const w = new BrowserWindow({});
  2898. w.minimize();
  2899. w.hide();
  2900. w.show();
  2901. });
  2902. });
  2903. describe('BrowserWindow.unmaximize()', () => {
  2904. afterEach(closeAllWindows);
  2905. it('should restore the previous window position', () => {
  2906. const w = new BrowserWindow();
  2907. const initialPosition = w.getPosition();
  2908. w.maximize();
  2909. w.unmaximize();
  2910. expectBoundsEqual(w.getPosition(), initialPosition);
  2911. });
  2912. });
  2913. describe('setFullScreen(false)', () => {
  2914. afterEach(closeAllWindows);
  2915. // only applicable to windows: https://github.com/electron/electron/issues/6036
  2916. ifdescribe(process.platform === 'win32')('on windows', () => {
  2917. it('should restore a normal visible window from a fullscreen startup state', async () => {
  2918. const w = new BrowserWindow({ show: false });
  2919. await w.loadURL('about:blank');
  2920. const shown = emittedOnce(w, 'show');
  2921. // start fullscreen and hidden
  2922. w.setFullScreen(true);
  2923. w.show();
  2924. await shown;
  2925. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  2926. w.setFullScreen(false);
  2927. await leftFullScreen;
  2928. expect(w.isVisible()).to.be.true('visible');
  2929. expect(w.isFullScreen()).to.be.false('fullscreen');
  2930. });
  2931. it('should keep window hidden if already in hidden state', async () => {
  2932. const w = new BrowserWindow({ show: false });
  2933. await w.loadURL('about:blank');
  2934. const leftFullScreen = emittedOnce(w, 'leave-full-screen');
  2935. w.setFullScreen(false);
  2936. await leftFullScreen;
  2937. expect(w.isVisible()).to.be.false('visible');
  2938. expect(w.isFullScreen()).to.be.false('fullscreen');
  2939. });
  2940. });
  2941. ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => {
  2942. it('exits HTML fullscreen when window leaves fullscreen', async () => {
  2943. const w = new BrowserWindow();
  2944. await w.loadURL('about:blank');
  2945. await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true);
  2946. await emittedOnce(w, 'enter-full-screen');
  2947. // Wait a tick for the full-screen state to 'stick'
  2948. await delay();
  2949. w.setFullScreen(false);
  2950. await emittedOnce(w, 'leave-html-full-screen');
  2951. });
  2952. });
  2953. });
  2954. describe('parent window', () => {
  2955. afterEach(closeAllWindows);
  2956. ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', (done) => {
  2957. const w = new BrowserWindow();
  2958. w.once('sheet-begin', () => {
  2959. done();
  2960. });
  2961. // eslint-disable-next-line no-new
  2962. new BrowserWindow({
  2963. modal: true,
  2964. parent: w
  2965. });
  2966. });
  2967. ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', (done) => {
  2968. const w = new BrowserWindow();
  2969. const sheet = new BrowserWindow({
  2970. modal: true,
  2971. parent: w
  2972. });
  2973. w.once('sheet-end', () => { done(); });
  2974. sheet.close();
  2975. });
  2976. describe('parent option', () => {
  2977. it('sets parent window', () => {
  2978. const w = new BrowserWindow({ show: false });
  2979. const c = new BrowserWindow({ show: false, parent: w });
  2980. expect(c.getParentWindow()).to.equal(w);
  2981. });
  2982. it('adds window to child windows of parent', () => {
  2983. const w = new BrowserWindow({ show: false });
  2984. const c = new BrowserWindow({ show: false, parent: w });
  2985. expect(w.getChildWindows()).to.deep.equal([c]);
  2986. });
  2987. it('removes from child windows of parent when window is closed', async () => {
  2988. const w = new BrowserWindow({ show: false });
  2989. const c = new BrowserWindow({ show: false, parent: w });
  2990. const closed = emittedOnce(c, 'closed');
  2991. c.close();
  2992. await closed;
  2993. // The child window list is not immediately cleared, so wait a tick until it's ready.
  2994. await delay();
  2995. expect(w.getChildWindows().length).to.equal(0);
  2996. });
  2997. it('should not affect the show option', () => {
  2998. const w = new BrowserWindow({ show: false });
  2999. const c = new BrowserWindow({ show: false, parent: w });
  3000. expect(c.isVisible()).to.be.false('child is visible');
  3001. expect(c.getParentWindow().isVisible()).to.be.false('parent is visible');
  3002. });
  3003. });
  3004. describe('win.setParentWindow(parent)', () => {
  3005. it('sets parent window', () => {
  3006. const w = new BrowserWindow({ show: false });
  3007. const c = new BrowserWindow({ show: false });
  3008. expect(w.getParentWindow()).to.be.null('w.parent');
  3009. expect(c.getParentWindow()).to.be.null('c.parent');
  3010. c.setParentWindow(w);
  3011. expect(c.getParentWindow()).to.equal(w);
  3012. c.setParentWindow(null);
  3013. expect(c.getParentWindow()).to.be.null('c.parent');
  3014. });
  3015. it('adds window to child windows of parent', () => {
  3016. const w = new BrowserWindow({ show: false });
  3017. const c = new BrowserWindow({ show: false });
  3018. expect(w.getChildWindows()).to.deep.equal([]);
  3019. c.setParentWindow(w);
  3020. expect(w.getChildWindows()).to.deep.equal([c]);
  3021. c.setParentWindow(null);
  3022. expect(w.getChildWindows()).to.deep.equal([]);
  3023. });
  3024. it('removes from child windows of parent when window is closed', async () => {
  3025. const w = new BrowserWindow({ show: false });
  3026. const c = new BrowserWindow({ show: false });
  3027. const closed = emittedOnce(c, 'closed');
  3028. c.setParentWindow(w);
  3029. c.close();
  3030. await closed;
  3031. // The child window list is not immediately cleared, so wait a tick until it's ready.
  3032. await delay();
  3033. expect(w.getChildWindows().length).to.equal(0);
  3034. });
  3035. });
  3036. describe('modal option', () => {
  3037. it('does not freeze or crash', async () => {
  3038. const parentWindow = new BrowserWindow();
  3039. const createTwo = async () => {
  3040. const two = new BrowserWindow({
  3041. width: 300,
  3042. height: 200,
  3043. parent: parentWindow,
  3044. modal: true,
  3045. show: false
  3046. });
  3047. const twoShown = emittedOnce(two, 'show');
  3048. two.show();
  3049. await twoShown;
  3050. setTimeout(() => two.close(), 500);
  3051. await emittedOnce(two, 'closed');
  3052. };
  3053. const one = new BrowserWindow({
  3054. width: 600,
  3055. height: 400,
  3056. parent: parentWindow,
  3057. modal: true,
  3058. show: false
  3059. });
  3060. const oneShown = emittedOnce(one, 'show');
  3061. one.show();
  3062. await oneShown;
  3063. setTimeout(() => one.destroy(), 500);
  3064. await emittedOnce(one, 'closed');
  3065. await createTwo();
  3066. });
  3067. ifit(process.platform !== 'darwin')('disables parent window', () => {
  3068. const w = new BrowserWindow({ show: false });
  3069. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3070. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3071. c.show();
  3072. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3073. });
  3074. ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => {
  3075. const w = new BrowserWindow({ show: false });
  3076. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3077. const closed = emittedOnce(c, 'closed');
  3078. c.show();
  3079. c.close();
  3080. await closed;
  3081. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3082. });
  3083. ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => {
  3084. const w = new BrowserWindow({ show: false });
  3085. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3086. const closed = emittedOnce(c, 'closed');
  3087. w.setEnabled(false);
  3088. c.show();
  3089. c.close();
  3090. await closed;
  3091. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3092. });
  3093. ifit(process.platform !== 'darwin')('disables parent window recursively', () => {
  3094. const w = new BrowserWindow({ show: false });
  3095. const c = new BrowserWindow({ show: false, parent: w, modal: true });
  3096. const c2 = new BrowserWindow({ show: false, parent: w, modal: true });
  3097. c.show();
  3098. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3099. c2.show();
  3100. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3101. c.destroy();
  3102. expect(w.isEnabled()).to.be.false('w.isEnabled');
  3103. c2.destroy();
  3104. expect(w.isEnabled()).to.be.true('w.isEnabled');
  3105. });
  3106. });
  3107. });
  3108. describe('window states', () => {
  3109. afterEach(closeAllWindows);
  3110. it('does not resize frameless windows when states change', () => {
  3111. const w = new BrowserWindow({
  3112. frame: false,
  3113. width: 300,
  3114. height: 200,
  3115. show: false
  3116. });
  3117. w.minimizable = false;
  3118. w.minimizable = true;
  3119. expect(w.getSize()).to.deep.equal([300, 200]);
  3120. w.resizable = false;
  3121. w.resizable = true;
  3122. expect(w.getSize()).to.deep.equal([300, 200]);
  3123. w.maximizable = false;
  3124. w.maximizable = true;
  3125. expect(w.getSize()).to.deep.equal([300, 200]);
  3126. w.fullScreenable = false;
  3127. w.fullScreenable = true;
  3128. expect(w.getSize()).to.deep.equal([300, 200]);
  3129. w.closable = false;
  3130. w.closable = true;
  3131. expect(w.getSize()).to.deep.equal([300, 200]);
  3132. });
  3133. describe('resizable state', () => {
  3134. it('with properties', () => {
  3135. it('can be set with resizable constructor option', () => {
  3136. const w = new BrowserWindow({ show: false, resizable: false });
  3137. expect(w.resizable).to.be.false('resizable');
  3138. if (process.platform === 'darwin') {
  3139. expect(w.maximizable).to.to.true('maximizable');
  3140. }
  3141. });
  3142. it('can be changed', () => {
  3143. const w = new BrowserWindow({ show: false });
  3144. expect(w.resizable).to.be.true('resizable');
  3145. w.resizable = false;
  3146. expect(w.resizable).to.be.false('resizable');
  3147. w.resizable = true;
  3148. expect(w.resizable).to.be.true('resizable');
  3149. });
  3150. });
  3151. it('with functions', () => {
  3152. it('can be set with resizable constructor option', () => {
  3153. const w = new BrowserWindow({ show: false, resizable: false });
  3154. expect(w.isResizable()).to.be.false('resizable');
  3155. if (process.platform === 'darwin') {
  3156. expect(w.isMaximizable()).to.to.true('maximizable');
  3157. }
  3158. });
  3159. it('can be changed', () => {
  3160. const w = new BrowserWindow({ show: false });
  3161. expect(w.isResizable()).to.be.true('resizable');
  3162. w.setResizable(false);
  3163. expect(w.isResizable()).to.be.false('resizable');
  3164. w.setResizable(true);
  3165. expect(w.isResizable()).to.be.true('resizable');
  3166. });
  3167. });
  3168. it('works for a frameless window', () => {
  3169. const w = new BrowserWindow({ show: false, frame: false });
  3170. expect(w.resizable).to.be.true('resizable');
  3171. if (process.platform === 'win32') {
  3172. const w = new BrowserWindow({ show: false, thickFrame: false });
  3173. expect(w.resizable).to.be.false('resizable');
  3174. }
  3175. });
  3176. ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => {
  3177. const w = new BrowserWindow({
  3178. show: false,
  3179. frame: false,
  3180. resizable: false,
  3181. transparent: true
  3182. });
  3183. w.setContentSize(60, 60);
  3184. expectBoundsEqual(w.getContentSize(), [60, 60]);
  3185. w.setContentSize(30, 30);
  3186. expectBoundsEqual(w.getContentSize(), [30, 30]);
  3187. w.setContentSize(10, 10);
  3188. expectBoundsEqual(w.getContentSize(), [10, 10]);
  3189. });
  3190. });
  3191. describe('loading main frame state', () => {
  3192. let server: http.Server = null as unknown as http.Server;
  3193. let serverUrl: string = null as unknown as string;
  3194. before((done) => {
  3195. server = http.createServer((request, response) => {
  3196. response.end();
  3197. }).listen(0, '127.0.0.1', () => {
  3198. serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port;
  3199. done();
  3200. });
  3201. });
  3202. after(() => {
  3203. server.close();
  3204. });
  3205. it('is true when the main frame is loading', async () => {
  3206. const w = new BrowserWindow({ show: false });
  3207. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3208. w.webContents.loadURL(serverUrl);
  3209. await didStartLoading;
  3210. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3211. });
  3212. it('is false when only a subframe is loading', async () => {
  3213. const w = new BrowserWindow({ show: false });
  3214. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3215. w.webContents.loadURL(serverUrl);
  3216. await didStopLoading;
  3217. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3218. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3219. w.webContents.executeJavaScript(`
  3220. var iframe = document.createElement('iframe')
  3221. iframe.src = '${serverUrl}/page2'
  3222. document.body.appendChild(iframe)
  3223. `);
  3224. await didStartLoading;
  3225. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3226. });
  3227. it('is true when navigating to pages from the same origin', async () => {
  3228. const w = new BrowserWindow({ show: false });
  3229. const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading');
  3230. w.webContents.loadURL(serverUrl);
  3231. await didStopLoading;
  3232. expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame');
  3233. const didStartLoading = emittedOnce(w.webContents, 'did-start-loading');
  3234. w.webContents.loadURL(`${serverUrl}/page2`);
  3235. await didStartLoading;
  3236. expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame');
  3237. });
  3238. });
  3239. });
  3240. ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => {
  3241. // Not implemented on Linux.
  3242. afterEach(closeAllWindows);
  3243. describe('movable state', () => {
  3244. it('with properties', () => {
  3245. it('can be set with movable constructor option', () => {
  3246. const w = new BrowserWindow({ show: false, movable: false });
  3247. expect(w.movable).to.be.false('movable');
  3248. });
  3249. it('can be changed', () => {
  3250. const w = new BrowserWindow({ show: false });
  3251. expect(w.movable).to.be.true('movable');
  3252. w.movable = false;
  3253. expect(w.movable).to.be.false('movable');
  3254. w.movable = true;
  3255. expect(w.movable).to.be.true('movable');
  3256. });
  3257. });
  3258. it('with functions', () => {
  3259. it('can be set with movable constructor option', () => {
  3260. const w = new BrowserWindow({ show: false, movable: false });
  3261. expect(w.isMovable()).to.be.false('movable');
  3262. });
  3263. it('can be changed', () => {
  3264. const w = new BrowserWindow({ show: false });
  3265. expect(w.isMovable()).to.be.true('movable');
  3266. w.setMovable(false);
  3267. expect(w.isMovable()).to.be.false('movable');
  3268. w.setMovable(true);
  3269. expect(w.isMovable()).to.be.true('movable');
  3270. });
  3271. });
  3272. });
  3273. describe('visibleOnAllWorkspaces state', () => {
  3274. it('with properties', () => {
  3275. it('can be changed', () => {
  3276. const w = new BrowserWindow({ show: false });
  3277. expect(w.visibleOnAllWorkspaces).to.be.false();
  3278. w.visibleOnAllWorkspaces = true;
  3279. expect(w.visibleOnAllWorkspaces).to.be.true();
  3280. });
  3281. });
  3282. it('with functions', () => {
  3283. it('can be changed', () => {
  3284. const w = new BrowserWindow({ show: false });
  3285. expect(w.isVisibleOnAllWorkspaces()).to.be.false();
  3286. w.setVisibleOnAllWorkspaces(true);
  3287. expect(w.isVisibleOnAllWorkspaces()).to.be.true();
  3288. });
  3289. });
  3290. });
  3291. ifdescribe(process.platform === 'darwin')('documentEdited state', () => {
  3292. it('with properties', () => {
  3293. it('can be changed', () => {
  3294. const w = new BrowserWindow({ show: false });
  3295. expect(w.documentEdited).to.be.false();
  3296. w.documentEdited = true;
  3297. expect(w.documentEdited).to.be.true();
  3298. });
  3299. });
  3300. it('with functions', () => {
  3301. it('can be changed', () => {
  3302. const w = new BrowserWindow({ show: false });
  3303. expect(w.isDocumentEdited()).to.be.false();
  3304. w.setDocumentEdited(true);
  3305. expect(w.isDocumentEdited()).to.be.true();
  3306. });
  3307. });
  3308. });
  3309. ifdescribe(process.platform === 'darwin')('representedFilename', () => {
  3310. it('with properties', () => {
  3311. it('can be changed', () => {
  3312. const w = new BrowserWindow({ show: false });
  3313. expect(w.representedFilename).to.eql('');
  3314. w.representedFilename = 'a name';
  3315. expect(w.representedFilename).to.eql('a name');
  3316. });
  3317. });
  3318. it('with functions', () => {
  3319. it('can be changed', () => {
  3320. const w = new BrowserWindow({ show: false });
  3321. expect(w.getRepresentedFilename()).to.eql('');
  3322. w.setRepresentedFilename('a name');
  3323. expect(w.getRepresentedFilename()).to.eql('a name');
  3324. });
  3325. });
  3326. });
  3327. describe('native window title', () => {
  3328. it('with properties', () => {
  3329. it('can be set with title constructor option', () => {
  3330. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  3331. expect(w.title).to.eql('mYtItLe');
  3332. });
  3333. it('can be changed', () => {
  3334. const w = new BrowserWindow({ show: false });
  3335. expect(w.title).to.eql('Electron Test Main');
  3336. w.title = 'NEW TITLE';
  3337. expect(w.title).to.eql('NEW TITLE');
  3338. });
  3339. });
  3340. it('with functions', () => {
  3341. it('can be set with minimizable constructor option', () => {
  3342. const w = new BrowserWindow({ show: false, title: 'mYtItLe' });
  3343. expect(w.getTitle()).to.eql('mYtItLe');
  3344. });
  3345. it('can be changed', () => {
  3346. const w = new BrowserWindow({ show: false });
  3347. expect(w.getTitle()).to.eql('Electron Test Main');
  3348. w.setTitle('NEW TITLE');
  3349. expect(w.getTitle()).to.eql('NEW TITLE');
  3350. });
  3351. });
  3352. });
  3353. describe('minimizable state', () => {
  3354. it('with properties', () => {
  3355. it('can be set with minimizable constructor option', () => {
  3356. const w = new BrowserWindow({ show: false, minimizable: false });
  3357. expect(w.minimizable).to.be.false('minimizable');
  3358. });
  3359. it('can be changed', () => {
  3360. const w = new BrowserWindow({ show: false });
  3361. expect(w.minimizable).to.be.true('minimizable');
  3362. w.minimizable = false;
  3363. expect(w.minimizable).to.be.false('minimizable');
  3364. w.minimizable = true;
  3365. expect(w.minimizable).to.be.true('minimizable');
  3366. });
  3367. });
  3368. it('with functions', () => {
  3369. it('can be set with minimizable constructor option', () => {
  3370. const w = new BrowserWindow({ show: false, minimizable: false });
  3371. expect(w.isMinimizable()).to.be.false('movable');
  3372. });
  3373. it('can be changed', () => {
  3374. const w = new BrowserWindow({ show: false });
  3375. expect(w.isMinimizable()).to.be.true('isMinimizable');
  3376. w.setMinimizable(false);
  3377. expect(w.isMinimizable()).to.be.false('isMinimizable');
  3378. w.setMinimizable(true);
  3379. expect(w.isMinimizable()).to.be.true('isMinimizable');
  3380. });
  3381. });
  3382. });
  3383. describe('maximizable state (property)', () => {
  3384. it('with properties', () => {
  3385. it('can be set with maximizable constructor option', () => {
  3386. const w = new BrowserWindow({ show: false, maximizable: false });
  3387. expect(w.maximizable).to.be.false('maximizable');
  3388. });
  3389. it('can be changed', () => {
  3390. const w = new BrowserWindow({ show: false });
  3391. expect(w.maximizable).to.be.true('maximizable');
  3392. w.maximizable = false;
  3393. expect(w.maximizable).to.be.false('maximizable');
  3394. w.maximizable = true;
  3395. expect(w.maximizable).to.be.true('maximizable');
  3396. });
  3397. it('is not affected when changing other states', () => {
  3398. const w = new BrowserWindow({ show: false });
  3399. w.maximizable = false;
  3400. expect(w.maximizable).to.be.false('maximizable');
  3401. w.minimizable = false;
  3402. expect(w.maximizable).to.be.false('maximizable');
  3403. w.closable = false;
  3404. expect(w.maximizable).to.be.false('maximizable');
  3405. w.maximizable = true;
  3406. expect(w.maximizable).to.be.true('maximizable');
  3407. w.closable = true;
  3408. expect(w.maximizable).to.be.true('maximizable');
  3409. w.fullScreenable = false;
  3410. expect(w.maximizable).to.be.true('maximizable');
  3411. });
  3412. });
  3413. it('with functions', () => {
  3414. it('can be set with maximizable constructor option', () => {
  3415. const w = new BrowserWindow({ show: false, maximizable: false });
  3416. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3417. });
  3418. it('can be changed', () => {
  3419. const w = new BrowserWindow({ show: false });
  3420. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3421. w.setMaximizable(false);
  3422. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3423. w.setMaximizable(true);
  3424. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3425. });
  3426. it('is not affected when changing other states', () => {
  3427. const w = new BrowserWindow({ show: false });
  3428. w.setMaximizable(false);
  3429. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3430. w.setMinimizable(false);
  3431. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3432. w.setClosable(false);
  3433. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3434. w.setMaximizable(true);
  3435. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3436. w.setClosable(true);
  3437. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3438. w.setFullScreenable(false);
  3439. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3440. });
  3441. });
  3442. });
  3443. ifdescribe(process.platform === 'win32')('maximizable state', () => {
  3444. it('with properties', () => {
  3445. it('is reset to its former state', () => {
  3446. const w = new BrowserWindow({ show: false });
  3447. w.maximizable = false;
  3448. w.resizable = false;
  3449. w.resizable = true;
  3450. expect(w.maximizable).to.be.false('maximizable');
  3451. w.maximizable = true;
  3452. w.resizable = false;
  3453. w.resizable = true;
  3454. expect(w.maximizable).to.be.true('maximizable');
  3455. });
  3456. });
  3457. it('with functions', () => {
  3458. it('is reset to its former state', () => {
  3459. const w = new BrowserWindow({ show: false });
  3460. w.setMaximizable(false);
  3461. w.setResizable(false);
  3462. w.setResizable(true);
  3463. expect(w.isMaximizable()).to.be.false('isMaximizable');
  3464. w.setMaximizable(true);
  3465. w.setResizable(false);
  3466. w.setResizable(true);
  3467. expect(w.isMaximizable()).to.be.true('isMaximizable');
  3468. });
  3469. });
  3470. });
  3471. ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => {
  3472. describe('with properties', () => {
  3473. it('can be changed', () => {
  3474. const w = new BrowserWindow({ show: false });
  3475. expect(w.menuBarVisible).to.be.true();
  3476. w.menuBarVisible = false;
  3477. expect(w.menuBarVisible).to.be.false();
  3478. w.menuBarVisible = true;
  3479. expect(w.menuBarVisible).to.be.true();
  3480. });
  3481. });
  3482. describe('with functions', () => {
  3483. it('can be changed', () => {
  3484. const w = new BrowserWindow({ show: false });
  3485. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  3486. w.setMenuBarVisibility(false);
  3487. expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible');
  3488. w.setMenuBarVisibility(true);
  3489. expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible');
  3490. });
  3491. });
  3492. });
  3493. ifdescribe(process.platform === 'darwin')('fullscreenable state', () => {
  3494. it('with functions', () => {
  3495. it('can be set with fullscreenable constructor option', () => {
  3496. const w = new BrowserWindow({ show: false, fullscreenable: false });
  3497. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  3498. });
  3499. it('can be changed', () => {
  3500. const w = new BrowserWindow({ show: false });
  3501. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  3502. w.setFullScreenable(false);
  3503. expect(w.isFullScreenable()).to.be.false('isFullScreenable');
  3504. w.setFullScreenable(true);
  3505. expect(w.isFullScreenable()).to.be.true('isFullScreenable');
  3506. });
  3507. });
  3508. });
  3509. // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron
  3510. ifdescribe(process.platform === 'darwin')('kiosk state', () => {
  3511. it('with properties', () => {
  3512. it('can be set with a constructor property', () => {
  3513. const w = new BrowserWindow({ kiosk: true });
  3514. expect(w.kiosk).to.be.true();
  3515. });
  3516. it('can be changed ', async () => {
  3517. const w = new BrowserWindow();
  3518. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3519. w.kiosk = true;
  3520. expect(w.isKiosk()).to.be.true('isKiosk');
  3521. await enterFullScreen;
  3522. await delay();
  3523. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3524. w.kiosk = false;
  3525. expect(w.isKiosk()).to.be.false('isKiosk');
  3526. await leaveFullScreen;
  3527. });
  3528. });
  3529. it('with functions', () => {
  3530. it('can be set with a constructor property', () => {
  3531. const w = new BrowserWindow({ kiosk: true });
  3532. expect(w.isKiosk()).to.be.true();
  3533. });
  3534. it('can be changed ', async () => {
  3535. const w = new BrowserWindow();
  3536. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3537. w.setKiosk(true);
  3538. expect(w.isKiosk()).to.be.true('isKiosk');
  3539. await enterFullScreen;
  3540. await delay();
  3541. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3542. w.setKiosk(false);
  3543. expect(w.isKiosk()).to.be.false('isKiosk');
  3544. await leaveFullScreen;
  3545. });
  3546. });
  3547. });
  3548. ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => {
  3549. it('resizable flag should be set to true and restored', async () => {
  3550. const w = new BrowserWindow({ resizable: false });
  3551. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3552. w.setFullScreen(true);
  3553. await enterFullScreen;
  3554. expect(w.resizable).to.be.true('resizable');
  3555. await delay();
  3556. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3557. w.setFullScreen(false);
  3558. await leaveFullScreen;
  3559. expect(w.resizable).to.be.false('resizable');
  3560. });
  3561. });
  3562. ifdescribe(process.platform === 'darwin')('fullscreen state', () => {
  3563. it('should not cause a crash if called when exiting fullscreen', async () => {
  3564. const w = new BrowserWindow();
  3565. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3566. w.setFullScreen(true);
  3567. await enterFullScreen;
  3568. await delay();
  3569. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3570. w.setFullScreen(false);
  3571. await leaveFullScreen;
  3572. w.close();
  3573. });
  3574. it('can be changed with setFullScreen method', async () => {
  3575. const w = new BrowserWindow();
  3576. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3577. w.setFullScreen(true);
  3578. await enterFullScreen;
  3579. expect(w.isFullScreen()).to.be.true('isFullScreen');
  3580. await delay();
  3581. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3582. w.setFullScreen(false);
  3583. await leaveFullScreen;
  3584. expect(w.isFullScreen()).to.be.false('isFullScreen');
  3585. });
  3586. it('does not crash when exiting simpleFullScreen (properties)', (done) => {
  3587. const w = new BrowserWindow();
  3588. w.setSimpleFullScreen(true);
  3589. setTimeout(() => {
  3590. w.setFullScreen(!w.isFullScreen());
  3591. done();
  3592. }, 1000);
  3593. });
  3594. it('does not crash when exiting simpleFullScreen (functions)', (done) => {
  3595. const w = new BrowserWindow();
  3596. w.simpleFullScreen = true;
  3597. setTimeout(() => {
  3598. w.setFullScreen(!w.isFullScreen());
  3599. done();
  3600. }, 1000);
  3601. });
  3602. it('should not be changed by setKiosk method', async () => {
  3603. const w = new BrowserWindow();
  3604. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  3605. w.setFullScreen(true);
  3606. await enterFullScreen;
  3607. expect(w.isFullScreen()).to.be.true('isFullScreen');
  3608. await delay();
  3609. w.setKiosk(true);
  3610. await delay();
  3611. w.setKiosk(false);
  3612. expect(w.isFullScreen()).to.be.true('isFullScreen');
  3613. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  3614. w.setFullScreen(false);
  3615. await leaveFullScreen;
  3616. expect(w.isFullScreen()).to.be.false('isFullScreen');
  3617. });
  3618. });
  3619. describe('closable state', () => {
  3620. it('with properties', () => {
  3621. it('can be set with closable constructor option', () => {
  3622. const w = new BrowserWindow({ show: false, closable: false });
  3623. expect(w.closable).to.be.false('closable');
  3624. });
  3625. it('can be changed', () => {
  3626. const w = new BrowserWindow({ show: false });
  3627. expect(w.closable).to.be.true('closable');
  3628. w.closable = false;
  3629. expect(w.closable).to.be.false('closable');
  3630. w.closable = true;
  3631. expect(w.closable).to.be.true('closable');
  3632. });
  3633. });
  3634. it('with functions', () => {
  3635. it('can be set with closable constructor option', () => {
  3636. const w = new BrowserWindow({ show: false, closable: false });
  3637. expect(w.isClosable()).to.be.false('isClosable');
  3638. });
  3639. it('can be changed', () => {
  3640. const w = new BrowserWindow({ show: false });
  3641. expect(w.isClosable()).to.be.true('isClosable');
  3642. w.setClosable(false);
  3643. expect(w.isClosable()).to.be.false('isClosable');
  3644. w.setClosable(true);
  3645. expect(w.isClosable()).to.be.true('isClosable');
  3646. });
  3647. });
  3648. });
  3649. describe('hasShadow state', () => {
  3650. it('with properties', () => {
  3651. it('returns a boolean on all platforms', () => {
  3652. const w = new BrowserWindow({ show: false });
  3653. expect(w.shadow).to.be.a('boolean');
  3654. });
  3655. // On Windows there's no shadow by default & it can't be changed dynamically.
  3656. it('can be changed with hasShadow option', () => {
  3657. const hasShadow = process.platform !== 'darwin';
  3658. const w = new BrowserWindow({ show: false, hasShadow });
  3659. expect(w.shadow).to.equal(hasShadow);
  3660. });
  3661. it('can be changed with setHasShadow method', () => {
  3662. const w = new BrowserWindow({ show: false });
  3663. w.shadow = false;
  3664. expect(w.shadow).to.be.false('hasShadow');
  3665. w.shadow = true;
  3666. expect(w.shadow).to.be.true('hasShadow');
  3667. w.shadow = false;
  3668. expect(w.shadow).to.be.false('hasShadow');
  3669. });
  3670. });
  3671. describe('with functions', () => {
  3672. it('returns a boolean on all platforms', () => {
  3673. const w = new BrowserWindow({ show: false });
  3674. const hasShadow = w.hasShadow();
  3675. expect(hasShadow).to.be.a('boolean');
  3676. });
  3677. // On Windows there's no shadow by default & it can't be changed dynamically.
  3678. it('can be changed with hasShadow option', () => {
  3679. const hasShadow = process.platform !== 'darwin';
  3680. const w = new BrowserWindow({ show: false, hasShadow });
  3681. expect(w.hasShadow()).to.equal(hasShadow);
  3682. });
  3683. it('can be changed with setHasShadow method', () => {
  3684. const w = new BrowserWindow({ show: false });
  3685. w.setHasShadow(false);
  3686. expect(w.hasShadow()).to.be.false('hasShadow');
  3687. w.setHasShadow(true);
  3688. expect(w.hasShadow()).to.be.true('hasShadow');
  3689. w.setHasShadow(false);
  3690. expect(w.hasShadow()).to.be.false('hasShadow');
  3691. });
  3692. });
  3693. });
  3694. });
  3695. describe('window.getMediaSourceId()', () => {
  3696. afterEach(closeAllWindows);
  3697. it('returns valid source id', async () => {
  3698. const w = new BrowserWindow({ show: false });
  3699. const shown = emittedOnce(w, 'show');
  3700. w.show();
  3701. await shown;
  3702. // Check format 'window:1234:0'.
  3703. const sourceId = w.getMediaSourceId();
  3704. expect(sourceId).to.match(/^window:\d+:\d+$/);
  3705. });
  3706. });
  3707. ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => {
  3708. afterEach(closeAllWindows);
  3709. it('returns valid handle', () => {
  3710. const w = new BrowserWindow({ show: false });
  3711. // The module's source code is hosted at
  3712. // https://github.com/electron/node-is-valid-window
  3713. const isValidWindow = require('is-valid-window');
  3714. expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window');
  3715. });
  3716. });
  3717. ifdescribe(process.platform === 'darwin')('previewFile', () => {
  3718. afterEach(closeAllWindows);
  3719. it('opens the path in Quick Look on macOS', () => {
  3720. const w = new BrowserWindow({ show: false });
  3721. expect(() => {
  3722. w.previewFile(__filename);
  3723. w.closeFilePreview();
  3724. }).to.not.throw();
  3725. });
  3726. });
  3727. describe('contextIsolation option with and without sandbox option', () => {
  3728. const expectedContextData = {
  3729. preloadContext: {
  3730. preloadProperty: 'number',
  3731. pageProperty: 'undefined',
  3732. typeofRequire: 'function',
  3733. typeofProcess: 'object',
  3734. typeofArrayPush: 'function',
  3735. typeofFunctionApply: 'function',
  3736. typeofPreloadExecuteJavaScriptProperty: 'undefined'
  3737. },
  3738. pageContext: {
  3739. preloadProperty: 'undefined',
  3740. pageProperty: 'string',
  3741. typeofRequire: 'undefined',
  3742. typeofProcess: 'undefined',
  3743. typeofArrayPush: 'number',
  3744. typeofFunctionApply: 'boolean',
  3745. typeofPreloadExecuteJavaScriptProperty: 'number',
  3746. typeofOpenedWindow: 'object'
  3747. }
  3748. };
  3749. afterEach(closeAllWindows);
  3750. it('separates the page context from the Electron/preload context', async () => {
  3751. const iw = new BrowserWindow({
  3752. show: false,
  3753. webPreferences: {
  3754. contextIsolation: true,
  3755. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3756. }
  3757. });
  3758. const p = emittedOnce(ipcMain, 'isolated-world');
  3759. iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3760. const [, data] = await p;
  3761. expect(data).to.deep.equal(expectedContextData);
  3762. });
  3763. it('recreates the contexts on reload', async () => {
  3764. const iw = new BrowserWindow({
  3765. show: false,
  3766. webPreferences: {
  3767. contextIsolation: true,
  3768. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3769. }
  3770. });
  3771. await iw.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3772. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  3773. iw.webContents.reload();
  3774. const [, data] = await isolatedWorld;
  3775. expect(data).to.deep.equal(expectedContextData);
  3776. });
  3777. it('enables context isolation on child windows', async () => {
  3778. const iw = new BrowserWindow({
  3779. show: false,
  3780. webPreferences: {
  3781. contextIsolation: true,
  3782. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3783. }
  3784. });
  3785. const browserWindowCreated = emittedOnce(app, 'browser-window-created');
  3786. iw.loadFile(path.join(fixtures, 'pages', 'window-open.html'));
  3787. const [, window] = await browserWindowCreated;
  3788. expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation');
  3789. });
  3790. it('separates the page context from the Electron/preload context with sandbox on', async () => {
  3791. const ws = new BrowserWindow({
  3792. show: false,
  3793. webPreferences: {
  3794. sandbox: true,
  3795. contextIsolation: true,
  3796. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3797. }
  3798. });
  3799. const p = emittedOnce(ipcMain, 'isolated-world');
  3800. ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3801. const [, data] = await p;
  3802. expect(data).to.deep.equal(expectedContextData);
  3803. });
  3804. it('recreates the contexts on reload with sandbox on', async () => {
  3805. const ws = new BrowserWindow({
  3806. show: false,
  3807. webPreferences: {
  3808. sandbox: true,
  3809. contextIsolation: true,
  3810. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3811. }
  3812. });
  3813. await ws.loadFile(path.join(fixtures, 'api', 'isolated.html'));
  3814. const isolatedWorld = emittedOnce(ipcMain, 'isolated-world');
  3815. ws.webContents.reload();
  3816. const [, data] = await isolatedWorld;
  3817. expect(data).to.deep.equal(expectedContextData);
  3818. });
  3819. it('supports fetch api', async () => {
  3820. const fetchWindow = new BrowserWindow({
  3821. show: false,
  3822. webPreferences: {
  3823. contextIsolation: true,
  3824. preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js')
  3825. }
  3826. });
  3827. const p = emittedOnce(ipcMain, 'isolated-fetch-error');
  3828. fetchWindow.loadURL('about:blank');
  3829. const [, error] = await p;
  3830. expect(error).to.equal('Failed to fetch');
  3831. });
  3832. it('doesn\'t break ipc serialization', async () => {
  3833. const iw = new BrowserWindow({
  3834. show: false,
  3835. webPreferences: {
  3836. contextIsolation: true,
  3837. preload: path.join(fixtures, 'api', 'isolated-preload.js')
  3838. }
  3839. });
  3840. const p = emittedOnce(ipcMain, 'isolated-world');
  3841. iw.loadURL('about:blank');
  3842. iw.webContents.executeJavaScript(`
  3843. const opened = window.open()
  3844. openedLocation = opened.location.href
  3845. opened.close()
  3846. window.postMessage({openedLocation}, '*')
  3847. `);
  3848. const [, data] = await p;
  3849. expect(data.pageContext.openedLocation).to.equal('about:blank');
  3850. });
  3851. });
  3852. describe('reloading with allowRendererProcessReuse enabled', () => {
  3853. it('does not cause Node.js module API hangs after reload', (done) => {
  3854. const w = new BrowserWindow({
  3855. show: false,
  3856. webPreferences: {
  3857. nodeIntegration: true
  3858. }
  3859. });
  3860. let count = 0;
  3861. ipcMain.on('async-node-api-done', () => {
  3862. if (count === 3) {
  3863. ipcMain.removeAllListeners('async-node-api-done');
  3864. done();
  3865. } else {
  3866. count++;
  3867. w.reload();
  3868. }
  3869. });
  3870. w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html'));
  3871. });
  3872. });
  3873. describe('window.webContents.focus()', () => {
  3874. afterEach(closeAllWindows);
  3875. it('focuses window', async () => {
  3876. const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 });
  3877. w1.loadURL('about:blank');
  3878. const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 });
  3879. w2.loadURL('about:blank');
  3880. w1.webContents.focus();
  3881. // Give focus some time to switch to w1
  3882. await delay();
  3883. expect(w1.webContents.isFocused()).to.be.true('focuses window');
  3884. });
  3885. });
  3886. ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => {
  3887. let w: BrowserWindow;
  3888. beforeEach(function () {
  3889. w = new BrowserWindow({
  3890. width: 100,
  3891. height: 100,
  3892. show: false,
  3893. webPreferences: {
  3894. backgroundThrottling: false,
  3895. offscreen: true
  3896. }
  3897. });
  3898. });
  3899. afterEach(closeAllWindows);
  3900. it('creates offscreen window with correct size', async () => {
  3901. const paint = emittedOnce(w.webContents, 'paint');
  3902. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3903. const [,, data] = await paint;
  3904. expect(data.constructor.name).to.equal('NativeImage');
  3905. expect(data.isEmpty()).to.be.false('data is empty');
  3906. const size = data.getSize();
  3907. const { scaleFactor } = screen.getPrimaryDisplay();
  3908. expect(size.width).to.be.closeTo(100 * scaleFactor, 2);
  3909. expect(size.height).to.be.closeTo(100 * scaleFactor, 2);
  3910. });
  3911. it('does not crash after navigation', () => {
  3912. w.webContents.loadURL('about:blank');
  3913. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3914. });
  3915. describe('window.webContents.isOffscreen()', () => {
  3916. it('is true for offscreen type', () => {
  3917. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3918. expect(w.webContents.isOffscreen()).to.be.true('isOffscreen');
  3919. });
  3920. it('is false for regular window', () => {
  3921. const c = new BrowserWindow({ show: false });
  3922. expect(c.webContents.isOffscreen()).to.be.false('isOffscreen');
  3923. c.destroy();
  3924. });
  3925. });
  3926. describe('window.webContents.isPainting()', () => {
  3927. it('returns whether is currently painting', async () => {
  3928. const paint = emittedOnce(w.webContents, 'paint');
  3929. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3930. await paint;
  3931. expect(w.webContents.isPainting()).to.be.true('isPainting');
  3932. });
  3933. });
  3934. describe('window.webContents.stopPainting()', () => {
  3935. it('stops painting', async () => {
  3936. const domReady = emittedOnce(w.webContents, 'dom-ready');
  3937. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3938. await domReady;
  3939. w.webContents.stopPainting();
  3940. expect(w.webContents.isPainting()).to.be.false('isPainting');
  3941. });
  3942. });
  3943. describe('window.webContents.startPainting()', () => {
  3944. it('starts painting', async () => {
  3945. const domReady = emittedOnce(w.webContents, 'dom-ready');
  3946. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3947. await domReady;
  3948. w.webContents.stopPainting();
  3949. w.webContents.startPainting();
  3950. await emittedOnce(w.webContents, 'paint');
  3951. expect(w.webContents.isPainting()).to.be.true('isPainting');
  3952. });
  3953. });
  3954. describe('frameRate APIs', () => {
  3955. it('has default frame rate (function)', async () => {
  3956. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3957. await emittedOnce(w.webContents, 'paint');
  3958. expect(w.webContents.getFrameRate()).to.equal(60);
  3959. });
  3960. it('has default frame rate (property)', async () => {
  3961. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3962. await emittedOnce(w.webContents, 'paint');
  3963. expect(w.webContents.frameRate).to.equal(60);
  3964. });
  3965. it('sets custom frame rate (function)', async () => {
  3966. const domReady = emittedOnce(w.webContents, 'dom-ready');
  3967. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3968. await domReady;
  3969. w.webContents.setFrameRate(30);
  3970. await emittedOnce(w.webContents, 'paint');
  3971. expect(w.webContents.getFrameRate()).to.equal(30);
  3972. });
  3973. it('sets custom frame rate (property)', async () => {
  3974. const domReady = emittedOnce(w.webContents, 'dom-ready');
  3975. w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html'));
  3976. await domReady;
  3977. w.webContents.frameRate = 30;
  3978. await emittedOnce(w.webContents, 'paint');
  3979. expect(w.webContents.frameRate).to.equal(30);
  3980. });
  3981. });
  3982. });
  3983. });