forked from electron/electron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi-web-contents-spec.ts
2404 lines (2100 loc) · 85.6 KB
/
api-web-contents-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 { AddressInfo } from 'node:net';
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as http from 'node:http';
import { BrowserWindow, ipcMain, webContents, session, app, BrowserView, WebContents } from 'electron/main';
import { closeAllWindows } from './lib/window-helpers';
import { ifdescribe, defer, waitUntil, listen, ifit } from './lib/spec-helpers';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
const pdfjs = require('pdfjs-dist');
const fixturesPath = path.resolve(__dirname, 'fixtures');
const mainFixturesPath = path.resolve(__dirname, 'fixtures');
const features = process._linkedBinding('electron_common_features');
describe('webContents module', () => {
describe('getAllWebContents() API', () => {
afterEach(closeAllWindows);
it('returns an array of web contents', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: { webviewTag: true }
});
w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html'));
await once(w.webContents, 'did-attach-webview') as [any, WebContents];
w.webContents.openDevTools();
await once(w.webContents, 'devtools-opened');
const all = webContents.getAllWebContents().sort((a, b) => {
return a.id - b.id;
});
expect(all).to.have.length(3);
expect(all[0].getType()).to.equal('window');
expect(all[all.length - 2].getType()).to.equal('webview');
expect(all[all.length - 1].getType()).to.equal('remote');
});
});
describe('fromId()', () => {
it('returns undefined for an unknown id', () => {
expect(webContents.fromId(12345)).to.be.undefined();
});
});
describe('fromFrame()', () => {
it('returns WebContents for mainFrame', () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents);
});
it('returns undefined for disposed frame', async () => {
const contents = (webContents as typeof ElectronInternal.WebContents).create();
const { mainFrame } = contents;
contents.destroy();
await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined');
});
it('throws when passing invalid argument', async () => {
let errored = false;
try {
webContents.fromFrame({} as any);
} catch {
errored = true;
}
expect(errored).to.be.true();
});
});
describe('fromDevToolsTargetId()', () => {
it('returns WebContents for attached DevTools target', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
try {
await w.webContents.debugger.attach('1.3');
const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo');
expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents);
} finally {
await w.webContents.debugger.detach();
}
});
it('returns undefined for an unknown id', () => {
expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined();
});
});
describe('will-prevent-unload event', function () {
afterEach(closeAllWindows);
it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('does not emit if beforeunload returns undefined in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
view.webContents.once('will-prevent-unload', () => {
expect.fail('should not have fired');
});
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
it('emits if beforeunload returns false in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(w.webContents, 'will-prevent-unload');
});
it('emits if beforeunload returns false in a BrowserView', async () => {
const w = new BrowserWindow({ show: false });
const view = new BrowserView();
w.setBrowserView(view);
view.setBounds(w.getBounds());
await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
w.close();
await once(view.webContents, 'will-prevent-unload');
});
it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => {
const w = new BrowserWindow({ show: false });
w.webContents.once('will-prevent-unload', event => event.preventDefault());
await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html'));
const wait = once(w, 'closed');
w.close();
await wait;
});
});
describe('webContents.send(channel, args...)', () => {
afterEach(closeAllWindows);
it('throws an error when the channel is missing', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
(w.webContents.send as any)();
}).to.throw('Missing required channel argument');
expect(() => {
w.webContents.send(null as any);
}).to.throw('Missing required channel argument');
});
it('does not block node async APIs when sent before document is ready', (done) => {
// Please reference https://github.com/electron/electron/issues/19368 if
// this test fails.
ipcMain.once('async-node-api-done', () => {
done();
});
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
sandbox: false,
contextIsolation: false
}
});
w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html'));
setTimeout(50).then(() => {
w.webContents.send('test');
});
});
});
ifdescribe(features.isPrintingEnabled())('webContents.print()', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('throws when invalid settings are passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print(true);
}).to.throw('webContents.print(): Invalid print settings specified.');
});
it('throws when an invalid pageSize is passed', () => {
const badSize = 5;
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: badSize });
}).to.throw(`Unsupported pageSize: ${badSize}`);
});
it('throws when an invalid callback is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({}, true);
}).to.throw('webContents.print(): Invalid optional callback provided.');
});
it('fails when an invalid deviceName is passed', (done) => {
w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, (success, reason) => {
expect(success).to.equal(false);
expect(reason).to.match(/Invalid deviceName provided/);
done();
});
});
it('throws when an invalid pageSize is passed', () => {
expect(() => {
// @ts-ignore this line is intentionally incorrect
w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {});
}).to.throw('Unsupported pageSize: i-am-a-bad-pagesize');
});
it('throws when an invalid custom pageSize is passed', () => {
expect(() => {
w.webContents.print({
pageSize: {
width: 100,
height: 200
}
});
}).to.throw('height and width properties must be minimum 352 microns.');
});
it('does not crash with custom margins', () => {
expect(() => {
w.webContents.print({
silent: true,
margins: {
marginType: 'custom',
top: 1,
bottom: 1,
left: 1,
right: 1
}
});
}).to.not.throw();
});
});
describe('webContents.executeJavaScript', () => {
describe('in about:blank', () => {
const expected = 'hello, world!';
const expectedErrorMsg = 'woops!';
const code = `(() => "${expected}")()`;
const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`;
const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`;
const errorTypes = new Set([
Error,
ReferenceError,
EvalError,
RangeError,
SyntaxError,
TypeError,
URIError
]);
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } });
await w.loadURL('about:blank');
});
after(closeAllWindows);
it('resolves the returned promise with the result', async () => {
const result = await w.webContents.executeJavaScript(code);
expect(result).to.equal(expected);
});
it('resolves the returned promise with the result if the code returns an asynchronous promise', async () => {
const result = await w.webContents.executeJavaScript(asyncCode);
expect(result).to.equal(expected);
});
it('rejects the returned promise if an async error is thrown', async () => {
await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg);
});
it('rejects the returned promise with an error if an Error.prototype is thrown', async () => {
for (const error of errorTypes) {
await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`))
.to.eventually.be.rejectedWith(error);
}
});
});
describe('on a real page', () => {
let w: BrowserWindow;
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
let server: http.Server;
let serverUrl: string;
before(async () => {
server = http.createServer((request, response) => {
response.end();
});
serverUrl = (await listen(server)).url;
});
after(() => {
server.close();
});
it('works after page load and during subframe load', async () => {
await w.loadURL(serverUrl);
// initiate a sub-frame load, then try and execute script during it
await w.webContents.executeJavaScript(`
var iframe = document.createElement('iframe')
iframe.src = '${serverUrl}/slow'
document.body.appendChild(iframe)
null // don't return the iframe
`);
await w.webContents.executeJavaScript('console.log(\'hello\')');
});
it('executes after page load', async () => {
const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()');
w.loadURL(serverUrl);
const result = await executeJavaScript;
expect(result).to.equal('test');
});
});
});
describe('webContents.executeJavaScriptInIsolatedWorld', () => {
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } });
await w.loadURL('about:blank');
});
it('resolves the returned promise with the result', async () => {
await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]);
const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]);
const mainWorldResult = await w.webContents.executeJavaScript('window.X');
expect(isolatedResult).to.equal(123);
expect(mainWorldResult).to.equal(undefined);
});
});
describe('loadURL() promise API', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false });
});
afterEach(closeAllWindows);
it('resolves when done loading', async () => {
await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled();
});
it('resolves when done loading a file URL', async () => {
await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled();
});
it('resolves when navigating within the page', async () => {
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await setTimeout();
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
it('rejects when failing to load a file URL', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FILE_NOT_FOUND');
});
// FIXME: Temporarily disable on WOA until
// https://github.com/electron/electron/issues/20008 is resolved
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('rejects when loading fails due to DNS not resolved', async () => {
await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_NAME_NOT_RESOLVED');
});
it('rejects when navigation is cancelled due to a bad scheme', async () => {
await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FAILED');
});
it('does not crash when loading a new URL with emulation settings set', async () => {
const setEmulation = async () => {
if (w.webContents) {
w.webContents.debugger.attach('1.3');
const deviceMetrics = {
width: 700,
height: 600,
deviceScaleFactor: 2,
mobile: true,
dontSetVisibleSize: true
};
await w.webContents.debugger.sendCommand(
'Emulation.setDeviceMetricsOverride',
deviceMetrics
);
}
};
try {
await w.loadURL(`file://${fixturesPath}/pages/blank.html`);
await setEmulation();
await w.loadURL('data:text/html,<h1>HELLO</h1>');
await setEmulation();
} catch (e) {
expect((e as Error).message).to.match(/Debugger is already attached to the target/);
}
});
it('sets appropriate error information on rejection', async () => {
let err: any;
try {
await w.loadURL('file:non-existent');
} catch (e) {
err = e;
}
expect(err).not.to.be.null();
expect(err.code).to.eql('ERR_FILE_NOT_FOUND');
expect(err.errno).to.eql(-6);
expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent');
});
it('rejects if the load is aborted', async () => {
const s = http.createServer(() => { /* never complete the request */ });
const { port } = await listen(s);
const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/);
// load a different file before the first load completes, causing the
// first load to be aborted.
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
await p;
s.close();
});
it("doesn't reject when a subframe fails to load", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="http://err.name.not.resolved"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.end();
await main;
s.close();
});
it("doesn't resolve when a subframe loads", async () => {
let resp = null as unknown as http.ServerResponse;
const s = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<iframe src="about:blank"></iframe>');
resp = res;
// don't end the response yet
});
const { port } = await listen(s);
const p = new Promise<void>(resolve => {
w.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
if (!isMainFrame) {
resolve();
}
});
});
const main = w.loadURL(`http://127.0.0.1:${port}`);
await p;
resp.destroy(); // cause the main request to fail
await expect(main).to.eventually.be.rejected()
.and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING
s.close();
});
});
describe('getFocusedWebContents() API', () => {
afterEach(closeAllWindows);
// FIXME
ifit(!(process.platform === 'win32' && process.arch === 'arm64'))('returns the focused web contents', async () => {
const w = new BrowserWindow({ show: true });
await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
const devToolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools();
await devToolsOpened;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.devToolsWebContents!.id);
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(webContents.getFocusedWebContents()?.id).to.equal(w.webContents.id);
});
it('does not crash when called on a detached dev tools window', async () => {
const w = new BrowserWindow({ show: true });
w.webContents.openDevTools({ mode: 'detach' });
w.webContents.inspectElement(100, 100);
// For some reason we have to wait for two focused events...?
await once(w.webContents, 'devtools-focused');
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
// Work around https://github.com/electron/electron/issues/19985
await setTimeout();
const devToolsClosed = once(w.webContents, 'devtools-closed');
w.webContents.closeDevTools();
await devToolsClosed;
expect(() => { webContents.getFocusedWebContents(); }).to.not.throw();
});
});
describe('setDevToolsWebContents() API', () => {
afterEach(closeAllWindows);
it('sets arbitrary webContents as devtools', async () => {
const w = new BrowserWindow({ show: false });
const devtools = new BrowserWindow({ show: false });
const promise = once(devtools.webContents, 'dom-ready');
w.webContents.setDevToolsWebContents(devtools.webContents);
w.webContents.openDevTools();
await promise;
expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true();
const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name');
expect(result).to.equal('InspectorFrontendHostImpl');
devtools.destroy();
});
});
describe('isFocused() API', () => {
it('returns false when the window is hidden', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
expect(w.isVisible()).to.be.false();
expect(w.webContents.isFocused()).to.be.false();
});
});
describe('isCurrentlyAudible() API', () => {
afterEach(closeAllWindows);
it('returns whether audio is playing', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await w.webContents.executeJavaScript(`
window.context = new AudioContext
// Start in suspended state, because of the
// new web audio api policy.
context.suspend()
window.oscillator = context.createOscillator()
oscillator.connect(context.destination)
oscillator.start()
`);
let p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('context.resume()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.true();
p = once(w.webContents, 'audio-state-changed');
w.webContents.executeJavaScript('oscillator.stop()');
await p;
expect(w.webContents.isCurrentlyAudible()).to.be.false();
});
});
describe('openDevTools() API', () => {
afterEach(closeAllWindows);
it('can show window with activation', async () => {
const w = new BrowserWindow({ show: false });
const focused = once(w, 'focus');
w.show();
await focused;
expect(w.isFocused()).to.be.true();
const blurred = once(w, 'blur');
w.webContents.openDevTools({ mode: 'detach', activate: true });
await Promise.all([
once(w.webContents, 'devtools-opened'),
once(w.webContents, 'devtools-focused')
]);
await blurred;
expect(w.isFocused()).to.be.false();
});
it('can show window without activation', async () => {
const w = new BrowserWindow({ show: false });
const devtoolsOpened = once(w.webContents, 'devtools-opened');
w.webContents.openDevTools({ mode: 'detach', activate: false });
await devtoolsOpened;
expect(w.webContents.isDevToolsOpened()).to.be.true();
});
});
describe('before-input-event event', () => {
afterEach(closeAllWindows);
it('can prevent document keyboard events', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
const keyDown = new Promise(resolve => {
ipcMain.once('keydown', (event, key) => resolve(key));
});
w.webContents.once('before-input-event', (event, input) => {
if (input.key === 'a') event.preventDefault();
});
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' });
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' });
expect(await keyDown).to.equal('b');
});
it('has the correct properties', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testBeforeInput = async (opts: any) => {
const modifiers = [];
if (opts.shift) modifiers.push('shift');
if (opts.control) modifiers.push('control');
if (opts.alt) modifiers.push('alt');
if (opts.meta) modifiers.push('meta');
if (opts.isAutoRepeat) modifiers.push('isAutoRepeat');
const p = once(w.webContents, 'before-input-event') as Promise<[any, Electron.Input]>;
w.webContents.sendInputEvent({
type: opts.type,
keyCode: opts.keyCode,
modifiers: modifiers as any
});
const [, input] = await p;
expect(input.type).to.equal(opts.type);
expect(input.key).to.equal(opts.key);
expect(input.code).to.equal(opts.code);
expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat);
expect(input.shift).to.equal(opts.shift);
expect(input.control).to.equal(opts.control);
expect(input.alt).to.equal(opts.alt);
expect(input.meta).to.equal(opts.meta);
};
await testBeforeInput({
type: 'keyDown',
key: 'A',
code: 'KeyA',
keyCode: 'a',
shift: true,
control: true,
alt: true,
meta: true,
isAutoRepeat: true
});
await testBeforeInput({
type: 'keyUp',
key: '.',
code: 'Period',
keyCode: '.',
shift: false,
control: true,
alt: true,
meta: false,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: '!',
code: 'Digit1',
keyCode: '1',
shift: true,
control: false,
alt: false,
meta: true,
isAutoRepeat: false
});
await testBeforeInput({
type: 'keyUp',
key: 'Tab',
code: 'Tab',
keyCode: 'Tab',
shift: false,
control: true,
alt: false,
meta: false,
isAutoRepeat: true
});
});
});
// On Mac, zooming isn't done with the mouse wheel.
ifdescribe(process.platform !== 'darwin')('zoom-changed', () => {
afterEach(closeAllWindows);
it('is emitted with the correct zoom-in info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: 1,
wheelTicksX: 0,
wheelTicksY: 1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('in');
};
await testZoomChanged();
});
it('is emitted with the correct zoom-out info', async () => {
const w = new BrowserWindow({ show: false });
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
const testZoomChanged = async () => {
w.webContents.sendInputEvent({
type: 'mouseWheel',
x: 300,
y: 300,
deltaX: 0,
deltaY: -1,
wheelTicksX: 0,
wheelTicksY: -1,
modifiers: ['control', 'meta']
});
const [, zoomDirection] = await once(w.webContents, 'zoom-changed') as [any, string];
expect(zoomDirection).to.equal('out');
};
await testZoomChanged();
});
});
describe('sendInputEvent(event)', () => {
let w: BrowserWindow;
beforeEach(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } });
await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html'));
});
afterEach(closeAllWindows);
it('can send keydown events', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send keydown events with modifiers', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
it('can send keydown events with special keys', async () => {
const keydown = once(ipcMain, 'keydown');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown;
expect(key).to.equal('Tab');
expect(code).to.equal('Tab');
expect(keyCode).to.equal(9);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.true();
});
it('can send char events', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('a');
expect(code).to.equal('KeyA');
expect(keyCode).to.equal(65);
expect(shiftKey).to.be.false();
expect(ctrlKey).to.be.false();
expect(altKey).to.be.false();
});
it('can send char events with modifiers', async () => {
const keypress = once(ipcMain, 'keypress');
w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' });
w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] });
const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress;
expect(key).to.equal('Z');
expect(code).to.equal('KeyZ');
expect(keyCode).to.equal(90);
expect(shiftKey).to.be.true();
expect(ctrlKey).to.be.true();
expect(altKey).to.be.false();
});
});
describe('insertCSS', () => {
afterEach(closeAllWindows);
it('supports inserting CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
await w.webContents.insertCSS('body { background-repeat: round; }');
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('round');
});
it('supports removing inserted CSS', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const key = await w.webContents.insertCSS('body { background-repeat: round; }');
await w.webContents.removeInsertedCSS(key);
const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
expect(result).to.equal('repeat');
});
});
describe('inspectElement()', () => {
afterEach(closeAllWindows);
it('supports inspecting an element in the devtools', async () => {
const w = new BrowserWindow({ show: false });
w.loadURL('about:blank');
const event = once(w.webContents, 'devtools-opened');
w.webContents.inspectElement(10, 10);
await event;
});
});
describe('startDrag({file, icon})', () => {
it('throws errors for a missing file or a missing/empty icon', () => {
const w = new BrowserWindow({ show: false });
expect(() => {
w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any);
}).to.throw('Must specify either \'file\' or \'files\' option');
expect(() => {
w.webContents.startDrag({ file: __filename } as any);
}).to.throw('\'icon\' parameter is required');
expect(() => {
w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') });
}).to.throw(/Failed to load image from path (.+)/);
});
});
describe('focus APIs', () => {
describe('focus()', () => {
afterEach(closeAllWindows);
it('does not blur the focused window when the web contents is hidden', async () => {
const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
w.show();
await w.loadURL('about:blank');
w.focus();
const child = new BrowserWindow({ show: false });
child.loadURL('about:blank');
child.webContents.focus();
const currentFocused = w.isFocused();
const childFocused = child.isFocused();
child.close();
expect(currentFocused).to.be.true();
expect(childFocused).to.be.false();
});
});
const moveFocusToDevTools = async (win: BrowserWindow) => {
const devToolsOpened = once(win.webContents, 'devtools-opened');
win.webContents.openDevTools({ mode: 'right' });
await devToolsOpened;
win.webContents.devToolsWebContents!.focus();
};
describe('focus event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is focused', async () => {
const w = new BrowserWindow({ show: false });
await w.loadURL('about:blank');
await moveFocusToDevTools(w);
const focusPromise = once(w.webContents, 'focus');
w.webContents.focus();
await expect(focusPromise).to.eventually.be.fulfilled();
});
});
describe('blur event', () => {
afterEach(closeAllWindows);
it('is triggered when web contents is blurred', async () => {
const w = new BrowserWindow({ show: true });
await w.loadURL('about:blank');
w.webContents.focus();
const blurPromise = once(w.webContents, 'blur');
await moveFocusToDevTools(w);
await expect(blurPromise).to.eventually.be.fulfilled();
});
});
});
describe('getOSProcessId()', () => {
afterEach(closeAllWindows);
it('returns a valid process id', async () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getOSProcessId()).to.equal(0);
await w.loadURL('about:blank');
expect(w.webContents.getOSProcessId()).to.be.above(0);
});
});
describe('getMediaSourceId()', () => {
afterEach(closeAllWindows);
it('returns a valid stream id', () => {
const w = new BrowserWindow({ show: false });
expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty();
});
});
describe('userAgent APIs', () => {
it('is not empty by default', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
expect(userAgent).to.be.a('string').that.is.not.empty();
});
it('can set the user agent (functions)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.getUserAgent();
w.webContents.setUserAgent('my-user-agent');
expect(w.webContents.getUserAgent()).to.equal('my-user-agent');
w.webContents.setUserAgent(userAgent);
expect(w.webContents.getUserAgent()).to.equal(userAgent);
});
it('can set the user agent (properties)', () => {
const w = new BrowserWindow({ show: false });
const userAgent = w.webContents.userAgent;
w.webContents.userAgent = 'my-user-agent';
expect(w.webContents.userAgent).to.equal('my-user-agent');
w.webContents.userAgent = userAgent;
expect(w.webContents.userAgent).to.equal(userAgent);
});
});
describe('audioMuted APIs', () => {
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.setAudioMuted(true);
expect(w.webContents.isAudioMuted()).to.be.true();
w.webContents.setAudioMuted(false);
expect(w.webContents.isAudioMuted()).to.be.false();
});
it('can set the audio mute level (functions)', () => {
const w = new BrowserWindow({ show: false });
w.webContents.audioMuted = true;
expect(w.webContents.audioMuted).to.be.true();
w.webContents.audioMuted = false;
expect(w.webContents.audioMuted).to.be.false();
});
});
describe('zoom api', () => {
const hostZoomMap: Record<string, number> = {
host1: 0.3,
host2: 0.7,
host3: 0.2