extensions-spec.ts 30 KB

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