extensions-spec.ts 30 KB

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