/
extensions-spec.ts
850 lines (741 loc) · 35.5 KB
/
extensions-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
import { expect } from 'chai';
import { app, session, BrowserWindow, ipcMain, WebContents, Extension } from 'electron';
import { closeAllWindows, closeWindow } from './window-helpers';
import * as http from 'http';
import { AddressInfo } from 'net';
import * as path from 'path';
import * as fs from 'fs';
import { ifdescribe } from './spec-helpers';
import { emittedOnce, emittedNTimes } from './events-helpers';
const fixtures = path.join(__dirname, 'fixtures');
ifdescribe(process.electronBinding('features').isExtensionsEnabled())('chrome extensions', () => {
// NB. extensions are only allowed on http://, https:// and ftp:// (!) urls by default.
let server: http.Server;
let url: string;
before(async () => {
server = http.createServer((req, res) => {
if (req.url === '/cors') {
res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
}
res.end();
});
await new Promise(resolve => server.listen(0, '127.0.0.1', () => {
url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
resolve();
}));
});
after(() => {
server.close();
});
afterEach(closeAllWindows);
afterEach(() => {
session.defaultSession.getAllExtensions().forEach((e: any) => {
session.defaultSession.removeExtension(e.id);
});
});
it('does not crash when using chrome.management', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
w.loadURL('about:blank');
await emittedOnce(w.webContents, 'dom-ready');
await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const args: any = await emittedOnce(app, 'web-contents-created');
const wc: Electron.WebContents = args[1];
await expect(wc.executeJavaScript(`
(() => {
return new Promise((resolve) => {
chrome.management.getSelf((info) => {
resolve(info);
});
})
})();
`)).to.eventually.have.property('id');
});
it('can open WebSQLDatabase in a background page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
w.loadURL('about:blank');
await emittedOnce(w.webContents, 'dom-ready');
await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const args: any = await emittedOnce(app, 'web-contents-created');
const wc: Electron.WebContents = args[1];
await expect(wc.executeJavaScript('(()=>{try{openDatabase("t", "1.0", "test", 2e5);return true;}catch(e){throw e}})()')).to.not.be.rejected();
});
function fetch (contents: WebContents, url: string) {
return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
}
it('bypasses CORS in requests made from extensions', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
w.loadURL(`${extension.url}bare-page.html`);
await emittedOnce(w.webContents, 'dom-ready');
await expect(fetch(w.webContents, `${url}/cors`)).to.not.be.rejectedWith(TypeError);
});
it('loads an extension', async () => {
// NB. we have to use a persist: session (i.e. non-OTR) because the
// extension registry is redirected to the main session. so installing an
// extension in an in-memory session results in it being installed in the
// default session.
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('red');
});
it('serializes a loaded extension', async () => {
const extensionPath = path.join(fixtures, 'extensions', 'red-bg');
const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8'));
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const extension = await customSession.loadExtension(extensionPath);
expect(extension.id).to.be.a('string');
expect(extension.name).to.be.a('string');
expect(extension.path).to.be.a('string');
expect(extension.version).to.be.a('string');
expect(extension.url).to.be.a('string');
expect(extension.manifest).to.deep.equal(manifest);
});
it('removes an extension', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
{
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('red');
}
customSession.removeExtension(id);
{
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('');
}
});
it('lists loaded extensions in getAllExtensions', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
expect(customSession.getAllExtensions()).to.deep.equal([e]);
customSession.removeExtension(e.id);
expect(customSession.getAllExtensions()).to.deep.equal([]);
});
it('gets an extension by id', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
expect(customSession.getExtension(e.id)).to.deep.equal(e);
});
it('confines an extension to the session it was loaded in', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
const w = new BrowserWindow({ show: false }); // not in the session
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('');
});
it('loading an extension in a temporary session throws an error', async () => {
const customSession = session.fromPartition(require('uuid').v4());
await expect(customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'))).to.eventually.be.rejectedWith('Extensions cannot be loaded in a temporary session');
});
describe('chrome.i18n', () => {
let w: BrowserWindow;
let extension: Extension;
const exec = async (name: string) => {
const p = emittedOnce(ipcMain, 'success');
await w.webContents.executeJavaScript(`exec('${name}')`);
const [, result] = await p;
return result;
};
beforeEach(async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n'));
w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
});
it('getAcceptLanguages()', async () => {
const result = await exec('getAcceptLanguages');
expect(result).to.be.an('array').and.deep.equal(['en-US']);
});
it('getMessage()', async () => {
const result = await exec('getMessage');
expect(result.id).to.be.a('string').and.equal(extension.id);
expect(result.name).to.be.a('string').and.equal('chrome-i18n');
});
});
describe('chrome.runtime', () => {
let content: any;
before(async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-runtime'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
try {
await w.loadURL(url);
content = JSON.parse(await w.webContents.executeJavaScript('document.documentElement.textContent'));
expect(content).to.be.an('object');
} finally {
w.destroy();
}
});
it('getManifest()', () => {
expect(content.manifest).to.be.an('object').with.property('name', 'chrome-runtime');
});
it('id', () => {
expect(content.id).to.be.a('string').with.lengthOf(32);
});
it('getURL()', () => {
expect(content.url).to.be.a('string').and.match(/^chrome-extension:\/\/.*main.js$/);
});
});
describe('chrome.storage', () => {
it('stores and retrieves a key', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-storage'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
try {
const p = emittedOnce(ipcMain, 'storage-success');
await w.loadURL(url);
const [, v] = await p;
expect(v).to.equal('value');
} finally {
w.destroy();
}
});
});
describe('chrome.tabs', () => {
it('executeScript', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
const message = { method: 'executeScript', args: ['1 + 2'] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.equal(3);
});
it('connect', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
const portName = require('uuid').v4();
const message = { method: 'connectTab', args: [portName] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
const response = responseString.split(',');
expect(response[0]).to.equal(portName);
expect(response[1]).to.equal('howdy');
});
it('sendMessage receives the response', async function () {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
const message = { method: 'sendMessage', args: ['Hello World!'] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response.message).to.equal('Hello World!');
expect(response.tabId).to.equal(w.webContents.id);
});
});
describe('background pages', () => {
it('loads a lazy background page when sending a message', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
try {
w.loadURL(url);
const [, resp] = await emittedOnce(ipcMain, 'bg-page-message-response');
expect(resp.message).to.deep.equal({ some: 'message' });
expect(resp.sender.id).to.be.a('string');
expect(resp.sender.origin).to.equal(url);
expect(resp.sender.url).to.equal(url + '/');
} finally {
w.destroy();
}
});
it('can use extension.getBackgroundPage from a ui page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
expect(receivedMessage).to.deep.equal({ some: 'message' });
});
it('can use extension.getBackgroundPage from a ui page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
expect(receivedMessage).to.deep.equal({ some: 'message' });
});
it('can use runtime.getBackgroundPage from a ui page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`);
const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
expect(receivedMessage).to.deep.equal({ some: 'message' });
});
it('has session in background page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
const promise = emittedOnce(app, 'web-contents-created');
await w.loadURL('about:blank');
const [, bgPageContents] = await promise;
expect(bgPageContents.session).to.not.equal(undefined);
});
it('can open devtools of background page', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
const promise = emittedOnce(app, 'web-contents-created');
await w.loadURL('about:blank');
const [, bgPageContents] = await promise;
expect(bgPageContents.getType()).to.equal('backgroundPage');
bgPageContents.openDevTools();
bgPageContents.closeDevTools();
});
});
describe('devtools extensions', () => {
let showPanelTimeoutId: any = null;
afterEach(() => {
if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId);
});
const showLastDevToolsPanel = (w: BrowserWindow) => {
w.webContents.once('devtools-opened', () => {
const show = () => {
if (w == null || w.isDestroyed()) return;
const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined };
if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
return;
}
const showLastPanel = () => {
// this is executed in the devtools context, where UI is a global
const { UI } = (window as any);
const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id;
UI.inspectorView.showPanel(lastPanelId);
};
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
showPanelTimeoutId = setTimeout(show, 100);
});
};
showPanelTimeoutId = setTimeout(show, 100);
});
};
it('loads a devtools extension', async () => {
const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension'));
const winningMessage = emittedOnce(ipcMain, 'winning');
const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true } });
await w.loadURL(url);
w.webContents.openDevTools();
showLastDevToolsPanel(w);
await winningMessage;
});
});
describe('deprecation shims', () => {
it('loads an extension through BrowserWindow.addExtension', async () => {
BrowserWindow.addExtension(path.join(fixtures, 'extensions', 'red-bg'));
const w = new BrowserWindow({ show: false });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('red');
});
it('loads an extension through BrowserWindow.addDevToolsExtension', async () => {
BrowserWindow.addDevToolsExtension(path.join(fixtures, 'extensions', 'red-bg'));
const w = new BrowserWindow({ show: false });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('red');
});
it('removes an extension through BrowserWindow.removeExtension', async () => {
await (BrowserWindow.addExtension(path.join(fixtures, 'extensions', 'red-bg')) as any);
BrowserWindow.removeExtension('red-bg');
const w = new BrowserWindow({ show: false });
await w.loadURL(url);
const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(bg).to.equal('');
});
});
describe('chrome extension content scripts', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
const extensionPath = path.resolve(fixtures, 'extensions');
const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name));
const removeAllExtensions = () => {
Object.keys(session.defaultSession.getAllExtensions()).map(extName => {
session.defaultSession.removeExtension(extName);
});
};
let responseIdCounter = 0;
const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => {
return new Promise(resolve => {
const responseId = responseIdCounter++;
ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => {
resolve(result);
});
webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId);
});
};
const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => {
describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => {
let w: BrowserWindow;
describe('supports "run_at" option', () => {
beforeEach(async () => {
await closeWindow(w);
w = new BrowserWindow({
show: false,
width: 400,
height: 400,
webPreferences: {
contextIsolation: contextIsolationEnabled,
sandbox: sandboxEnabled
}
});
});
afterEach(() => {
removeAllExtensions();
return closeWindow(w).then(() => { w = null as unknown as BrowserWindow; });
});
it('should run content script at document_start', async () => {
await addExtension('content-script-document-start');
w.webContents.once('dom-ready', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(result).to.equal('red');
});
w.loadURL(url);
});
it('should run content script at document_idle', async () => {
await addExtension('content-script-document-idle');
w.loadURL(url);
const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor');
expect(result).to.equal('red');
});
it('should run content script at document_end', async () => {
await addExtension('content-script-document-end');
w.webContents.once('did-finish-load', async () => {
const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
expect(result).to.equal('red');
});
w.loadURL(url);
});
});
// TODO(nornagon): real extensions don't load on file: urls, so this
// test needs to be updated to serve its content over http.
describe.skip('supports "all_frames" option', () => {
const contentScript = path.resolve(fixtures, 'extensions/content-script');
// Computed style values
const COLOR_RED = 'rgb(255, 0, 0)';
const COLOR_BLUE = 'rgb(0, 0, 255)';
const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)';
before(() => {
BrowserWindow.addExtension(contentScript);
});
after(() => {
BrowserWindow.removeExtension('content-script-test');
});
beforeEach(() => {
w = new BrowserWindow({
show: false,
webPreferences: {
// enable content script injection in subframes
nodeIntegrationInSubFrames: true,
preload: path.join(contentScript, 'all_frames-preload.js')
}
});
});
afterEach(() =>
closeWindow(w).then(() => {
w = null as unknown as BrowserWindow;
})
);
it('applies matching rules in subframes', async () => {
const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2);
w.loadFile(path.join(contentScript, 'frame-with-frame.html'));
const frameEvents = await detailsPromise;
await Promise.all(
frameEvents.map(async frameEvent => {
const [, isMainFrame, , frameRoutingId] = frameEvent;
const result: any = await executeJavaScriptInFrame(
w.webContents,
frameRoutingId,
`(() => {
const a = document.getElementById('all_frames_enabled')
const b = document.getElementById('all_frames_disabled')
return {
enabledColor: getComputedStyle(a).backgroundColor,
disabledColor: getComputedStyle(b).backgroundColor
}
})()`
);
expect(result.enabledColor).to.equal(COLOR_RED);
if (isMainFrame) {
expect(result.disabledColor).to.equal(COLOR_BLUE);
} else {
expect(result.disabledColor).to.equal(COLOR_TRANSPARENT); // null color
}
})
);
});
});
});
};
generateTests(false, false);
generateTests(false, true);
generateTests(true, false);
generateTests(true, true);
});
describe('extension ui pages', () => {
afterEach(() => {
session.defaultSession.getAllExtensions().forEach(e => {
session.defaultSession.removeExtension(e.id);
});
});
it('loads a ui page of an extension', async () => {
const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
const w = new BrowserWindow({ show: false });
await w.loadURL(`chrome-extension://${id}/bare-page.html`);
const textContent = await w.webContents.executeJavaScript('document.body.textContent');
expect(textContent).to.equal('ui page loaded ok\n');
});
it('can load resources', async () => {
const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
const w = new BrowserWindow({ show: false });
await w.loadURL(`chrome-extension://${id}/page-script-load.html`);
const textContent = await w.webContents.executeJavaScript('document.body.textContent');
expect(textContent).to.equal('script loaded ok\n');
});
});
});
ifdescribe(!process.electronBinding('features').isExtensionsEnabled())('chrome extensions', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
let w: BrowserWindow;
before(() => {
BrowserWindow.addExtension(path.join(fixtures, 'extensions/chrome-api'));
});
after(() => {
BrowserWindow.removeExtension('chrome-api');
});
beforeEach(() => {
w = new BrowserWindow({ show: false });
});
afterEach(() => closeWindow(w).then(() => { w = null as unknown as BrowserWindow; }));
it('chrome.runtime.connect parses arguments properly', async function () {
await w.loadURL('about:blank');
const promise = emittedOnce(w.webContents, 'console-message');
const message = { method: 'connect' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await promise;
const response = JSON.parse(responseString);
expect(response).to.be.true();
});
it('runtime.getManifest returns extension manifest', async () => {
const actualManifest = (() => {
const data = fs.readFileSync(path.join(fixtures, 'extensions/chrome-api/manifest.json'), 'utf-8');
return JSON.parse(data);
})();
await w.loadURL('about:blank');
const promise = emittedOnce(w.webContents, 'console-message');
const message = { method: 'getManifest' };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, manifestString] = await promise;
const manifest = JSON.parse(manifestString);
expect(manifest.name).to.equal(actualManifest.name);
expect(manifest.content_scripts).to.have.lengthOf(actualManifest.content_scripts.length);
});
it('chrome.tabs.sendMessage receives the response', async function () {
await w.loadURL('about:blank');
const promise = emittedOnce(w.webContents, 'console-message');
const message = { method: 'sendMessage', args: ['Hello World!'] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await promise;
const response = JSON.parse(responseString);
expect(response.message).to.equal('Hello World!');
expect(response.tabId).to.equal(w.webContents.id);
});
it('chrome.tabs.executeScript receives the response', async function () {
await w.loadURL('about:blank');
const promise = emittedOnce(w.webContents, 'console-message');
const message = { method: 'executeScript', args: ['1 + 2'] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
const [,, responseString] = await promise;
const response = JSON.parse(responseString);
expect(response).to.equal(3);
});
describe('extensions and dev tools extensions', () => {
let showPanelTimeoutId: NodeJS.Timeout | null = null;
const showLastDevToolsPanel = (w: BrowserWindow) => {
w.webContents.once('devtools-opened', () => {
const show = () => {
if (w == null || w.isDestroyed()) return;
const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined };
if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
return;
}
const showLastPanel = () => {
// this is executed in the devtools context, where UI is a global
const { UI } = (window as any);
const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id;
UI.inspectorView.showPanel(lastPanelId);
};
devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
showPanelTimeoutId = setTimeout(show, 100);
});
};
showPanelTimeoutId = setTimeout(show, 100);
});
};
afterEach(() => {
if (showPanelTimeoutId != null) {
clearTimeout(showPanelTimeoutId);
showPanelTimeoutId = null;
}
});
describe('BrowserWindow.addDevToolsExtension', () => {
describe('for invalid extensions', () => {
it('throws errors for missing manifest.json files', () => {
const nonexistentExtensionPath = path.join(__dirname, 'does-not-exist');
expect(() => {
BrowserWindow.addDevToolsExtension(nonexistentExtensionPath);
}).to.throw(/ENOENT: no such file or directory/);
});
it('throws errors for invalid manifest.json files', () => {
const badManifestExtensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest');
expect(() => {
BrowserWindow.addDevToolsExtension(badManifestExtensionPath);
}).to.throw(/Unexpected token }/);
});
});
describe('for a valid extension', () => {
const extensionName = 'foo';
before(() => {
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
BrowserWindow.addDevToolsExtension(extensionPath);
expect(BrowserWindow.getDevToolsExtensions()).to.have.property(extensionName);
});
after(() => {
BrowserWindow.removeDevToolsExtension('foo');
expect(BrowserWindow.getDevToolsExtensions()).to.not.have.property(extensionName);
});
describe('when the devtools is docked', () => {
let message: any;
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
const p = new Promise(resolve => ipcMain.once('answer', (event, message) => {
resolve(message);
}));
showLastDevToolsPanel(w);
w.loadURL('about:blank');
w.webContents.openDevTools({ mode: 'bottom' });
message = await p;
});
after(closeAllWindows);
describe('created extension info', function () {
it('has proper "runtimeId"', async function () {
expect(message).to.have.ownProperty('runtimeId');
expect(message.runtimeId).to.equal(extensionName);
});
it('has "tabId" matching webContents id', function () {
expect(message).to.have.ownProperty('tabId');
expect(message.tabId).to.equal(w.webContents.id);
});
it('has "i18nString" with proper contents', function () {
expect(message).to.have.ownProperty('i18nString');
expect(message.i18nString).to.equal('foo - bar (baz)');
});
it('has "storageItems" with proper contents', function () {
expect(message).to.have.ownProperty('storageItems');
expect(message.storageItems).to.deep.equal({
local: {
set: { hello: 'world', world: 'hello' },
remove: { world: 'hello' },
clear: {}
},
sync: {
set: { foo: 'bar', bar: 'foo' },
remove: { foo: 'bar' },
clear: {}
}
});
});
});
});
describe('when the devtools is undocked', () => {
let message: any;
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } });
showLastDevToolsPanel(w);
w.loadURL('about:blank');
w.webContents.openDevTools({ mode: 'undocked' });
message = await new Promise(resolve => ipcMain.once('answer', (event, message) => {
resolve(message);
}));
});
after(closeAllWindows);
describe('created extension info', function () {
it('has proper "runtimeId"', function () {
expect(message).to.have.ownProperty('runtimeId');
expect(message.runtimeId).to.equal(extensionName);
});
it('has "tabId" matching webContents id', function () {
expect(message).to.have.ownProperty('tabId');
expect(message.tabId).to.equal(w.webContents.id);
});
});
});
});
});
it('works when used with partitions', async () => {
const w = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: true,
partition: 'temp'
}
});
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
BrowserWindow.addDevToolsExtension(extensionPath);
try {
showLastDevToolsPanel(w);
const p: Promise<any> = new Promise(resolve => ipcMain.once('answer', function (event, message) {
resolve(message);
}));
w.loadURL('about:blank');
w.webContents.openDevTools({ mode: 'bottom' });
const message = await p;
expect(message.runtimeId).to.equal('foo');
} finally {
BrowserWindow.removeDevToolsExtension('foo');
await closeAllWindows();
}
});
it('serializes the registered extensions on quit', () => {
const extensionName = 'foo';
const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', extensionName);
const serializedPath = path.join(app.getPath('userData'), 'DevTools Extensions');
BrowserWindow.addDevToolsExtension(extensionPath);
app.emit('will-quit');
expect(JSON.parse(fs.readFileSync(serializedPath, 'utf8'))).to.deep.equal([extensionPath]);
BrowserWindow.removeDevToolsExtension(extensionName);
app.emit('will-quit');
expect(fs.existsSync(serializedPath)).to.be.false('file exists');
});
describe('BrowserWindow.addExtension', () => {
it('throws errors for missing manifest.json files', () => {
expect(() => {
BrowserWindow.addExtension(path.join(__dirname, 'does-not-exist'));
}).to.throw('ENOENT: no such file or directory');
});
it('throws errors for invalid manifest.json files', () => {
expect(() => {
BrowserWindow.addExtension(path.join(__dirname, 'fixtures', 'devtools-extensions', 'bad-manifest'));
}).to.throw('Unexpected token }');
});
});
});
});