extensions-spec.ts 30 KB

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