extensions-spec.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import { expect } from 'chai';
  2. import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main';
  3. import { closeAllWindows, closeWindow } from './window-helpers';
  4. import * as http from 'http';
  5. import { AddressInfo } from 'net';
  6. import * as path from 'path';
  7. import * as fs from 'fs';
  8. import * as WebSocket from 'ws';
  9. import { emittedOnce, emittedNTimes, emittedUntil } from './events-helpers';
  10. const uuid = require('uuid');
  11. const fixtures = path.join(__dirname, 'fixtures');
  12. describe('chrome extensions', () => {
  13. const emptyPage = '<script>console.log("loaded")</script>';
  14. // NB. extensions are only allowed on http://, https:// and ftp:// (!) urls by default.
  15. let server: http.Server;
  16. let url: string;
  17. let port: string;
  18. before(async () => {
  19. server = http.createServer((req, res) => {
  20. if (req.url === '/cors') {
  21. res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
  22. }
  23. res.end(emptyPage);
  24. });
  25. const wss = new WebSocket.Server({ noServer: true });
  26. wss.on('connection', function connection (ws) {
  27. ws.on('message', function incoming (message) {
  28. if (message === 'foo') {
  29. ws.send('bar');
  30. }
  31. });
  32. });
  33. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => {
  34. port = String((server.address() as AddressInfo).port);
  35. url = `http://127.0.0.1:${port}`;
  36. resolve();
  37. }));
  38. });
  39. after(() => {
  40. server.close();
  41. });
  42. afterEach(closeAllWindows);
  43. afterEach(() => {
  44. session.defaultSession.getAllExtensions().forEach((e: any) => {
  45. session.defaultSession.removeExtension(e.id);
  46. });
  47. });
  48. it('does not crash when using chrome.management', async () => {
  49. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  50. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  51. await w.loadURL('about:blank');
  52. const promise = emittedOnce(app, 'web-contents-created');
  53. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  54. const args: any = await promise;
  55. const wc: Electron.WebContents = args[1];
  56. await expect(wc.executeJavaScript(`
  57. (() => {
  58. return new Promise((resolve) => {
  59. chrome.management.getSelf((info) => {
  60. resolve(info);
  61. });
  62. })
  63. })();
  64. `)).to.eventually.have.property('id');
  65. });
  66. it('can open WebSQLDatabase in a background page', async () => {
  67. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  68. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  69. await w.loadURL('about:blank');
  70. const promise = emittedOnce(app, 'web-contents-created');
  71. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  72. const args: any = await promise;
  73. const wc: Electron.WebContents = args[1];
  74. await expect(wc.executeJavaScript('(()=>{try{openDatabase("t", "1.0", "test", 2e5);return true;}catch(e){throw e}})()')).to.not.be.rejected();
  75. });
  76. function fetch (contents: WebContents, url: string) {
  77. return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
  78. }
  79. it('bypasses CORS in requests made from extensions', async () => {
  80. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  81. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  82. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  83. await w.loadURL(`${extension.url}bare-page.html`);
  84. await expect(fetch(w.webContents, `${url}/cors`)).to.not.be.rejectedWith(TypeError);
  85. });
  86. it('loads an extension', async () => {
  87. // NB. we have to use a persist: session (i.e. non-OTR) because the
  88. // extension registry is redirected to the main session. so installing an
  89. // extension in an in-memory session results in it being installed in the
  90. // default session.
  91. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  92. await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  93. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  94. await w.loadURL(url);
  95. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  96. expect(bg).to.equal('red');
  97. });
  98. it('does not crash when failing to load an extension', async () => {
  99. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  100. const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'load-error'));
  101. await expect(promise).to.eventually.be.rejected();
  102. });
  103. it('serializes a loaded extension', async () => {
  104. const extensionPath = path.join(fixtures, 'extensions', 'red-bg');
  105. const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8'));
  106. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  107. const extension = await customSession.loadExtension(extensionPath);
  108. expect(extension.id).to.be.a('string');
  109. expect(extension.name).to.be.a('string');
  110. expect(extension.path).to.be.a('string');
  111. expect(extension.version).to.be.a('string');
  112. expect(extension.url).to.be.a('string');
  113. expect(extension.manifest).to.deep.equal(manifest);
  114. });
  115. it('removes an extension', async () => {
  116. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  117. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  118. {
  119. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  120. await w.loadURL(url);
  121. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  122. expect(bg).to.equal('red');
  123. }
  124. customSession.removeExtension(id);
  125. {
  126. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  127. await w.loadURL(url);
  128. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  129. expect(bg).to.equal('');
  130. }
  131. });
  132. it('emits extension lifecycle events', async () => {
  133. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  134. const loadedPromise = emittedOnce(customSession, 'extension-loaded');
  135. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  136. const [, loadedExtension] = await loadedPromise;
  137. const [, readyExtension] = await emittedUntil(customSession, 'extension-ready', (event: Event, extension: Extension) => {
  138. return extension.name !== 'Chromium PDF Viewer' && extension.name !== 'CryptoTokenExtension';
  139. });
  140. expect(loadedExtension).to.deep.equal(extension);
  141. expect(readyExtension).to.deep.equal(extension);
  142. const unloadedPromise = emittedOnce(customSession, 'extension-unloaded');
  143. await customSession.removeExtension(extension.id);
  144. const [, unloadedExtension] = await unloadedPromise;
  145. expect(unloadedExtension).to.deep.equal(extension);
  146. });
  147. it('lists loaded extensions in getAllExtensions', async () => {
  148. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  149. const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  150. expect(customSession.getAllExtensions()).to.deep.equal([e]);
  151. customSession.removeExtension(e.id);
  152. expect(customSession.getAllExtensions()).to.deep.equal([]);
  153. });
  154. it('gets an extension by id', async () => {
  155. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  156. const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  157. expect(customSession.getExtension(e.id)).to.deep.equal(e);
  158. });
  159. it('confines an extension to the session it was loaded in', async () => {
  160. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  161. await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  162. const w = new BrowserWindow({ show: false }); // not in the session
  163. await w.loadURL(url);
  164. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  165. expect(bg).to.equal('');
  166. });
  167. it('loading an extension in a temporary session throws an error', async () => {
  168. const customSession = session.fromPartition(uuid.v4());
  169. await expect(customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'))).to.eventually.be.rejectedWith('Extensions cannot be loaded in a temporary session');
  170. });
  171. describe('chrome.i18n', () => {
  172. let w: BrowserWindow;
  173. let extension: Extension;
  174. const exec = async (name: string) => {
  175. const p = emittedOnce(ipcMain, 'success');
  176. await w.webContents.executeJavaScript(`exec('${name}')`);
  177. const [, result] = await p;
  178. return result;
  179. };
  180. beforeEach(async () => {
  181. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  182. extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n'));
  183. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  184. await w.loadURL(url);
  185. });
  186. it('getAcceptLanguages()', async () => {
  187. const result = await exec('getAcceptLanguages');
  188. expect(result).to.be.an('array').and.deep.equal(['en-US']);
  189. });
  190. it('getMessage()', async () => {
  191. const result = await exec('getMessage');
  192. expect(result.id).to.be.a('string').and.equal(extension.id);
  193. expect(result.name).to.be.a('string').and.equal('chrome-i18n');
  194. });
  195. });
  196. describe('chrome.runtime', () => {
  197. let w: BrowserWindow;
  198. const exec = async (name: string) => {
  199. const p = emittedOnce(ipcMain, 'success');
  200. await w.webContents.executeJavaScript(`exec('${name}')`);
  201. const [, result] = await p;
  202. return result;
  203. };
  204. beforeEach(async () => {
  205. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  206. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-runtime'));
  207. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  208. await w.loadURL(url);
  209. });
  210. it('getManifest()', async () => {
  211. const result = await exec('getManifest');
  212. expect(result).to.be.an('object').with.property('name', 'chrome-runtime');
  213. });
  214. it('id', async () => {
  215. const result = await exec('id');
  216. expect(result).to.be.a('string').with.lengthOf(32);
  217. });
  218. it('getURL()', async () => {
  219. const result = await exec('getURL');
  220. expect(result).to.be.a('string').and.match(/^chrome-extension:\/\/.*main.js$/);
  221. });
  222. it('getPlatformInfo()', async () => {
  223. const result = await exec('getPlatformInfo');
  224. expect(result).to.be.an('object');
  225. expect(result.os).to.be.a('string');
  226. expect(result.arch).to.be.a('string');
  227. expect(result.nacl_arch).to.be.a('string');
  228. });
  229. });
  230. describe('chrome.storage', () => {
  231. it('stores and retrieves a key', async () => {
  232. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  233. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-storage'));
  234. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  235. try {
  236. const p = emittedOnce(ipcMain, 'storage-success');
  237. await w.loadURL(url);
  238. const [, v] = await p;
  239. expect(v).to.equal('value');
  240. } finally {
  241. w.destroy();
  242. }
  243. });
  244. });
  245. describe('chrome.webRequest', () => {
  246. function fetch (contents: WebContents, url: string) {
  247. return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
  248. }
  249. let customSession: Session;
  250. let w: BrowserWindow;
  251. beforeEach(() => {
  252. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  253. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true, contextIsolation: true } });
  254. });
  255. describe('onBeforeRequest', () => {
  256. it('can cancel http requests', async () => {
  257. await w.loadURL(url);
  258. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
  259. await expect(fetch(w.webContents, url)).to.eventually.be.rejectedWith('Failed to fetch');
  260. });
  261. it('does not cancel http requests when no extension loaded', async () => {
  262. await w.loadURL(url);
  263. await expect(fetch(w.webContents, url)).to.not.be.rejectedWith('Failed to fetch');
  264. });
  265. });
  266. it('does not take precedence over Electron webRequest - http', async () => {
  267. return new Promise<void>((resolve) => {
  268. (async () => {
  269. customSession.webRequest.onBeforeRequest((details, callback) => {
  270. resolve();
  271. callback({ cancel: true });
  272. });
  273. await w.loadURL(url);
  274. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
  275. fetch(w.webContents, url);
  276. })();
  277. });
  278. });
  279. it('does not take precedence over Electron webRequest - WebSocket', () => {
  280. return new Promise<void>((resolve) => {
  281. (async () => {
  282. customSession.webRequest.onBeforeSendHeaders(() => {
  283. resolve();
  284. });
  285. await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port } });
  286. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
  287. })();
  288. });
  289. });
  290. describe('WebSocket', () => {
  291. it('can be proxied', async () => {
  292. await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port } });
  293. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
  294. customSession.webRequest.onSendHeaders((details) => {
  295. if (details.url.startsWith('ws://')) {
  296. expect(details.requestHeaders.foo).be.equal('bar');
  297. }
  298. });
  299. });
  300. });
  301. });
  302. describe('chrome.tabs', () => {
  303. let customSession: Session;
  304. before(async () => {
  305. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  306. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  307. });
  308. it('executeScript', async () => {
  309. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  310. await w.loadURL(url);
  311. const message = { method: 'executeScript', args: ['1 + 2'] };
  312. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  313. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  314. const response = JSON.parse(responseString);
  315. expect(response).to.equal(3);
  316. });
  317. it('connect', async () => {
  318. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  319. await w.loadURL(url);
  320. const portName = uuid.v4();
  321. const message = { method: 'connectTab', args: [portName] };
  322. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  323. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  324. const response = responseString.split(',');
  325. expect(response[0]).to.equal(portName);
  326. expect(response[1]).to.equal('howdy');
  327. });
  328. it('sendMessage receives the response', async () => {
  329. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  330. await w.loadURL(url);
  331. const message = { method: 'sendMessage', args: ['Hello World!'] };
  332. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  333. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  334. const response = JSON.parse(responseString);
  335. expect(response.message).to.equal('Hello World!');
  336. expect(response.tabId).to.equal(w.webContents.id);
  337. });
  338. it('update', async () => {
  339. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  340. await w.loadURL(url);
  341. const w2 = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  342. await w2.loadURL('about:blank');
  343. const w2Navigated = emittedOnce(w2.webContents, 'did-navigate');
  344. const message = { method: 'update', args: [w2.webContents.id, { url }] };
  345. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  346. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  347. const response = JSON.parse(responseString);
  348. await w2Navigated;
  349. expect(new URL(w2.getURL()).toString()).to.equal(new URL(url).toString());
  350. expect(response.id).to.equal(w2.webContents.id);
  351. });
  352. });
  353. describe('background pages', () => {
  354. it('loads a lazy background page when sending a message', async () => {
  355. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  356. await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  357. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  358. try {
  359. w.loadURL(url);
  360. const [, resp] = await emittedOnce(ipcMain, 'bg-page-message-response');
  361. expect(resp.message).to.deep.equal({ some: 'message' });
  362. expect(resp.sender.id).to.be.a('string');
  363. expect(resp.sender.origin).to.equal(url);
  364. expect(resp.sender.url).to.equal(url + '/');
  365. } finally {
  366. w.destroy();
  367. }
  368. });
  369. it('can use extension.getBackgroundPage from a ui page', async () => {
  370. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  371. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  372. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  373. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  374. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  375. expect(receivedMessage).to.deep.equal({ some: 'message' });
  376. });
  377. it('can use extension.getBackgroundPage from a ui page', async () => {
  378. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  379. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  380. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  381. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  382. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  383. expect(receivedMessage).to.deep.equal({ some: 'message' });
  384. });
  385. it('can use runtime.getBackgroundPage from a ui page', async () => {
  386. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  387. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  388. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  389. await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`);
  390. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  391. expect(receivedMessage).to.deep.equal({ some: 'message' });
  392. });
  393. it('has session in background page', async () => {
  394. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  395. const promise = emittedOnce(app, 'web-contents-created');
  396. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  397. const [, bgPageContents] = await promise;
  398. expect(bgPageContents.getType()).to.equal('backgroundPage');
  399. await emittedOnce(bgPageContents, 'did-finish-load');
  400. expect(bgPageContents.getURL()).to.equal(`chrome-extension://${id}/_generated_background_page.html`);
  401. expect(bgPageContents.session).to.not.equal(undefined);
  402. });
  403. it('can open devtools of background page', async () => {
  404. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  405. const promise = emittedOnce(app, 'web-contents-created');
  406. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  407. const [, bgPageContents] = await promise;
  408. expect(bgPageContents.getType()).to.equal('backgroundPage');
  409. bgPageContents.openDevTools();
  410. bgPageContents.closeDevTools();
  411. });
  412. });
  413. describe('devtools extensions', () => {
  414. let showPanelTimeoutId: any = null;
  415. afterEach(() => {
  416. if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId);
  417. });
  418. const showLastDevToolsPanel = (w: BrowserWindow) => {
  419. w.webContents.once('devtools-opened', () => {
  420. const show = () => {
  421. if (w == null || w.isDestroyed()) return;
  422. const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined };
  423. if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
  424. return;
  425. }
  426. const showLastPanel = () => {
  427. // this is executed in the devtools context, where UI is a global
  428. const { UI } = (window as any);
  429. const tabs = UI.inspectorView.tabbedPane.tabs;
  430. const lastPanelId = tabs[tabs.length - 1].id;
  431. UI.inspectorView.showPanel(lastPanelId);
  432. };
  433. devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
  434. showPanelTimeoutId = setTimeout(show, 100);
  435. });
  436. };
  437. showPanelTimeoutId = setTimeout(show, 100);
  438. });
  439. };
  440. it('loads a devtools extension', async () => {
  441. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  442. customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension'));
  443. const winningMessage = emittedOnce(ipcMain, 'winning');
  444. const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  445. await w.loadURL(url);
  446. w.webContents.openDevTools();
  447. showLastDevToolsPanel(w);
  448. await winningMessage;
  449. });
  450. });
  451. describe('chrome extension content scripts', () => {
  452. const fixtures = path.resolve(__dirname, 'fixtures');
  453. const extensionPath = path.resolve(fixtures, 'extensions');
  454. const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name));
  455. const removeAllExtensions = () => {
  456. Object.keys(session.defaultSession.getAllExtensions()).map(extName => {
  457. session.defaultSession.removeExtension(extName);
  458. });
  459. };
  460. let responseIdCounter = 0;
  461. const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => {
  462. return new Promise(resolve => {
  463. const responseId = responseIdCounter++;
  464. ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => {
  465. resolve(result);
  466. });
  467. webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId);
  468. });
  469. };
  470. const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => {
  471. describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => {
  472. let w: BrowserWindow;
  473. describe('supports "run_at" option', () => {
  474. beforeEach(async () => {
  475. await closeWindow(w);
  476. w = new BrowserWindow({
  477. show: false,
  478. width: 400,
  479. height: 400,
  480. webPreferences: {
  481. contextIsolation: contextIsolationEnabled,
  482. sandbox: sandboxEnabled
  483. }
  484. });
  485. });
  486. afterEach(() => {
  487. removeAllExtensions();
  488. return closeWindow(w).then(() => { w = null as unknown as BrowserWindow; });
  489. });
  490. it('should run content script at document_start', async () => {
  491. await addExtension('content-script-document-start');
  492. w.webContents.once('dom-ready', async () => {
  493. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  494. expect(result).to.equal('red');
  495. });
  496. w.loadURL(url);
  497. });
  498. it('should run content script at document_idle', async () => {
  499. await addExtension('content-script-document-idle');
  500. w.loadURL(url);
  501. const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor');
  502. expect(result).to.equal('red');
  503. });
  504. it('should run content script at document_end', async () => {
  505. await addExtension('content-script-document-end');
  506. w.webContents.once('did-finish-load', async () => {
  507. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  508. expect(result).to.equal('red');
  509. });
  510. w.loadURL(url);
  511. });
  512. });
  513. // TODO(nornagon): real extensions don't load on file: urls, so this
  514. // test needs to be updated to serve its content over http.
  515. describe.skip('supports "all_frames" option', () => {
  516. const contentScript = path.resolve(fixtures, 'extensions/content-script');
  517. // Computed style values
  518. const COLOR_RED = 'rgb(255, 0, 0)';
  519. const COLOR_BLUE = 'rgb(0, 0, 255)';
  520. const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)';
  521. before(() => {
  522. session.defaultSession.loadExtension(contentScript);
  523. });
  524. after(() => {
  525. session.defaultSession.removeExtension('content-script-test');
  526. });
  527. beforeEach(() => {
  528. w = new BrowserWindow({
  529. show: false,
  530. webPreferences: {
  531. // enable content script injection in subframes
  532. nodeIntegrationInSubFrames: true,
  533. preload: path.join(contentScript, 'all_frames-preload.js')
  534. }
  535. });
  536. });
  537. afterEach(() =>
  538. closeWindow(w).then(() => {
  539. w = null as unknown as BrowserWindow;
  540. })
  541. );
  542. it('applies matching rules in subframes', async () => {
  543. const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2);
  544. w.loadFile(path.join(contentScript, 'frame-with-frame.html'));
  545. const frameEvents = await detailsPromise;
  546. await Promise.all(
  547. frameEvents.map(async frameEvent => {
  548. const [, isMainFrame, , frameRoutingId] = frameEvent;
  549. const result: any = await executeJavaScriptInFrame(
  550. w.webContents,
  551. frameRoutingId,
  552. `(() => {
  553. const a = document.getElementById('all_frames_enabled')
  554. const b = document.getElementById('all_frames_disabled')
  555. return {
  556. enabledColor: getComputedStyle(a).backgroundColor,
  557. disabledColor: getComputedStyle(b).backgroundColor
  558. }
  559. })()`
  560. );
  561. expect(result.enabledColor).to.equal(COLOR_RED);
  562. if (isMainFrame) {
  563. expect(result.disabledColor).to.equal(COLOR_BLUE);
  564. } else {
  565. expect(result.disabledColor).to.equal(COLOR_TRANSPARENT); // null color
  566. }
  567. })
  568. );
  569. });
  570. });
  571. });
  572. };
  573. generateTests(false, false);
  574. generateTests(false, true);
  575. generateTests(true, false);
  576. generateTests(true, true);
  577. });
  578. describe('extension ui pages', () => {
  579. afterEach(() => {
  580. session.defaultSession.getAllExtensions().forEach(e => {
  581. session.defaultSession.removeExtension(e.id);
  582. });
  583. });
  584. it('loads a ui page of an extension', async () => {
  585. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  586. const w = new BrowserWindow({ show: false });
  587. await w.loadURL(`chrome-extension://${id}/bare-page.html`);
  588. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  589. expect(textContent).to.equal('ui page loaded ok\n');
  590. });
  591. it('can load resources', async () => {
  592. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  593. const w = new BrowserWindow({ show: false });
  594. await w.loadURL(`chrome-extension://${id}/page-script-load.html`);
  595. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  596. expect(textContent).to.equal('script loaded ok\n');
  597. });
  598. });
  599. describe('manifest v3', () => {
  600. it('registers background service worker', async () => {
  601. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  602. const registrationPromise = new Promise<string>(resolve => {
  603. customSession.serviceWorkers.once('registration-completed', (event, { scope }) => resolve(scope));
  604. });
  605. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
  606. const scope = await registrationPromise;
  607. expect(scope).equals(extension.url);
  608. });
  609. });
  610. });