forked from electron/electron
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwebview-spec.js
1543 lines (1302 loc) · 49.3 KB
/
webview-spec.js
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
const assert = require('assert')
const chai = require('chai')
const dirtyChai = require('dirty-chai')
const path = require('path')
const http = require('http')
const url = require('url')
const { ipcRenderer, remote } = require('electron')
const { app, session, ipcMain, BrowserWindow } = remote
const { closeWindow } = require('./window-helpers')
const { emittedOnce, waitForEvent } = require('./events-helpers')
const { expect } = chai
chai.use(dirtyChai)
const isCI = remote.getGlobal('isCi')
const nativeModulesEnabled = remote.getGlobal('nativeModulesEnabled')
/* Most of the APIs here don't use standard callbacks */
/* eslint-disable standard/no-callback-literal */
describe('<webview> tag', function () {
this.timeout(3 * 60 * 1000)
const fixtures = path.join(__dirname, 'fixtures')
let webview = null
let w = null
const openTheWindow = async (...args) => {
await closeTheWindow()
w = new BrowserWindow(...args)
return w
}
const closeTheWindow = async () => {
await closeWindow(w)
w = null
}
const loadWebView = async (webview, attributes = {}) => {
for (const [name, value] of Object.entries(attributes)) {
webview.setAttribute(name, value)
}
document.body.appendChild(webview)
await waitForEvent(webview, 'did-finish-load')
return webview
}
const startLoadingWebViewAndWaitForMessage = async (webview, attributes = {}) => {
loadWebView(webview, attributes) // Don't wait for load to be finished.
const event = await waitForEvent(webview, 'console-message')
return event.message
}
beforeEach(() => {
webview = new WebView()
})
afterEach(() => {
if (!document.body.contains(webview)) {
document.body.appendChild(webview)
}
webview.remove()
return closeTheWindow()
})
it('works without script tag in page', async () => {
const w = await openTheWindow({ show: false })
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'))
await emittedOnce(ipcMain, 'pong')
})
it('is disabled when nodeIntegration is disabled', async () => {
const w = await openTheWindow({
show: false,
webPreferences: {
nodeIntegration: false,
preload: path.join(fixtures, 'module', 'preload-webview.js')
}
})
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'))
const [, type] = await emittedOnce(ipcMain, 'webview')
expect(type).to.equal('undefined', 'WebView still exists')
})
it('is enabled when the webviewTag option is enabled and the nodeIntegration option is disabled', async () => {
const w = await openTheWindow({
show: false,
webPreferences: {
nodeIntegration: false,
preload: path.join(fixtures, 'module', 'preload-webview.js'),
webviewTag: true
}
})
w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'))
const [, type] = await emittedOnce(ipcMain, 'webview')
expect(type).to.not.equal('undefined', 'WebView is not created')
})
describe('src attribute', () => {
it('specifies the page to load', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `file://${fixtures}/pages/a.html`
})
expect(message).to.equal('a')
})
it('navigates to new page when changed', async () => {
await loadWebView(webview, {
src: `file://${fixtures}/pages/a.html`
})
webview.src = `file://${fixtures}/pages/b.html`
const { message } = await waitForEvent(webview, 'console-message')
expect(message).to.equal('b')
})
it('resolves relative URLs', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: '../fixtures/pages/e.html'
})
assert.strictEqual(message, 'Window script is loaded before preload script')
})
it('ignores empty values', () => {
assert.strictEqual(webview.src, '')
for (const emptyValue of ['', null, undefined]) {
webview.src = emptyValue
expect(webview.src).to.equal('')
}
})
})
describe('nodeintegration attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `file://${fixtures}/pages/c.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
})
})
it('inserts node symbols when set', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/d.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
})
})
it('loads node symbols after POST navigation when set', async function () {
// FIXME Figure out why this is timing out on AppVeyor
if (process.env.APPVEYOR === 'True') {
this.skip()
return
}
const message = await startLoadingWebViewAndWaitForMessage(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/post.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
})
})
it('disables node integration on child windows when it is disabled on the webview', (done) => {
app.once('browser-window-created', (event, window) => {
assert.strictEqual(window.webContents.getWebPreferences().nodeIntegration, false)
done()
})
const src = url.format({
pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`,
protocol: 'file',
query: {
p: `${fixtures}/pages/window-opener-node.html`
},
slashes: true
})
loadWebView(webview, {
allowpopups: 'on',
src
})
});
(nativeModulesEnabled ? it : it.skip)('loads native modules when navigation happens', async function () {
await loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/native-module.html`
})
webview.reload()
const { message } = await waitForEvent(webview, 'console-message')
assert.strictEqual(message, 'function')
})
})
describe('enableremotemodule attribute', () => {
const generateSpecs = (description, sandbox) => {
describe(description, () => {
const preload = `${fixtures}/module/preload-disable-remote.js`
const src = `file://${fixtures}/api/blank.html`
it('enables the remote module by default', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload,
src,
sandbox
})
const typeOfRemote = JSON.parse(message)
expect(typeOfRemote).to.equal('object')
})
it('disables the remote module when false', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload,
src,
sandbox,
enableremotemodule: false
})
const typeOfRemote = JSON.parse(message)
expect(typeOfRemote).to.equal('undefined')
})
})
}
generateSpecs('without sandbox', false)
generateSpecs('with sandbox', true)
})
describe('preload attribute', () => {
it('loads the script before other scripts in window', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload: `${fixtures}/module/preload.js`,
src: `file://${fixtures}/pages/e.html`
})
expect(message).to.be.a('string')
expect(message).to.be.not.equal('Window script is loaded before preload script')
})
it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload: `${fixtures}/module/preload-node-off.js`,
src: `file://${fixtures}/api/blank.html`
})
const types = JSON.parse(message)
expect(types).to.include({
process: 'object',
Buffer: 'function'
})
})
it('runs in the correct scope when sandboxed', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload: `${fixtures}/module/preload-context.js`,
src: `file://${fixtures}/api/blank.html`,
webpreferences: 'sandbox=yes'
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function', // arguments passed to it should be availale
electron: 'undefined', // objects from the scope it is called from should not be available
window: 'object', // the window object should be available
localVar: 'undefined' // but local variables should not be exposed to the window
})
})
it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload: `${fixtures}/module/preload-node-off-wrapper.js`,
src: `file://${fixtures}/api/blank.html`
})
const types = JSON.parse(message)
expect(types).to.include({
process: 'object',
Buffer: 'function'
})
})
it('receives ipc message in preload script', async () => {
await loadWebView(webview, {
preload: `${fixtures}/module/preload-ipc.js`,
src: `file://${fixtures}/pages/e.html`
})
const message = 'boom!'
webview.send('ping', message)
const { channel, args } = await waitForEvent(webview, 'ipc-message')
assert.strictEqual(channel, 'pong')
assert.deepStrictEqual(args, [message])
})
it('works without script tag in page', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload: `${fixtures}/module/preload.js`,
src: `file://${fixtures}pages/base-page.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
})
})
it('resolves relative URLs', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload: '../fixtures/module/preload.js',
src: `file://${fixtures}/pages/e.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
})
})
it('ignores empty values', () => {
assert.strictEqual(webview.preload, '')
for (const emptyValue of ['', null, undefined]) {
webview.preload = emptyValue
assert.strictEqual(webview.preload, '')
}
})
})
describe('httpreferrer attribute', () => {
it('sets the referrer url', (done) => {
const referrer = 'http://github.com/'
const server = http.createServer((req, res) => {
res.end()
server.close()
assert.strictEqual(req.headers.referer, referrer)
done()
}).listen(0, '127.0.0.1', () => {
const port = server.address().port
loadWebView(webview, {
httpreferrer: referrer,
src: `http://127.0.0.1:${port}`
})
})
})
})
describe('useragent attribute', () => {
it('sets the user agent', async () => {
const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `file://${fixtures}/pages/useragent.html`,
useragent: referrer
})
expect(message).to.equal(referrer)
})
})
describe('disablewebsecurity attribute', () => {
it('does not disable web security when not set', async () => {
const jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js')
const src = `<script src='file://${jqueryPath}'></script> <script>console.log('ok');</script>`
const encoded = btoa(unescape(encodeURIComponent(src)))
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `data:text/html;base64,${encoded}`
})
expect(message).to.be.a('string')
expect(message).to.contain('Not allowed to load local resource')
})
it('disables web security when set', async () => {
const jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js')
const src = `<script src='file://${jqueryPath}'></script> <script>console.log('ok');</script>`
const encoded = btoa(unescape(encodeURIComponent(src)))
const message = await startLoadingWebViewAndWaitForMessage(webview, {
disablewebsecurity: '',
src: `data:text/html;base64,${encoded}`
})
expect(message).to.equal('ok')
})
it('does not break node integration', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
disablewebsecurity: '',
nodeintegration: 'on',
src: `file://${fixtures}/pages/d.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
})
})
it('does not break preload script', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
disablewebsecurity: '',
preload: `${fixtures}/module/preload.js`,
src: `file://${fixtures}/pages/e.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object',
Buffer: 'function'
})
})
})
describe('partition attribute', () => {
it('inserts no node symbols when not set', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
partition: 'test1',
src: `file://${fixtures}/pages/c.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'undefined',
module: 'undefined',
process: 'undefined',
global: 'undefined'
})
})
it('inserts node symbols when set', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
nodeintegration: 'on',
partition: 'test2',
src: `file://${fixtures}/pages/d.html`
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
})
})
it('isolates storage for different id', async () => {
window.localStorage.setItem('test', 'one')
const message = await startLoadingWebViewAndWaitForMessage(webview, {
partition: 'test3',
src: `file://${fixtures}/pages/partition/one.html`
})
const parsedMessage = JSON.parse(message)
expect(parsedMessage).to.include({
numberOfEntries: 0,
testValue: null
})
})
it('uses current session storage when no id is provided', async () => {
const testValue = 'one'
window.localStorage.setItem('test', testValue)
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `file://${fixtures}/pages/partition/one.html`
})
const parsedMessage = JSON.parse(message)
expect(parsedMessage).to.include({
numberOfEntries: 1,
testValue
})
})
})
describe('allowpopups attribute', () => {
it('can not open new window when not set', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `file://${fixtures}/pages/window-open-hide.html`
})
expect(message).to.equal('null')
})
it('can open new window when set', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
allowpopups: 'on',
src: `file://${fixtures}/pages/window-open-hide.html`
})
expect(message).to.equal('window')
})
})
describe('webpreferences attribute', () => {
it('can enable nodeintegration', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `file://${fixtures}/pages/d.html`,
webpreferences: 'nodeIntegration'
})
const types = JSON.parse(message)
expect(types).to.include({
require: 'function',
module: 'object',
process: 'object'
})
})
it('can disable the remote module', async () => {
const message = await startLoadingWebViewAndWaitForMessage(webview, {
preload: `${fixtures}/module/preload-disable-remote.js`,
src: `file://${fixtures}/api/blank.html`,
webpreferences: 'enableRemoteModule=no'
})
const typeOfRemote = JSON.parse(message)
expect(typeOfRemote).to.equal('undefined')
})
it('can disables web security and enable nodeintegration', async () => {
const jqueryPath = path.join(__dirname, '/static/jquery-2.0.3.min.js')
const src = `<script src='file://${jqueryPath}'></script> <script>console.log(typeof require);</script>`
const encoded = btoa(unescape(encodeURIComponent(src)))
const message = await startLoadingWebViewAndWaitForMessage(webview, {
src: `data:text/html;base64,${encoded}`,
webpreferences: 'webSecurity=no, nodeIntegration=yes'
})
expect(message).to.equal('function')
})
it('can enable context isolation', async () => {
loadWebView(webview, {
allowpopups: 'yes',
preload: path.join(fixtures, 'api', 'isolated-preload.js'),
src: `file://${fixtures}/api/isolated.html`,
webpreferences: 'contextIsolation=yes'
})
const [, data] = await emittedOnce(ipcMain, 'isolated-world')
assert.deepStrictEqual(data, {
preloadContext: {
preloadProperty: 'number',
pageProperty: 'undefined',
typeofRequire: 'function',
typeofProcess: 'object',
typeofArrayPush: 'function',
typeofFunctionApply: 'function',
typeofPreloadExecuteJavaScriptProperty: 'undefined'
},
pageContext: {
preloadProperty: 'undefined',
pageProperty: 'string',
typeofRequire: 'undefined',
typeofProcess: 'undefined',
typeofArrayPush: 'number',
typeofFunctionApply: 'boolean',
typeofPreloadExecuteJavaScriptProperty: 'number',
typeofOpenedWindow: 'object'
}
})
})
})
describe('new-window event', () => {
it('emits when window.open is called', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/window-open.html`
})
const { url, frameName } = await waitForEvent(webview, 'new-window')
assert.strictEqual(url, 'http://host/')
assert.strictEqual(frameName, 'host')
})
it('emits when link with target is called', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/target-name.html`
})
const { url, frameName } = await waitForEvent(webview, 'new-window')
assert.strictEqual(url, 'http://host/')
assert.strictEqual(frameName, 'target')
})
})
describe('ipc-message event', () => {
it('emits when guest sends a ipc message to browser', async () => {
loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/ipc-message.html`
})
const { channel, args } = await waitForEvent(webview, 'ipc-message')
assert.strictEqual(channel, 'channel')
assert.deepStrictEqual(args, ['arg1', 'arg2'])
})
})
describe('page-title-set event', () => {
it('emits when title is set', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/a.html`
})
const { title, explicitSet } = await waitForEvent(webview, 'page-title-set')
assert.strictEqual(title, 'test')
assert(explicitSet)
})
})
describe('page-favicon-updated event', () => {
it('emits when favicon urls are received', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/a.html`
})
const { favicons } = await waitForEvent(webview, 'page-favicon-updated')
assert(favicons)
assert.strictEqual(favicons.length, 2)
if (process.platform === 'win32') {
assert(/^file:\/\/\/[A-Z]:\/favicon.png$/i.test(favicons[0]))
} else {
assert.strictEqual(favicons[0], 'file:///favicon.png')
}
})
})
describe('will-navigate event', () => {
it('emits when a url that leads to oustide of the page is clicked', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/webview-will-navigate.html`
})
const { url } = await waitForEvent(webview, 'will-navigate')
assert.strictEqual(url, 'http://host/')
})
})
describe('did-navigate event', () => {
let p = path.join(fixtures, 'pages', 'webview-will-navigate.html')
p = p.replace(/\\/g, '/')
const pageUrl = url.format({
protocol: 'file',
slashes: true,
pathname: p
})
it('emits when a url that leads to outside of the page is clicked', async () => {
loadWebView(webview, { src: pageUrl })
const { url } = await waitForEvent(webview, 'did-navigate')
assert.strictEqual(url, pageUrl)
})
})
describe('did-navigate-in-page event', () => {
it('emits when an anchor link is clicked', async () => {
let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html')
p = p.replace(/\\/g, '/')
const pageUrl = url.format({
protocol: 'file',
slashes: true,
pathname: p
})
loadWebView(webview, { src: pageUrl })
const event = await waitForEvent(webview, 'did-navigate-in-page')
assert.strictEqual(event.url, `${pageUrl}#test_content`)
})
it('emits when window.history.replaceState is called', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`
})
const { url } = await waitForEvent(webview, 'did-navigate-in-page')
assert.strictEqual(url, 'http://host/')
})
it('emits when window.location.hash is changed', async () => {
let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html')
p = p.replace(/\\/g, '/')
const pageUrl = url.format({
protocol: 'file',
slashes: true,
pathname: p
})
loadWebView(webview, { src: pageUrl })
const event = await waitForEvent(webview, 'did-navigate-in-page')
assert.strictEqual(event.url, `${pageUrl}#test`)
})
})
describe('close event', () => {
it('should fire when interior page calls window.close', async () => {
loadWebView(webview, { src: `file://${fixtures}/pages/close.html` })
await waitForEvent(webview, 'close')
})
})
// FIXME(zcbenz): Disabled because of moving to OOPIF webview.
xdescribe('setDevToolsWebContents() API', () => {
it('sets webContents of webview as devtools', async () => {
const webview2 = new WebView()
loadWebView(webview2)
// Setup an event handler for further usage.
const waitForDomReady = waitForEvent(webview2, 'dom-ready')
loadWebView(webview, { src: 'about:blank' })
await waitForEvent(webview, 'dom-ready')
webview.getWebContents().setDevToolsWebContents(webview2.getWebContents())
webview.getWebContents().openDevTools()
await waitForDomReady
// Its WebContents should be a DevTools.
const devtools = webview2.getWebContents()
assert.ok(devtools.getURL().startsWith('chrome-devtools://devtools'))
const name = await new Promise((resolve) => {
devtools.executeJavaScript('InspectorFrontendHost.constructor.name', (name) => {
resolve(name)
})
})
document.body.removeChild(webview2)
expect(name).to.be.equal('InspectorFrontendHostImpl')
})
})
describe('devtools-opened event', () => {
it('should fire when webview.openDevTools() is called', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/base-page.html`
})
await waitForEvent(webview, 'dom-ready')
webview.openDevTools()
await waitForEvent(webview, 'devtools-opened')
webview.closeDevTools()
})
})
describe('devtools-closed event', () => {
it('should fire when webview.closeDevTools() is called', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/base-page.html`
})
await waitForEvent(webview, 'dom-ready')
webview.openDevTools()
await waitForEvent(webview, 'devtools-opened')
webview.closeDevTools()
await waitForEvent(webview, 'devtools-closed')
})
})
describe('devtools-focused event', () => {
it('should fire when webview.openDevTools() is called', async () => {
loadWebView(webview, {
src: `file://${fixtures}/pages/base-page.html`
})
const waitForDevToolsFocused = waitForEvent(webview, 'devtools-focused')
await waitForEvent(webview, 'dom-ready')
webview.openDevTools()
await waitForDevToolsFocused
webview.closeDevTools()
})
})
describe('<webview>.reload()', () => {
it('should emit beforeunload handler', async () => {
await loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/beforeunload-false.html`
})
// Event handler has to be added before reload.
const waitForOnbeforeunload = waitForEvent(webview, 'ipc-message')
webview.reload()
const { channel } = await waitForOnbeforeunload
assert.strictEqual(channel, 'onbeforeunload')
})
})
describe('<webview>.goForward()', () => {
it('should work after a replaced history entry', (done) => {
let loadCount = 1
const listener = (e) => {
if (loadCount === 1) {
assert.strictEqual(e.channel, 'history')
assert.strictEqual(e.args[0], 1)
assert(!webview.canGoBack())
assert(!webview.canGoForward())
} else if (loadCount === 2) {
assert.strictEqual(e.channel, 'history')
assert.strictEqual(e.args[0], 2)
assert(!webview.canGoBack())
assert(webview.canGoForward())
webview.removeEventListener('ipc-message', listener)
}
}
const loadListener = () => {
if (loadCount === 1) {
webview.src = `file://${fixtures}/pages/base-page.html`
} else if (loadCount === 2) {
assert(webview.canGoBack())
assert(!webview.canGoForward())
webview.goBack()
} else if (loadCount === 3) {
webview.goForward()
} else if (loadCount === 4) {
assert(webview.canGoBack())
assert(!webview.canGoForward())
webview.removeEventListener('did-finish-load', loadListener)
done()
}
loadCount += 1
}
webview.addEventListener('ipc-message', listener)
webview.addEventListener('did-finish-load', loadListener)
loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/history-replace.html`
})
})
})
describe('<webview>.clearHistory()', () => {
it('should clear the navigation history', async () => {
loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/history.html`
})
const event = await waitForEvent(webview, 'ipc-message')
assert.strictEqual(event.channel, 'history')
assert.strictEqual(event.args[0], 2)
assert(webview.canGoBack())
webview.clearHistory()
assert(!webview.canGoBack())
})
})
describe('basic auth', () => {
const auth = require('basic-auth')
it('should authenticate with correct credentials', (done) => {
const message = 'Authenticated'
const server = http.createServer((req, res) => {
const credentials = auth(req)
if (credentials.name === 'test' && credentials.pass === 'test') {
res.end(message)
} else {
res.end('failed')
}
server.close()
})
server.listen(0, '127.0.0.1', () => {
const port = server.address().port
webview.addEventListener('ipc-message', (e) => {
assert.strictEqual(e.channel, message)
done()
})
loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/basic-auth.html?port=${port}`
})
})
})
})
describe('dom-ready event', () => {
it('emits when document is loaded', (done) => {
const server = http.createServer(() => {})
server.listen(0, '127.0.0.1', () => {
const port = server.address().port
webview.addEventListener('dom-ready', () => {
done()
})
loadWebView(webview, {
src: `file://${fixtures}/pages/dom-ready.html?port=${port}`
})
})
})
it('throws a custom error when an API method is called before the event is emitted', () => {
const expectedErrorMessage =
'The WebView must be attached to the DOM ' +
'and the dom-ready event emitted before this method can be called.'
expect(() => { webview.stop() }).to.throw(expectedErrorMessage)
})
})
describe('executeJavaScript', () => {
it('should support user gesture', async () => {
await loadWebView(webview, {
src: `file://${fixtures}/pages/fullscreen.html`
})
// Event handler has to be added before js execution.
const waitForEnterHtmlFullScreen = waitForEvent(webview, 'enter-html-full-screen')
const jsScript = "document.querySelector('video').webkitRequestFullscreen()"
webview.executeJavaScript(jsScript, true)
return waitForEnterHtmlFullScreen
})
it('can return the result of the executed script', async () => {
await loadWebView(webview, {
src: 'about:blank'
})
const jsScript = "'4'+2"
const expectedResult = '42'
const result = await new Promise((resolve) => {
webview.executeJavaScript(jsScript, false, (result) => {
resolve(result)
})
})
assert.strictEqual(result, expectedResult)
})
})
describe('sendInputEvent', () => {
it('can send keyboard event', async () => {
loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/onkeyup.html`
})
await waitForEvent(webview, 'dom-ready')
const waitForIpcMessage = waitForEvent(webview, 'ipc-message')
webview.sendInputEvent({
type: 'keyup',
keyCode: 'c',
modifiers: ['shift']
})
const { channel, args } = await waitForIpcMessage
assert.strictEqual(channel, 'keyup')
assert.deepStrictEqual(args, ['C', 'KeyC', 67, true, false])
})
it('can send mouse event', async () => {
loadWebView(webview, {
nodeintegration: 'on',
src: `file://${fixtures}/pages/onmouseup.html`