forked from electron/electron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-browser-window-spec.ts
6393 lines (5602 loc) · 223 KB
/
api-browser-window-spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { expect } from 'chai';
import * as childProcess from 'node:child_process';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as qs from 'node:querystring';
import * as http from 'node:http';
import * as os from 'node:os';
import { AddressInfo } from 'node:net';
import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, webFrameMain, session, WebContents, WebFrameMain } from 'electron/main';
import { emittedUntil, emittedNTimes } from './lib/events-helpers';
import { ifit, ifdescribe, defer, listen } from './lib/spec-helpers';
import { closeWindow, closeAllWindows } from './lib/window-helpers';
import { areColorsSimilar, captureScreen, HexColors, getPixelColor } from './lib/screen-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
const fixtures = path.resolve(__dirname, 'fixtures');
const mainFixtures = path.resolve(__dirname, 'fixtures');
// Is the display's scale factor possibly causing rounding of pixel coordinate
// values?
const isScaleFactorRounding = () => {
const { scaleFactor } = screen.getPrimaryDisplay();
// Return true if scale factor is non-integer value
if (Math.round(scaleFactor) !== scaleFactor) return true;
// Return true if scale factor is odd number above 2
return scaleFactor > 2 && scaleFactor % 2 === 1;
};
const expectBoundsEqual = (actual: any, expected: any) => {
if (!isScaleFactorRounding()) {
expect(expected).to.deep.equal(actual);
} else if (Array.isArray(actual)) {
expect(actual[0]).to.be.closeTo(expected[0], 1);
expect(actual[1]).to.be.closeTo(expected[1], 1);
} else {
expect(actual.x).to.be.closeTo(expected.x, 1);
expect(actual.y).to.be.closeTo(expected.y, 1);
expect(actual.width).to.be.closeTo(expected.width, 1);
expect(actual.height).to.be.closeTo(expected.height, 1);
}
};
const isBeforeUnload = (event: Event, level: number, message: string) => {
return (message === 'beforeunload');
};
describe('BrowserWindow module', () => {
it('sets the correct class name on the prototype', () => {
expect(BrowserWindow.prototype.constructor.name).to.equal('BrowserWindow');
});
describe('BrowserWindow constructor', () => {
it('allows passing void 0 as the webContents', async () => {
expect(() => {
const w = new BrowserWindow({
show: false,
// apparently void 0 had different behaviour from undefined in the
// issue that this test is supposed to catch.
webContents: void 0 // eslint-disable-line no-void
} as any);
w.destroy();
}).not.to.throw();
});
ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
const appProcess = childProcess.spawn(process.execPath, [appPath]);
await once(appProcess, 'exit');
});
it('does not crash or throw when passed an invalid icon', async () => {
expect(() => {
const w = new BrowserWindow({
icon: undefined
} as any);
w.destroy();
}).not.to.throw();
});
});
describe('garbage collection', () => {
const v8Util = process._linkedBinding('electron_common_v8_util');
afterEach(closeAllWindows);
it('window does not get garbage collected when opened', async () => {
const w = new BrowserWindow({ show: false });
// Keep a weak reference to the window.
const wr = new WeakRef(w);
await setTimeout();
// Do garbage collection, since |w| is not referenced in this closure
// it would be gone after next call if there is no other reference.
v8Util.requestGarbageCollectionForTesting();
await setTimeout();
expect(wr.deref()).to.not.be.undefined();
});
});
describe('BrowserWindow.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should work if called when a messageBox is showing', async () => {
const closed = once(w, 'closed');
dialog.showMessageBox(w, { message: 'Hello Error' });
w.close();
await closed;
});
it('closes window without rounded corners', async () => {
await closeWindow(w);
w = new BrowserWindow({ show: false, frame: false, roundedCorners: false });
const closed = once(w, 'closed');
w.close();
await closed;
});
it('should not crash if called after webContents is destroyed', () => {
w.webContents.destroy();
w.webContents.on('destroyed', () => w.close());
});
it('should allow access to id after destruction', async () => {
const closed = once(w, 'closed');
w.destroy();
await closed;
expect(w.id).to.be.a('number');
});
it('should emit unload handler', async () => {
await w.loadFile(path.join(fixtures, 'api', 'unload.html'));
const closed = once(w, 'closed');
w.close();
await closed;
const test = path.join(fixtures, 'api', 'unload');
const content = fs.readFileSync(test);
fs.unlinkSync(test);
expect(String(content)).to.equal('unload');
});
it('should emit beforeunload handler', async () => {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'before-unload-fired');
});
it('should not crash when keyboard event is sent before closing', async () => {
await w.loadURL('data:text/html,pls no crash');
const closed = once(w, 'closed');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
w.close();
await closed;
});
describe('when invoked synchronously inside navigation observer', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((request, response) => {
switch (request.url) {
case '/net-error':
response.destroy();
break;
case '/301':
response.statusCode = 301;
response.setHeader('Location', '/200');
response.end();
break;
case '/200':
response.statusCode = 200;
response.end('hello');
break;
case '/title':
response.statusCode = 200;
response.end('<title>Hello</title>');
break;
default:
throw new Error(`unsupported endpoint: ${request.url}`);
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
const events = [
{ name: 'did-start-loading', path: '/200' },
{ name: 'dom-ready', path: '/200' },
{ name: 'page-title-updated', path: '/title' },
{ name: 'did-stop-loading', path: '/200' },
{ name: 'did-finish-load', path: '/200' },
{ name: 'did-frame-finish-load', path: '/200' },
{ name: 'did-fail-load', path: '/net-error' }
];
for (const { name, path } of events) {
it(`should not crash when closed during ${name}`, async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once((name as any), () => {
w.close();
});
const destroyed = once(w.webContents, 'destroyed');
w.webContents.loadURL(url + path);
await destroyed;
});
}
});
});
describe('window.close()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('should emit unload event', async () => {
w.loadFile(path.join(fixtures, 'api', 'close.html'));
await once(w, 'closed');
const test = path.join(fixtures, 'api', 'close');
const content = fs.readFileSync(test).toString();
fs.unlinkSync(test);
expect(content).to.equal('close');
});
it('should emit beforeunload event', async function () {
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.webContents.executeJavaScript('window.close()', true);
await once(w.webContents, 'before-unload-fired');
});
});
describe('BrowserWindow.destroy()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
it('prevents users to access methods of webContents', async () => {
const contents = w.webContents;
w.destroy();
await new Promise(setImmediate);
expect(() => {
contents.getProcessId();
}).to.throw('Object has been destroyed');
});
it('should not crash when destroying windows with pending events', () => {
const focusListener = () => { };
app.on('browser-window-focus', focusListener);
const windowCount = 3;
const windowOptions = {
show: false,
width: 400,
height: 400,
webPreferences: {
backgroundThrottling: false
}
};
const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions));
windows.forEach(win => win.show());
windows.forEach(win => win.focus());
windows.forEach(win => win.destroy());
app.removeListener('browser-window-focus', focusListener);
});
});
describe('BrowserWindow.loadURL(url)', () => {
let w: BrowserWindow;
const scheme = 'other';
const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js');
before(() => {
protocol.registerFileProtocol(scheme, (request, callback) => {
callback(srcPath);
});
});
after(() => {
protocol.unregisterProtocol(scheme);
});
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
let server: http.Server;
let url: string;
let postData = null as any;
before(async () => {
const filePath = path.join(fixtures, 'pages', 'a.html');
const fileStats = fs.statSync(filePath);
postData = [
{
type: 'rawData',
bytes: Buffer.from('username=test&file=')
},
{
type: 'file',
filePath: filePath,
offset: 0,
length: fileStats.size,
modificationTime: fileStats.mtime.getTime() / 1000
}
];
server = http.createServer((req, res) => {
function respond () {
if (req.method === 'POST') {
let body = '';
req.on('data', (data) => {
if (data) body += data;
});
req.on('end', () => {
const parsedData = qs.parse(body);
fs.readFile(filePath, (err, data) => {
if (err) return;
if (parsedData.username === 'test' &&
parsedData.file === data.toString()) {
res.end();
}
});
});
} else if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else {
res.end();
}
}
setTimeout(req.url && req.url.includes('slow') ? 200 : 0).then(respond);
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('should emit did-start-loading event', async () => {
const didStartLoading = once(w.webContents, 'did-start-loading');
w.loadURL('about:blank');
await didStartLoading;
});
it('should emit ready-to-show event', async () => {
const readyToShow = once(w, 'ready-to-show');
w.loadURL('about:blank');
await readyToShow;
});
// DISABLED-FIXME(deepak1556): The error code now seems to be `ERR_FAILED`, verify what
// changed and adjust the test.
it('should emit did-fail-load event for files that do not exist', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('file://a.txt');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(code).to.equal(-6);
expect(desc).to.equal('ERR_FILE_NOT_FOUND');
expect(isMainFrame).to.equal(true);
});
it('should emit did-fail-load event for invalid URL', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL('http://example:port');
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should not emit did-fail-load for a successfully loaded media file', async () => {
w.webContents.on('did-fail-load', () => {
expect.fail('did-fail-load should not emit on media file loads');
});
const mediaStarted = once(w.webContents, 'media-started-playing');
w.loadFile(path.join(fixtures, 'cat-spin.mp4'));
await mediaStarted;
});
it('should set `mainFrame = false` on did-fail-load events in iframes', async () => {
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html'));
const [,,,, isMainFrame] = await didFailLoad;
expect(isMainFrame).to.equal(false);
});
it('does not crash in did-fail-provisional-load handler', (done) => {
w.webContents.once('did-fail-provisional-load', () => {
w.loadURL('http://127.0.0.1:11111');
done();
});
w.loadURL('http://127.0.0.1:11111');
});
it('should emit did-fail-load event for URL exceeding character limit', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const didFailLoad = once(w.webContents, 'did-fail-load');
w.loadURL(`data:image/png;base64,${data}`);
const [, code, desc,, isMainFrame] = await didFailLoad;
expect(desc).to.equal('ERR_INVALID_URL');
expect(code).to.equal(-300);
expect(isMainFrame).to.equal(true);
});
it('should return a promise', () => {
const p = w.loadURL('about:blank');
expect(p).to.have.property('then');
});
it('should return a promise that resolves', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('should return a promise that rejects on a load failure', async () => {
const data = Buffer.alloc(2 * 1024 * 1024).toString('base64');
const p = w.loadURL(`data:image/png;base64,${data}`);
await expect(p).to.eventually.be.rejected;
});
it('should return a promise that resolves even if pushState occurs during navigation', async () => {
const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>');
await expect(p).to.eventually.be.fulfilled;
});
describe('POST navigations', () => {
afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); });
it('supports specifying POST data', async () => {
await w.loadURL(url, { postData });
});
it('sets the content type header on URL encoded forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded');
});
it('sets the content type header on multi part forms', async () => {
await w.loadURL(url);
const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => {
w.webContents.session.webRequest.onBeforeSendHeaders((details) => {
resolve(details);
});
});
w.webContents.executeJavaScript(`
form = document.createElement('form')
document.body.appendChild(form)
form.method = 'POST'
form.enctype = 'multipart/form-data'
file = document.createElement('input')
file.type = 'file'
file.name = 'file'
form.appendChild(file)
form.submit()
`);
const details = await requestDetails;
expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true);
});
});
it('should support base url for data urls', async () => {
await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` });
expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong');
});
});
for (const sandbox of [false, true]) {
describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } });
});
afterEach(async () => {
await closeWindow(w);
w = null as unknown as BrowserWindow;
});
describe('will-navigate event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else {
res.end('');
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-navigate');
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
await event;
w.close();
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-navigate', (e, url) => {
e.preventDefault();
resolve(url);
});
});
expect(navigatedTo).to.equal(url + '/');
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await emittedUntil(w.webContents, 'did-frame-finish-load', (e: any, isMainFrame: boolean) => !isMainFrame);
let initiator: WebFrameMain | undefined;
w.webContents.on('will-navigate', (e) => {
initiator = e.initiator;
});
const subframe = w.webContents.mainFrame.frames[0];
subframe.executeJavaScript('document.getElementsByTagName("a")[0].click()', true);
await once(w.webContents, 'did-navigate');
expect(initiator).not.to.be.undefined();
expect(initiator).to.equal(subframe);
});
});
describe('will-frame-navigate event', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate-top') {
res.end('<a target=_top href="/">navigate _top</a>');
} else if (req.url === '/navigate-iframe') {
res.end('<a href="/test">navigate iframe</a>');
} else if (req.url === '/navigate-iframe?navigated') {
res.end('Successfully navigated');
} else if (req.url === '/navigate-iframe-immediately') {
res.end(`
<script type="text/javascript" charset="utf-8">
location.href += '?navigated'
</script>
`);
} else if (req.url === '/navigate-iframe-immediately?navigated') {
res.end('Successfully navigated');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
after(() => {
server.close();
});
it('allows the window to be closed from the event listener', (done) => {
w.webContents.once('will-frame-navigate', () => {
w.close();
done();
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented', (done) => {
let willNavigate = false;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html'));
});
it('can be prevented when navigating subframe', (done) => {
let willNavigate = false;
w.webContents.on('did-frame-navigate', (_event, _url, _httpResponseCode, _httpStatusText, isMainFrame, frameProcessId, frameRoutingId) => {
if (isMainFrame) return;
w.webContents.once('will-frame-navigate', (e) => {
willNavigate = true;
e.preventDefault();
});
w.webContents.on('did-stop-loading', () => {
const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
expect(frame).to.not.be.undefined();
if (willNavigate) {
// i.e. it shouldn't have had '?navigated' appended to it.
try {
expect(frame!.url.endsWith('/navigate-iframe-immediately')).to.be.true();
done();
} catch (e) {
done(e);
}
}
});
});
w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe-immediately"></iframe>`);
});
it('is triggered when navigating from file: to http:', async () => {
await w.loadFile(path.join(fixtures, 'api', 'blank.html'));
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.match(/^file:/);
});
it('is triggered when navigating from about:blank to http:', async () => {
await w.loadURL('about:blank');
w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`);
const navigatedTo = await new Promise(resolve => {
w.webContents.once('will-frame-navigate', (e) => {
e.preventDefault();
resolve(e.url);
});
});
expect(navigatedTo).to.equal(url);
expect(w.webContents.getURL()).to.equal('about:blank');
});
it('is triggered when a cross-origin iframe navigates _top', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`);
await setTimeout(1000);
let willFrameNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willFrameNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willFrameNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.true();
});
it('is triggered when a cross-origin iframe navigates itself', async () => {
await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-iframe"></iframe>`);
await setTimeout(1000);
let willNavigateEmitted = false;
let isMainFrameValue;
w.webContents.on('will-frame-navigate', (event) => {
willNavigateEmitted = true;
isMainFrameValue = event.isMainFrame;
});
const didNavigatePromise = once(w.webContents, 'did-frame-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: iframeTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await didNavigatePromise;
expect(willNavigateEmitted).to.be.true();
expect(isMainFrameValue).to.be.false();
});
it('can cancel when a cross-origin iframe navigates itself', async () => {
});
});
describe('will-redirect event', () => {
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/302') {
res.setHeader('Location', '/200');
res.statusCode = 302;
res.end();
} else if (req.url === '/navigate-302') {
res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`);
} else {
res.end();
}
});
url = (await listen(server)).url;
});
after(() => {
server.close();
});
it('is emitted on redirects', async () => {
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
});
it('is emitted after will-navigate on redirects', async () => {
let navigateCalled = false;
w.webContents.on('will-navigate', () => {
navigateCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/navigate-302`);
await willRedirect;
expect(navigateCalled).to.equal(true, 'should have called will-navigate first');
});
it('is emitted before did-stop-loading on redirects', async () => {
let stopCalled = false;
w.webContents.on('did-stop-loading', () => {
stopCalled = true;
});
const willRedirect = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await willRedirect;
expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first');
});
it('allows the window to be closed from the event listener', async () => {
const event = once(w.webContents, 'will-redirect');
w.loadURL(`${url}/302`);
await event;
w.close();
});
it('can be prevented', (done) => {
w.webContents.once('will-redirect', (event) => {
event.preventDefault();
});
w.webContents.on('will-navigate', (e, u) => {
expect(u).to.equal(`${url}/302`);
});
w.webContents.on('did-stop-loading', () => {
try {
expect(w.webContents.getURL()).to.equal(
`${url}/navigate-302`,
'url should not have changed after navigation event'
);
done();
} catch (e) {
done(e);
}
});
w.webContents.on('will-redirect', (e, u) => {
try {
expect(u).to.equal(`${url}/200`);
} catch (e) {
done(e);
}
});
w.loadURL(`${url}/navigate-302`);
});
});
describe('ordering', () => {
let server = null as unknown as http.Server;
let url = null as unknown as string;
const navigationEvents = [
'did-start-navigation',
'did-navigate-in-page',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
before((done) => {
server = http.createServer((req, res) => {
if (req.url === '/navigate') {
res.end('<a href="/">navigate</a>');
} else if (req.url === '/redirect') {
res.end('<a href="/redirect2">redirect</a>');
} else if (req.url === '/redirect2') {
res.statusCode = 302;
res.setHeader('location', url);
res.end();
} else if (req.url === '/in-page') {
res.end('<a href="#in-page">redirect</a><div id="in-page"></div>');
} else {
res.end('');
}
});
server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`;
done();
});
});
it('for initial navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'did-frame-navigate',
'did-navigate'
];
const allEvents = Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const timeout = setTimeout(1000);
w.loadURL(url);
await Promise.race([allEvents, timeout]);
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('for second navigation, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}navigate`);
await once(w.webContents, 'did-navigate');
await setTimeout(2000);
Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await navigationFinished;
expect(firedEvents).to.deep.equal(expectedEventOrder);
});
it('when navigating with redirection, event order is consistent', async () => {
const firedEvents: string[] = [];
const expectedEventOrder = [
'did-start-navigation',
'will-frame-navigate',
'will-navigate',
'will-redirect',
'did-redirect-navigation',
'did-frame-navigate',
'did-navigate'
];
w.loadURL(`${url}redirect`);
await once(w.webContents, 'did-navigate');
await setTimeout(2000);
Promise.all(navigationEvents.map(event =>
once(w.webContents, event).then(() => firedEvents.push(event))
));
const navigationFinished = once(w.webContents, 'did-navigate');
w.webContents.debugger.attach('1.1');
const targets = await w.webContents.debugger.sendCommand('Target.getTargets');
const pageTarget = targets.targetInfos.find((t: any) => t.type === 'page');
const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', {
targetId: pageTarget.targetId,
flatten: true
});
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 10,
y: 10,
clickCount: 1,
button: 'left'
}, sessionId);
await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 10,
y: 10,
clickCount: 1,