extensions-spec.ts 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. import { expect } from 'chai';
  2. import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main';
  3. import { closeAllWindows, closeWindow } from './lib/window-helpers';
  4. import * as http from 'node:http';
  5. import * as path from 'node:path';
  6. import * as fs from 'node:fs';
  7. import * as WebSocket from 'ws';
  8. import { emittedNTimes, emittedUntil } from './lib/events-helpers';
  9. import { ifit, listen } from './lib/spec-helpers';
  10. import { once } from 'node:events';
  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: number;
  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. ({ port, url } = await listen(server));
  35. });
  36. after(() => {
  37. server.close();
  38. });
  39. afterEach(closeAllWindows);
  40. afterEach(() => {
  41. for (const e of session.defaultSession.getAllExtensions()) {
  42. session.defaultSession.removeExtension(e.id);
  43. }
  44. });
  45. it('does not crash when using chrome.management', async () => {
  46. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  47. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  48. await w.loadURL('about:blank');
  49. const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
  50. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  51. const args: any = await promise;
  52. const wc: Electron.WebContents = args[1];
  53. await expect(wc.executeJavaScript(`
  54. (() => {
  55. return new Promise((resolve) => {
  56. chrome.management.getSelf((info) => {
  57. resolve(info);
  58. });
  59. })
  60. })();
  61. `)).to.eventually.have.property('id');
  62. });
  63. describe('host_permissions', async () => {
  64. let customSession: Session;
  65. let w: BrowserWindow;
  66. beforeEach(() => {
  67. customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  68. w = new BrowserWindow({
  69. show: false,
  70. webPreferences: {
  71. session: customSession,
  72. sandbox: true
  73. }
  74. });
  75. });
  76. afterEach(closeAllWindows);
  77. it('recognize malformed host permissions', async () => {
  78. await w.loadURL(url);
  79. const extPath = path.join(fixtures, 'extensions', 'host-permissions', 'malformed');
  80. customSession.loadExtension(extPath);
  81. const warning = await new Promise(resolve => { process.on('warning', resolve); });
  82. const malformedHost = /Permission 'malformed_host' is unknown or URL pattern is malformed/;
  83. expect(warning).to.match(malformedHost);
  84. });
  85. it('can grant special privileges to urls with host permissions', async () => {
  86. const extPath = path.join(fixtures, 'extensions', 'host-permissions', 'privileged-tab-info');
  87. await customSession.loadExtension(extPath);
  88. await w.loadURL(url);
  89. const message = { method: 'query' };
  90. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  91. const [,, responseString] = await once(w.webContents, 'console-message');
  92. const response = JSON.parse(responseString);
  93. expect(response).to.have.lengthOf(1);
  94. const tab = response[0];
  95. expect(tab).to.have.property('url').that.is.a('string');
  96. expect(tab).to.have.property('title').that.is.a('string');
  97. expect(tab).to.have.property('active').that.is.a('boolean');
  98. expect(tab).to.have.property('autoDiscardable').that.is.a('boolean');
  99. expect(tab).to.have.property('discarded').that.is.a('boolean');
  100. expect(tab).to.have.property('groupId').that.is.a('number');
  101. expect(tab).to.have.property('highlighted').that.is.a('boolean');
  102. expect(tab).to.have.property('id').that.is.a('number');
  103. expect(tab).to.have.property('incognito').that.is.a('boolean');
  104. expect(tab).to.have.property('index').that.is.a('number');
  105. expect(tab).to.have.property('pinned').that.is.a('boolean');
  106. expect(tab).to.have.property('selected').that.is.a('boolean');
  107. expect(tab).to.have.property('windowId').that.is.a('number');
  108. });
  109. });
  110. it('supports minimum_chrome_version manifest key', async () => {
  111. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  112. const w = new BrowserWindow({
  113. show: false,
  114. webPreferences: {
  115. session: customSession,
  116. sandbox: true
  117. }
  118. });
  119. await w.loadURL('about:blank');
  120. const extPath = path.join(fixtures, 'extensions', 'minimum-chrome-version');
  121. const load = customSession.loadExtension(extPath);
  122. await expect(load).to.eventually.be.rejectedWith(
  123. `Loading extension at ${extPath} failed with: This extension requires Chromium version 999 or greater.`
  124. );
  125. });
  126. it('can open WebSQLDatabase in a background page', async () => {
  127. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  128. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  129. await w.loadURL('about:blank');
  130. const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
  131. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  132. const args: any = await promise;
  133. const wc: Electron.WebContents = args[1];
  134. await expect(wc.executeJavaScript('(()=>{try{openDatabase("t", "1.0", "test", 2e5);return true;}catch(e){throw e}})()')).to.not.be.rejected();
  135. });
  136. function fetch (contents: WebContents, url: string) {
  137. return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
  138. }
  139. it('bypasses CORS in requests made from extensions', async () => {
  140. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  141. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  142. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  143. await w.loadURL(`${extension.url}bare-page.html`);
  144. await expect(fetch(w.webContents, `${url}/cors`)).to.not.be.rejectedWith(TypeError);
  145. });
  146. it('loads an extension', async () => {
  147. // NB. we have to use a persist: session (i.e. non-OTR) because the
  148. // extension registry is redirected to the main session. so installing an
  149. // extension in an in-memory session results in it being installed in the
  150. // default session.
  151. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  152. await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  153. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  154. await w.loadURL(url);
  155. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  156. expect(bg).to.equal('red');
  157. });
  158. it('does not crash when loading an extension with missing manifest', async () => {
  159. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  160. const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'missing-manifest'));
  161. await expect(promise).to.eventually.be.rejectedWith(/Manifest file is missing or unreadable/);
  162. });
  163. it('does not crash when failing to load an extension', async () => {
  164. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  165. const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'load-error'));
  166. await expect(promise).to.eventually.be.rejected();
  167. });
  168. it('serializes a loaded extension', async () => {
  169. const extensionPath = path.join(fixtures, 'extensions', 'red-bg');
  170. const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8'));
  171. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  172. const extension = await customSession.loadExtension(extensionPath);
  173. expect(extension.id).to.be.a('string');
  174. expect(extension.name).to.be.a('string');
  175. expect(extension.path).to.be.a('string');
  176. expect(extension.version).to.be.a('string');
  177. expect(extension.url).to.be.a('string');
  178. expect(extension.manifest).to.deep.equal(manifest);
  179. });
  180. it('removes an extension', async () => {
  181. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  182. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  183. {
  184. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  185. await w.loadURL(url);
  186. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  187. expect(bg).to.equal('red');
  188. }
  189. customSession.removeExtension(id);
  190. {
  191. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  192. await w.loadURL(url);
  193. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  194. expect(bg).to.equal('');
  195. }
  196. });
  197. it('emits extension lifecycle events', async () => {
  198. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  199. const loadedPromise = once(customSession, 'extension-loaded');
  200. const readyPromise = emittedUntil(customSession, 'extension-ready', (event: Event, extension: Extension) => {
  201. return extension.name !== 'Chromium PDF Viewer';
  202. });
  203. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  204. const [, loadedExtension] = await loadedPromise;
  205. const [, readyExtension] = await readyPromise;
  206. expect(loadedExtension).to.deep.equal(extension);
  207. expect(readyExtension).to.deep.equal(extension);
  208. const unloadedPromise = once(customSession, 'extension-unloaded');
  209. await customSession.removeExtension(extension.id);
  210. const [, unloadedExtension] = await unloadedPromise;
  211. expect(unloadedExtension).to.deep.equal(extension);
  212. });
  213. it('lists loaded extensions in getAllExtensions', async () => {
  214. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  215. const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  216. expect(customSession.getAllExtensions()).to.deep.equal([e]);
  217. customSession.removeExtension(e.id);
  218. expect(customSession.getAllExtensions()).to.deep.equal([]);
  219. });
  220. it('gets an extension by id', async () => {
  221. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  222. const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  223. expect(customSession.getExtension(e.id)).to.deep.equal(e);
  224. });
  225. it('confines an extension to the session it was loaded in', async () => {
  226. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  227. await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  228. const w = new BrowserWindow({ show: false }); // not in the session
  229. await w.loadURL(url);
  230. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  231. expect(bg).to.equal('');
  232. });
  233. it('loading an extension in a temporary session throws an error', async () => {
  234. const customSession = session.fromPartition(uuid.v4());
  235. await expect(customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'))).to.eventually.be.rejectedWith('Extensions cannot be loaded in a temporary session');
  236. });
  237. describe('chrome.i18n', () => {
  238. let w: BrowserWindow;
  239. let extension: Extension;
  240. const exec = async (name: string) => {
  241. const p = once(ipcMain, 'success');
  242. await w.webContents.executeJavaScript(`exec('${name}')`);
  243. const [, result] = await p;
  244. return result;
  245. };
  246. beforeEach(async () => {
  247. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  248. extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n', 'v2'));
  249. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  250. await w.loadURL(url);
  251. });
  252. it('getAcceptLanguages()', async () => {
  253. const result = await exec('getAcceptLanguages');
  254. expect(result).to.be.an('array').and.deep.equal(['en-US', 'en']);
  255. });
  256. it('getMessage()', async () => {
  257. const result = await exec('getMessage');
  258. expect(result.id).to.be.a('string').and.equal(extension.id);
  259. expect(result.name).to.be.a('string').and.equal('chrome-i18n');
  260. });
  261. });
  262. describe('chrome.runtime', () => {
  263. let w: BrowserWindow;
  264. const exec = async (name: string) => {
  265. const p = once(ipcMain, 'success');
  266. await w.webContents.executeJavaScript(`exec('${name}')`);
  267. const [, result] = await p;
  268. return result;
  269. };
  270. beforeEach(async () => {
  271. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  272. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-runtime'));
  273. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  274. await w.loadURL(url);
  275. });
  276. it('getManifest()', async () => {
  277. const result = await exec('getManifest');
  278. expect(result).to.be.an('object').with.property('name', 'chrome-runtime');
  279. });
  280. it('id', async () => {
  281. const result = await exec('id');
  282. expect(result).to.be.a('string').with.lengthOf(32);
  283. });
  284. it('getURL()', async () => {
  285. const result = await exec('getURL');
  286. expect(result).to.be.a('string').and.match(/^chrome-extension:\/\/.*main.js$/);
  287. });
  288. it('getPlatformInfo()', async () => {
  289. const result = await exec('getPlatformInfo');
  290. expect(result).to.be.an('object');
  291. expect(result.os).to.be.a('string');
  292. expect(result.arch).to.be.a('string');
  293. expect(result.nacl_arch).to.be.a('string');
  294. });
  295. });
  296. describe('chrome.storage', () => {
  297. it('stores and retrieves a key', async () => {
  298. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  299. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-storage'));
  300. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  301. try {
  302. const p = once(ipcMain, 'storage-success');
  303. await w.loadURL(url);
  304. const [, v] = await p;
  305. expect(v).to.equal('value');
  306. } finally {
  307. w.destroy();
  308. }
  309. });
  310. });
  311. describe('chrome.webRequest', () => {
  312. function fetch (contents: WebContents, url: string) {
  313. return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
  314. }
  315. let customSession: Session;
  316. let w: BrowserWindow;
  317. beforeEach(() => {
  318. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  319. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true, contextIsolation: true } });
  320. });
  321. describe('onBeforeRequest', () => {
  322. it('can cancel http requests', async () => {
  323. await w.loadURL(url);
  324. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
  325. await expect(fetch(w.webContents, url)).to.eventually.be.rejectedWith('Failed to fetch');
  326. });
  327. it('does not cancel http requests when no extension loaded', async () => {
  328. await w.loadURL(url);
  329. await expect(fetch(w.webContents, url)).to.not.be.rejectedWith('Failed to fetch');
  330. });
  331. });
  332. it('does not take precedence over Electron webRequest - http', async () => {
  333. return new Promise<void>((resolve) => {
  334. (async () => {
  335. customSession.webRequest.onBeforeRequest((details, callback) => {
  336. resolve();
  337. callback({ cancel: true });
  338. });
  339. await w.loadURL(url);
  340. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
  341. fetch(w.webContents, url);
  342. })();
  343. });
  344. });
  345. it('does not take precedence over Electron webRequest - WebSocket', () => {
  346. return new Promise<void>((resolve) => {
  347. (async () => {
  348. customSession.webRequest.onBeforeSendHeaders(() => {
  349. resolve();
  350. });
  351. await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } });
  352. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
  353. })();
  354. });
  355. });
  356. describe('WebSocket', () => {
  357. it('can be proxied', async () => {
  358. await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port: `${port}` } });
  359. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
  360. customSession.webRequest.onSendHeaders((details) => {
  361. if (details.url.startsWith('ws://')) {
  362. expect(details.requestHeaders.foo).be.equal('bar');
  363. }
  364. });
  365. });
  366. });
  367. });
  368. describe('chrome.tabs', () => {
  369. let customSession: Session;
  370. before(async () => {
  371. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  372. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  373. });
  374. it('executeScript', async () => {
  375. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  376. await w.loadURL(url);
  377. const message = { method: 'executeScript', args: ['1 + 2'] };
  378. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  379. const [, , responseString] = await once(w.webContents, 'console-message');
  380. const response = JSON.parse(responseString);
  381. expect(response).to.equal(3);
  382. });
  383. it('connect', async () => {
  384. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  385. await w.loadURL(url);
  386. const portName = uuid.v4();
  387. const message = { method: 'connectTab', args: [portName] };
  388. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  389. const [,, responseString] = await once(w.webContents, 'console-message');
  390. const response = responseString.split(',');
  391. expect(response[0]).to.equal(portName);
  392. expect(response[1]).to.equal('howdy');
  393. });
  394. it('sendMessage receives the response', async () => {
  395. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  396. await w.loadURL(url);
  397. const message = { method: 'sendMessage', args: ['Hello World!'] };
  398. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  399. const [,, responseString] = await once(w.webContents, 'console-message');
  400. const response = JSON.parse(responseString);
  401. expect(response.message).to.equal('Hello World!');
  402. expect(response.tabId).to.equal(w.webContents.id);
  403. });
  404. it('update', async () => {
  405. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  406. await w.loadURL(url);
  407. const w2 = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  408. await w2.loadURL('about:blank');
  409. const w2Navigated = once(w2.webContents, 'did-navigate');
  410. const message = { method: 'update', args: [w2.webContents.id, { url }] };
  411. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  412. const [,, responseString] = await once(w.webContents, 'console-message');
  413. const response = JSON.parse(responseString);
  414. await w2Navigated;
  415. expect(new URL(w2.getURL()).toString()).to.equal(new URL(url).toString());
  416. expect(response.id).to.equal(w2.webContents.id);
  417. });
  418. });
  419. describe('background pages', () => {
  420. it('loads a lazy background page when sending a message', async () => {
  421. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  422. await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  423. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  424. try {
  425. w.loadURL(url);
  426. const [, resp] = await once(ipcMain, 'bg-page-message-response');
  427. expect(resp.message).to.deep.equal({ some: 'message' });
  428. expect(resp.sender.id).to.be.a('string');
  429. expect(resp.sender.origin).to.equal(url);
  430. expect(resp.sender.url).to.equal(url + '/');
  431. } finally {
  432. w.destroy();
  433. }
  434. });
  435. it('can use extension.getBackgroundPage from a ui page', async () => {
  436. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  437. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  438. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  439. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  440. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  441. expect(receivedMessage).to.deep.equal({ some: 'message' });
  442. });
  443. it('can use extension.getBackgroundPage from a ui page', async () => {
  444. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  445. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  446. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  447. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  448. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  449. expect(receivedMessage).to.deep.equal({ some: 'message' });
  450. });
  451. it('can use runtime.getBackgroundPage from a ui page', async () => {
  452. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  453. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  454. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  455. await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`);
  456. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  457. expect(receivedMessage).to.deep.equal({ some: 'message' });
  458. });
  459. it('has session in background page', async () => {
  460. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  461. const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
  462. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  463. const [, bgPageContents] = await promise;
  464. expect(bgPageContents.getType()).to.equal('backgroundPage');
  465. await once(bgPageContents, 'did-finish-load');
  466. expect(bgPageContents.getURL()).to.equal(`chrome-extension://${id}/_generated_background_page.html`);
  467. expect(bgPageContents.session).to.not.equal(undefined);
  468. });
  469. it('can open devtools of background page', async () => {
  470. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  471. const promise = once(app, 'web-contents-created') as Promise<[any, WebContents]>;
  472. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  473. const [, bgPageContents] = await promise;
  474. expect(bgPageContents.getType()).to.equal('backgroundPage');
  475. bgPageContents.openDevTools();
  476. bgPageContents.closeDevTools();
  477. });
  478. });
  479. describe('devtools extensions', () => {
  480. let showPanelTimeoutId: any = null;
  481. afterEach(() => {
  482. if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId);
  483. });
  484. const showLastDevToolsPanel = (w: BrowserWindow) => {
  485. w.webContents.once('devtools-opened', () => {
  486. const show = () => {
  487. if (w == null || w.isDestroyed()) return;
  488. const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined };
  489. if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
  490. return;
  491. }
  492. const showLastPanel = () => {
  493. // this is executed in the devtools context, where UI is a global
  494. const { UI } = (window as any);
  495. const tabs = UI.inspectorView.tabbedPane.tabs;
  496. const lastPanelId = tabs[tabs.length - 1].id;
  497. UI.inspectorView.showPanel(lastPanelId);
  498. };
  499. devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
  500. showPanelTimeoutId = setTimeout(show, 100);
  501. });
  502. };
  503. showPanelTimeoutId = setTimeout(show, 100);
  504. });
  505. };
  506. // TODO(jkleinsc) fix this flaky test on WOA
  507. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads a devtools extension', async () => {
  508. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  509. customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension'));
  510. const winningMessage = once(ipcMain, 'winning');
  511. const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  512. await w.loadURL(url);
  513. w.webContents.openDevTools();
  514. showLastDevToolsPanel(w);
  515. await winningMessage;
  516. });
  517. });
  518. describe('chrome extension content scripts', () => {
  519. const fixtures = path.resolve(__dirname, 'fixtures');
  520. const extensionPath = path.resolve(fixtures, 'extensions');
  521. const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name));
  522. const removeAllExtensions = () => {
  523. Object.keys(session.defaultSession.getAllExtensions()).map(extName => {
  524. session.defaultSession.removeExtension(extName);
  525. });
  526. };
  527. let responseIdCounter = 0;
  528. const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => {
  529. return new Promise(resolve => {
  530. const responseId = responseIdCounter++;
  531. ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => {
  532. resolve(result);
  533. });
  534. webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId);
  535. });
  536. };
  537. const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => {
  538. describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => {
  539. let w: BrowserWindow;
  540. describe('supports "run_at" option', () => {
  541. beforeEach(async () => {
  542. await closeWindow(w);
  543. w = new BrowserWindow({
  544. show: false,
  545. width: 400,
  546. height: 400,
  547. webPreferences: {
  548. contextIsolation: contextIsolationEnabled,
  549. sandbox: sandboxEnabled
  550. }
  551. });
  552. });
  553. afterEach(async () => {
  554. removeAllExtensions();
  555. await closeWindow(w);
  556. w = null as unknown as BrowserWindow;
  557. });
  558. it('should run content script at document_start', async () => {
  559. await addExtension('content-script-document-start');
  560. w.webContents.once('dom-ready', async () => {
  561. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  562. expect(result).to.equal('red');
  563. });
  564. w.loadURL(url);
  565. });
  566. it('should run content script at document_idle', async () => {
  567. await addExtension('content-script-document-idle');
  568. w.loadURL(url);
  569. const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor');
  570. expect(result).to.equal('red');
  571. });
  572. it('should run content script at document_end', async () => {
  573. await addExtension('content-script-document-end');
  574. w.webContents.once('did-finish-load', async () => {
  575. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  576. expect(result).to.equal('red');
  577. });
  578. w.loadURL(url);
  579. });
  580. });
  581. describe('supports "all_frames" option', () => {
  582. const contentScript = path.resolve(fixtures, 'extensions/content-script');
  583. const contentPath = path.join(contentScript, 'frame-with-frame.html');
  584. // Computed style values
  585. const COLOR_RED = 'rgb(255, 0, 0)';
  586. const COLOR_BLUE = 'rgb(0, 0, 255)';
  587. const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)';
  588. let server: http.Server;
  589. let port: number;
  590. before(async () => {
  591. server = http.createServer((_, res) => {
  592. fs.readFile(contentPath, (error, content) => {
  593. if (error) {
  594. res.writeHead(500);
  595. res.end(`Failed to load ${contentPath} : ${error.code}`);
  596. } else {
  597. res.writeHead(200, { 'Content-Type': 'text/html' });
  598. res.end(content, 'utf-8');
  599. }
  600. });
  601. });
  602. ({ port, url } = await listen(server));
  603. session.defaultSession.loadExtension(contentScript);
  604. });
  605. after(() => {
  606. session.defaultSession.removeExtension('content-script-test');
  607. });
  608. beforeEach(() => {
  609. w = new BrowserWindow({
  610. show: false,
  611. webPreferences: {
  612. // enable content script injection in subframes
  613. nodeIntegrationInSubFrames: true,
  614. preload: path.join(contentScript, 'all_frames-preload.js')
  615. }
  616. });
  617. });
  618. afterEach(() =>
  619. closeWindow(w).then(() => {
  620. w = null as unknown as BrowserWindow;
  621. })
  622. );
  623. it('applies matching rules in subframes', async () => {
  624. const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2);
  625. w.loadURL(`http://127.0.0.1:${port}`);
  626. const frameEvents = await detailsPromise;
  627. await Promise.all(
  628. frameEvents.map(async frameEvent => {
  629. const [, isMainFrame, , frameRoutingId] = frameEvent;
  630. const result: any = await executeJavaScriptInFrame(
  631. w.webContents,
  632. frameRoutingId,
  633. `(() => {
  634. const a = document.getElementById('all_frames_enabled')
  635. const b = document.getElementById('all_frames_disabled')
  636. return {
  637. enabledColor: getComputedStyle(a).backgroundColor,
  638. disabledColor: getComputedStyle(b).backgroundColor
  639. }
  640. })()`
  641. );
  642. expect(result.enabledColor).to.equal(COLOR_RED);
  643. expect(result.disabledColor).to.equal(isMainFrame ? COLOR_BLUE : COLOR_TRANSPARENT);
  644. })
  645. );
  646. });
  647. });
  648. });
  649. };
  650. generateTests(false, false);
  651. generateTests(false, true);
  652. generateTests(true, false);
  653. generateTests(true, true);
  654. });
  655. describe('extension ui pages', () => {
  656. afterEach(() => {
  657. for (const e of session.defaultSession.getAllExtensions()) {
  658. session.defaultSession.removeExtension(e.id);
  659. }
  660. });
  661. it('loads a ui page of an extension', async () => {
  662. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  663. const w = new BrowserWindow({ show: false });
  664. await w.loadURL(`chrome-extension://${id}/bare-page.html`);
  665. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  666. expect(textContent).to.equal('ui page loaded ok\n');
  667. });
  668. it('can load resources', async () => {
  669. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  670. const w = new BrowserWindow({ show: false });
  671. await w.loadURL(`chrome-extension://${id}/page-script-load.html`);
  672. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  673. expect(textContent).to.equal('script loaded ok\n');
  674. });
  675. });
  676. describe('manifest v3', () => {
  677. it('registers background service worker', async () => {
  678. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  679. const registrationPromise = new Promise<string>(resolve => {
  680. customSession.serviceWorkers.once('registration-completed', (event, { scope }) => resolve(scope));
  681. });
  682. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
  683. const scope = await registrationPromise;
  684. expect(scope).equals(extension.url);
  685. });
  686. it('can run chrome extension APIs', async () => {
  687. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  688. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  689. await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
  690. await w.loadURL(url);
  691. w.webContents.executeJavaScript('window.postMessage(\'fetch-confirmation\', \'*\')');
  692. const [, , responseString] = await once(w.webContents, 'console-message');
  693. const { message } = JSON.parse(responseString);
  694. expect(message).to.equal('Hello from background.js');
  695. });
  696. describe('chrome.i18n', () => {
  697. let customSession: Session;
  698. let w = null as unknown as BrowserWindow;
  699. before(async () => {
  700. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  701. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n', 'v3'));
  702. });
  703. beforeEach(() => {
  704. w = new BrowserWindow({
  705. show: false,
  706. webPreferences: {
  707. session: customSession,
  708. nodeIntegration: true
  709. }
  710. });
  711. });
  712. afterEach(closeAllWindows);
  713. it('getAcceptLanguages', async () => {
  714. await w.loadURL(url);
  715. const message = { method: 'getAcceptLanguages' };
  716. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  717. const [,, responseString] = await once(w.webContents, 'console-message');
  718. const response = JSON.parse(responseString);
  719. expect(response).to.be.an('array').that.is.not.empty('languages array is empty');
  720. });
  721. it('getUILanguage', async () => {
  722. await w.loadURL(url);
  723. const message = { method: 'getUILanguage' };
  724. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  725. const [,, responseString] = await once(w.webContents, 'console-message');
  726. const response = JSON.parse(responseString);
  727. expect(response).to.be.a('string');
  728. });
  729. it('getMessage', async () => {
  730. await w.loadURL(url);
  731. const message = { method: 'getMessage' };
  732. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  733. const [, , responseString] = await once(w.webContents, 'console-message');
  734. const response = JSON.parse(responseString);
  735. expect(response).to.equal('Hola mundo!!');
  736. });
  737. it('detectLanguage', async () => {
  738. await w.loadURL(url);
  739. const greetings = [
  740. 'Ich liebe dich', // German
  741. 'Mahal kita', // Filipino
  742. '愛してます', // Japanese
  743. 'دوستت دارم', // Persian
  744. 'Minä rakastan sinua' // Finnish
  745. ];
  746. const message = { method: 'detectLanguage', args: [greetings] };
  747. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  748. const [, , responseString] = await once(w.webContents, 'console-message');
  749. const response = JSON.parse(responseString);
  750. expect(response).to.be.an('array');
  751. for (const item of response) {
  752. expect(Object.keys(item)).to.deep.equal(['isReliable', 'languages']);
  753. }
  754. const languages = response.map((r: { isReliable: boolean, languages: any[] }) => r.languages[0]);
  755. expect(languages).to.deep.equal([
  756. { language: 'de', percentage: 100 },
  757. { language: 'fil', percentage: 100 },
  758. { language: 'ja', percentage: 100 },
  759. { language: 'ps', percentage: 100 },
  760. { language: 'fi', percentage: 100 }
  761. ]);
  762. });
  763. });
  764. describe('chrome.tabs', () => {
  765. let customSession: Session;
  766. let w = null as unknown as BrowserWindow;
  767. before(async () => {
  768. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  769. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'api-async'));
  770. });
  771. beforeEach(() => {
  772. w = new BrowserWindow({
  773. show: false,
  774. webPreferences: {
  775. session: customSession
  776. }
  777. });
  778. });
  779. afterEach(closeAllWindows);
  780. it('getZoom', async () => {
  781. await w.loadURL(url);
  782. const message = { method: 'getZoom' };
  783. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  784. const [,, responseString] = await once(w.webContents, 'console-message');
  785. const response = JSON.parse(responseString);
  786. expect(response).to.equal(1);
  787. });
  788. it('setZoom', async () => {
  789. await w.loadURL(url);
  790. const message = { method: 'setZoom', args: [2] };
  791. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  792. const [,, responseString] = await once(w.webContents, 'console-message');
  793. const response = JSON.parse(responseString);
  794. expect(response).to.deep.equal(2);
  795. });
  796. it('getZoomSettings', async () => {
  797. await w.loadURL(url);
  798. const message = { method: 'getZoomSettings' };
  799. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  800. const [,, responseString] = await once(w.webContents, 'console-message');
  801. const response = JSON.parse(responseString);
  802. expect(response).to.deep.equal({
  803. defaultZoomFactor: 1,
  804. mode: 'automatic',
  805. scope: 'per-origin'
  806. });
  807. });
  808. it('setZoomSettings', async () => {
  809. await w.loadURL(url);
  810. const message = { method: 'setZoomSettings', args: [{ mode: 'disabled' }] };
  811. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  812. const [,, responseString] = await once(w.webContents, 'console-message');
  813. const response = JSON.parse(responseString);
  814. expect(response).to.deep.equal({
  815. defaultZoomFactor: 1,
  816. mode: 'disabled',
  817. scope: 'per-tab'
  818. });
  819. });
  820. describe('get', () => {
  821. it('returns tab properties', async () => {
  822. await w.loadURL(url);
  823. const message = { method: 'get' };
  824. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  825. const [,, responseString] = await once(w.webContents, 'console-message');
  826. const response = JSON.parse(responseString);
  827. expect(response).to.have.property('url').that.is.a('string');
  828. expect(response).to.have.property('title').that.is.a('string');
  829. expect(response).to.have.property('active').that.is.a('boolean');
  830. expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
  831. expect(response).to.have.property('discarded').that.is.a('boolean');
  832. expect(response).to.have.property('groupId').that.is.a('number');
  833. expect(response).to.have.property('highlighted').that.is.a('boolean');
  834. expect(response).to.have.property('id').that.is.a('number');
  835. expect(response).to.have.property('incognito').that.is.a('boolean');
  836. expect(response).to.have.property('index').that.is.a('number');
  837. expect(response).to.have.property('pinned').that.is.a('boolean');
  838. expect(response).to.have.property('selected').that.is.a('boolean');
  839. expect(response).to.have.property('windowId').that.is.a('number');
  840. });
  841. it('does not return privileged properties without tabs permission', async () => {
  842. const noPrivilegeSes = session.fromPartition(`persist:${uuid.v4()}`);
  843. await noPrivilegeSes.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'no-privileges'));
  844. w = new BrowserWindow({ show: false, webPreferences: { session: noPrivilegeSes } });
  845. await w.loadURL(url);
  846. w.webContents.executeJavaScript('window.postMessage(\'{}\', \'*\')');
  847. const [,, responseString] = await once(w.webContents, 'console-message');
  848. const response = JSON.parse(responseString);
  849. expect(response).not.to.have.property('url');
  850. expect(response).not.to.have.property('title');
  851. expect(response).to.have.property('active').that.is.a('boolean');
  852. expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
  853. expect(response).to.have.property('discarded').that.is.a('boolean');
  854. expect(response).to.have.property('groupId').that.is.a('number');
  855. expect(response).to.have.property('highlighted').that.is.a('boolean');
  856. expect(response).to.have.property('id').that.is.a('number');
  857. expect(response).to.have.property('incognito').that.is.a('boolean');
  858. expect(response).to.have.property('index').that.is.a('number');
  859. expect(response).to.have.property('pinned').that.is.a('boolean');
  860. expect(response).to.have.property('selected').that.is.a('boolean');
  861. expect(response).to.have.property('windowId').that.is.a('number');
  862. });
  863. });
  864. it('reload', async () => {
  865. await w.loadURL(url);
  866. const message = { method: 'reload' };
  867. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  868. const consoleMessage = once(w.webContents, 'console-message');
  869. const finish = once(w.webContents, 'did-finish-load');
  870. await Promise.all([consoleMessage, finish]).then(([[,, responseString]]) => {
  871. const response = JSON.parse(responseString);
  872. expect(response.status).to.equal('reloaded');
  873. });
  874. });
  875. it('update', async () => {
  876. await w.loadURL(url);
  877. const message = { method: 'update', args: [{ muted: true }] };
  878. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  879. const [,, responseString] = await once(w.webContents, 'console-message');
  880. const response = JSON.parse(responseString);
  881. expect(response).to.have.property('url').that.is.a('string');
  882. expect(response).to.have.property('title').that.is.a('string');
  883. expect(response).to.have.property('active').that.is.a('boolean');
  884. expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
  885. expect(response).to.have.property('discarded').that.is.a('boolean');
  886. expect(response).to.have.property('groupId').that.is.a('number');
  887. expect(response).to.have.property('highlighted').that.is.a('boolean');
  888. expect(response).to.have.property('id').that.is.a('number');
  889. expect(response).to.have.property('incognito').that.is.a('boolean');
  890. expect(response).to.have.property('index').that.is.a('number');
  891. expect(response).to.have.property('pinned').that.is.a('boolean');
  892. expect(response).to.have.property('selected').that.is.a('boolean');
  893. expect(response).to.have.property('windowId').that.is.a('number');
  894. expect(response).to.have.property('mutedInfo').that.is.a('object');
  895. const { mutedInfo } = response;
  896. expect(mutedInfo).to.deep.eq({
  897. muted: true,
  898. reason: 'user'
  899. });
  900. });
  901. describe('query', () => {
  902. it('can query for a tab with specific properties', async () => {
  903. await w.loadURL(url);
  904. expect(w.webContents.isAudioMuted()).to.be.false('muted');
  905. w.webContents.setAudioMuted(true);
  906. expect(w.webContents.isAudioMuted()).to.be.true('not muted');
  907. const message = { method: 'query', args: [{ muted: true }] };
  908. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  909. const [, , responseString] = await once(w.webContents, 'console-message');
  910. const response = JSON.parse(responseString);
  911. expect(response).to.have.lengthOf(1);
  912. const tab = response[0];
  913. expect(tab.mutedInfo).to.deep.equal({
  914. muted: true,
  915. reason: 'user'
  916. });
  917. });
  918. it('only returns tabs in the same session', async () => {
  919. await w.loadURL(url);
  920. w.webContents.setAudioMuted(true);
  921. const sameSessionWin = new BrowserWindow({
  922. show: false,
  923. webPreferences: {
  924. session: customSession
  925. }
  926. });
  927. sameSessionWin.webContents.setAudioMuted(true);
  928. const newSession = session.fromPartition(`persist:${uuid.v4()}`);
  929. const differentSessionWin = new BrowserWindow({
  930. show: false,
  931. webPreferences: {
  932. session: newSession
  933. }
  934. });
  935. differentSessionWin.webContents.setAudioMuted(true);
  936. const message = { method: 'query', args: [{ muted: true }] };
  937. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  938. const [, , responseString] = await once(w.webContents, 'console-message');
  939. const response = JSON.parse(responseString);
  940. expect(response).to.have.lengthOf(2);
  941. for (const tab of response) {
  942. expect(tab.mutedInfo).to.deep.equal({
  943. muted: true,
  944. reason: 'user'
  945. });
  946. }
  947. });
  948. });
  949. });
  950. describe('chrome.scripting', () => {
  951. let customSession: Session;
  952. let w = null as unknown as BrowserWindow;
  953. before(async () => {
  954. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  955. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-scripting'));
  956. });
  957. beforeEach(() => {
  958. w = new BrowserWindow({
  959. show: false,
  960. webPreferences: {
  961. session: customSession,
  962. nodeIntegration: true
  963. }
  964. });
  965. });
  966. afterEach(closeAllWindows);
  967. it('executeScript', async () => {
  968. await w.loadURL(url);
  969. const message = { method: 'executeScript' };
  970. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  971. const updated = await once(w.webContents, 'page-title-updated');
  972. expect(updated[1]).to.equal('HEY HEY HEY');
  973. });
  974. it('registerContentScripts', async () => {
  975. await w.loadURL(url);
  976. const message = { method: 'registerContentScripts' };
  977. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  978. const [,, responseString] = await once(w.webContents, 'console-message');
  979. const response = JSON.parse(responseString);
  980. expect(response).to.be.an('array').with.lengthOf(1);
  981. expect(response[0]).to.deep.equal({
  982. allFrames: false,
  983. id: 'session-script',
  984. js: ['content.js'],
  985. matchOriginAsFallback: false,
  986. matches: ['<all_urls>'],
  987. persistAcrossSessions: false,
  988. runAt: 'document_start',
  989. world: 'ISOLATED'
  990. });
  991. });
  992. it('insertCSS', async () => {
  993. await w.loadURL(url);
  994. const bgBefore = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
  995. expect(bgBefore).to.equal('rgba(0, 0, 0, 0)');
  996. const message = { method: 'insertCSS' };
  997. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  998. const [,, responseString] = await once(w.webContents, 'console-message');
  999. const response = JSON.parse(responseString);
  1000. expect(response.success).to.be.true();
  1001. const bgAfter = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
  1002. expect(bgAfter).to.equal('rgb(255, 0, 0)');
  1003. });
  1004. });
  1005. });
  1006. });