extensions-spec.ts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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';
  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. it('executeScript', async () => {
  304. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  305. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  306. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  307. await w.loadURL(url);
  308. const message = { method: 'executeScript', args: ['1 + 2'] };
  309. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  310. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  311. const response = JSON.parse(responseString);
  312. expect(response).to.equal(3);
  313. });
  314. it('connect', async () => {
  315. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  316. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  317. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  318. await w.loadURL(url);
  319. const portName = uuid.v4();
  320. const message = { method: 'connectTab', args: [portName] };
  321. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  322. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  323. const response = responseString.split(',');
  324. expect(response[0]).to.equal(portName);
  325. expect(response[1]).to.equal('howdy');
  326. });
  327. it('sendMessage receives the response', async function () {
  328. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  329. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  330. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  331. await w.loadURL(url);
  332. const message = { method: 'sendMessage', args: ['Hello World!'] };
  333. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  334. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  335. const response = JSON.parse(responseString);
  336. expect(response.message).to.equal('Hello World!');
  337. expect(response.tabId).to.equal(w.webContents.id);
  338. });
  339. });
  340. describe('background pages', () => {
  341. it('loads a lazy background page when sending a message', async () => {
  342. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  343. await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  344. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  345. try {
  346. w.loadURL(url);
  347. const [, resp] = await emittedOnce(ipcMain, 'bg-page-message-response');
  348. expect(resp.message).to.deep.equal({ some: 'message' });
  349. expect(resp.sender.id).to.be.a('string');
  350. expect(resp.sender.origin).to.equal(url);
  351. expect(resp.sender.url).to.equal(url + '/');
  352. } finally {
  353. w.destroy();
  354. }
  355. });
  356. it('can use extension.getBackgroundPage from a ui page', async () => {
  357. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  358. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  359. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  360. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  361. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  362. expect(receivedMessage).to.deep.equal({ some: 'message' });
  363. });
  364. it('can use extension.getBackgroundPage from a ui page', async () => {
  365. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  366. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  367. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  368. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  369. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  370. expect(receivedMessage).to.deep.equal({ some: 'message' });
  371. });
  372. it('can use runtime.getBackgroundPage from a ui page', async () => {
  373. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  374. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  375. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  376. await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`);
  377. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  378. expect(receivedMessage).to.deep.equal({ some: 'message' });
  379. });
  380. it('has session in background page', async () => {
  381. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  382. const promise = emittedOnce(app, 'web-contents-created');
  383. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  384. const [, bgPageContents] = await promise;
  385. expect(bgPageContents.getType()).to.equal('backgroundPage');
  386. await emittedOnce(bgPageContents, 'did-finish-load');
  387. expect(bgPageContents.getURL()).to.equal(`chrome-extension://${id}/_generated_background_page.html`);
  388. expect(bgPageContents.session).to.not.equal(undefined);
  389. });
  390. it('can open devtools of background page', async () => {
  391. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  392. const promise = emittedOnce(app, 'web-contents-created');
  393. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  394. const [, bgPageContents] = await promise;
  395. expect(bgPageContents.getType()).to.equal('backgroundPage');
  396. bgPageContents.openDevTools();
  397. bgPageContents.closeDevTools();
  398. });
  399. });
  400. describe('devtools extensions', () => {
  401. let showPanelTimeoutId: any = null;
  402. afterEach(() => {
  403. if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId);
  404. });
  405. const showLastDevToolsPanel = (w: BrowserWindow) => {
  406. w.webContents.once('devtools-opened', () => {
  407. const show = () => {
  408. if (w == null || w.isDestroyed()) return;
  409. const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined };
  410. if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
  411. return;
  412. }
  413. const showLastPanel = () => {
  414. // this is executed in the devtools context, where UI is a global
  415. const { UI } = (window as any);
  416. const tabs = UI.inspectorView._tabbedPane._tabs;
  417. const lastPanelId = tabs[tabs.length - 1].id;
  418. UI.inspectorView.showPanel(lastPanelId);
  419. };
  420. devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
  421. showPanelTimeoutId = setTimeout(show, 100);
  422. });
  423. };
  424. showPanelTimeoutId = setTimeout(show, 100);
  425. });
  426. };
  427. it('loads a devtools extension', async () => {
  428. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  429. customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension'));
  430. const winningMessage = emittedOnce(ipcMain, 'winning');
  431. const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  432. await w.loadURL(url);
  433. w.webContents.openDevTools();
  434. showLastDevToolsPanel(w);
  435. await winningMessage;
  436. });
  437. });
  438. describe('chrome extension content scripts', () => {
  439. const fixtures = path.resolve(__dirname, 'fixtures');
  440. const extensionPath = path.resolve(fixtures, 'extensions');
  441. const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name));
  442. const removeAllExtensions = () => {
  443. Object.keys(session.defaultSession.getAllExtensions()).map(extName => {
  444. session.defaultSession.removeExtension(extName);
  445. });
  446. };
  447. let responseIdCounter = 0;
  448. const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => {
  449. return new Promise(resolve => {
  450. const responseId = responseIdCounter++;
  451. ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => {
  452. resolve(result);
  453. });
  454. webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId);
  455. });
  456. };
  457. const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => {
  458. describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => {
  459. let w: BrowserWindow;
  460. describe('supports "run_at" option', () => {
  461. beforeEach(async () => {
  462. await closeWindow(w);
  463. w = new BrowserWindow({
  464. show: false,
  465. width: 400,
  466. height: 400,
  467. webPreferences: {
  468. contextIsolation: contextIsolationEnabled,
  469. sandbox: sandboxEnabled
  470. }
  471. });
  472. });
  473. afterEach(() => {
  474. removeAllExtensions();
  475. return closeWindow(w).then(() => { w = null as unknown as BrowserWindow; });
  476. });
  477. it('should run content script at document_start', async () => {
  478. await addExtension('content-script-document-start');
  479. w.webContents.once('dom-ready', async () => {
  480. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  481. expect(result).to.equal('red');
  482. });
  483. w.loadURL(url);
  484. });
  485. it('should run content script at document_idle', async () => {
  486. await addExtension('content-script-document-idle');
  487. w.loadURL(url);
  488. const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor');
  489. expect(result).to.equal('red');
  490. });
  491. it('should run content script at document_end', async () => {
  492. await addExtension('content-script-document-end');
  493. w.webContents.once('did-finish-load', async () => {
  494. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  495. expect(result).to.equal('red');
  496. });
  497. w.loadURL(url);
  498. });
  499. });
  500. // TODO(nornagon): real extensions don't load on file: urls, so this
  501. // test needs to be updated to serve its content over http.
  502. describe.skip('supports "all_frames" option', () => {
  503. const contentScript = path.resolve(fixtures, 'extensions/content-script');
  504. // Computed style values
  505. const COLOR_RED = 'rgb(255, 0, 0)';
  506. const COLOR_BLUE = 'rgb(0, 0, 255)';
  507. const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)';
  508. before(() => {
  509. session.defaultSession.loadExtension(contentScript);
  510. });
  511. after(() => {
  512. session.defaultSession.removeExtension('content-script-test');
  513. });
  514. beforeEach(() => {
  515. w = new BrowserWindow({
  516. show: false,
  517. webPreferences: {
  518. // enable content script injection in subframes
  519. nodeIntegrationInSubFrames: true,
  520. preload: path.join(contentScript, 'all_frames-preload.js')
  521. }
  522. });
  523. });
  524. afterEach(() =>
  525. closeWindow(w).then(() => {
  526. w = null as unknown as BrowserWindow;
  527. })
  528. );
  529. it('applies matching rules in subframes', async () => {
  530. const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2);
  531. w.loadFile(path.join(contentScript, 'frame-with-frame.html'));
  532. const frameEvents = await detailsPromise;
  533. await Promise.all(
  534. frameEvents.map(async frameEvent => {
  535. const [, isMainFrame, , frameRoutingId] = frameEvent;
  536. const result: any = await executeJavaScriptInFrame(
  537. w.webContents,
  538. frameRoutingId,
  539. `(() => {
  540. const a = document.getElementById('all_frames_enabled')
  541. const b = document.getElementById('all_frames_disabled')
  542. return {
  543. enabledColor: getComputedStyle(a).backgroundColor,
  544. disabledColor: getComputedStyle(b).backgroundColor
  545. }
  546. })()`
  547. );
  548. expect(result.enabledColor).to.equal(COLOR_RED);
  549. if (isMainFrame) {
  550. expect(result.disabledColor).to.equal(COLOR_BLUE);
  551. } else {
  552. expect(result.disabledColor).to.equal(COLOR_TRANSPARENT); // null color
  553. }
  554. })
  555. );
  556. });
  557. });
  558. });
  559. };
  560. generateTests(false, false);
  561. generateTests(false, true);
  562. generateTests(true, false);
  563. generateTests(true, true);
  564. });
  565. describe('extension ui pages', () => {
  566. afterEach(() => {
  567. session.defaultSession.getAllExtensions().forEach(e => {
  568. session.defaultSession.removeExtension(e.id);
  569. });
  570. });
  571. it('loads a ui page of an extension', async () => {
  572. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  573. const w = new BrowserWindow({ show: false });
  574. await w.loadURL(`chrome-extension://${id}/bare-page.html`);
  575. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  576. expect(textContent).to.equal('ui page loaded ok\n');
  577. });
  578. it('can load resources', async () => {
  579. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  580. const w = new BrowserWindow({ show: false });
  581. await w.loadURL(`chrome-extension://${id}/page-script-load.html`);
  582. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  583. expect(textContent).to.equal('script loaded ok\n');
  584. });
  585. });
  586. describe('manifest v3', () => {
  587. it('registers background service worker', async () => {
  588. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  589. const registrationPromise = new Promise<string>(resolve => {
  590. customSession.serviceWorkers.once('registration-completed', (event, { scope }) => resolve(scope));
  591. });
  592. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
  593. const scope = await registrationPromise;
  594. expect(scope).equals(extension.url);
  595. });
  596. });
  597. });