extensions-spec.ts 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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 { EUI } = (window as any);
  495. const instance = EUI.InspectorView.InspectorView.instance();
  496. const tabs = instance.tabbedPane.tabs;
  497. const lastPanelId = tabs[tabs.length - 1].id;
  498. instance.showPanel(lastPanelId);
  499. };
  500. devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
  501. showPanelTimeoutId = setTimeout(show, 100);
  502. });
  503. };
  504. showPanelTimeoutId = setTimeout(show, 100);
  505. });
  506. };
  507. // TODO(jkleinsc) fix this flaky test on WOA
  508. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads a devtools extension', async () => {
  509. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  510. customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension'));
  511. const winningMessage = once(ipcMain, 'winning');
  512. const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true, contextIsolation: false } });
  513. await w.loadURL(url);
  514. w.webContents.openDevTools();
  515. showLastDevToolsPanel(w);
  516. await winningMessage;
  517. });
  518. });
  519. describe('chrome extension content scripts', () => {
  520. const fixtures = path.resolve(__dirname, 'fixtures');
  521. const extensionPath = path.resolve(fixtures, 'extensions');
  522. const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name));
  523. const removeAllExtensions = () => {
  524. Object.keys(session.defaultSession.getAllExtensions()).map(extName => {
  525. session.defaultSession.removeExtension(extName);
  526. });
  527. };
  528. let responseIdCounter = 0;
  529. const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => {
  530. return new Promise(resolve => {
  531. const responseId = responseIdCounter++;
  532. ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => {
  533. resolve(result);
  534. });
  535. webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId);
  536. });
  537. };
  538. const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => {
  539. describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => {
  540. let w: BrowserWindow;
  541. describe('supports "run_at" option', () => {
  542. beforeEach(async () => {
  543. await closeWindow(w);
  544. w = new BrowserWindow({
  545. show: false,
  546. width: 400,
  547. height: 400,
  548. webPreferences: {
  549. contextIsolation: contextIsolationEnabled,
  550. sandbox: sandboxEnabled
  551. }
  552. });
  553. });
  554. afterEach(async () => {
  555. removeAllExtensions();
  556. await closeWindow(w);
  557. w = null as unknown as BrowserWindow;
  558. });
  559. it('should run content script at document_start', async () => {
  560. await addExtension('content-script-document-start');
  561. w.webContents.once('dom-ready', async () => {
  562. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  563. expect(result).to.equal('red');
  564. });
  565. w.loadURL(url);
  566. });
  567. it('should run content script at document_idle', async () => {
  568. await addExtension('content-script-document-idle');
  569. w.loadURL(url);
  570. const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor');
  571. expect(result).to.equal('red');
  572. });
  573. it('should run content script at document_end', async () => {
  574. await addExtension('content-script-document-end');
  575. w.webContents.once('did-finish-load', async () => {
  576. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  577. expect(result).to.equal('red');
  578. });
  579. w.loadURL(url);
  580. });
  581. });
  582. describe('supports "all_frames" option', () => {
  583. const contentScript = path.resolve(fixtures, 'extensions/content-script');
  584. const contentPath = path.join(contentScript, 'frame-with-frame.html');
  585. // Computed style values
  586. const COLOR_RED = 'rgb(255, 0, 0)';
  587. const COLOR_BLUE = 'rgb(0, 0, 255)';
  588. const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)';
  589. let server: http.Server;
  590. let port: number;
  591. before(async () => {
  592. server = http.createServer((_, res) => {
  593. fs.readFile(contentPath, (error, content) => {
  594. if (error) {
  595. res.writeHead(500);
  596. res.end(`Failed to load ${contentPath} : ${error.code}`);
  597. } else {
  598. res.writeHead(200, { 'Content-Type': 'text/html' });
  599. res.end(content, 'utf-8');
  600. }
  601. });
  602. });
  603. ({ port, url } = await listen(server));
  604. session.defaultSession.loadExtension(contentScript);
  605. });
  606. after(() => {
  607. session.defaultSession.removeExtension('content-script-test');
  608. });
  609. beforeEach(() => {
  610. w = new BrowserWindow({
  611. show: false,
  612. webPreferences: {
  613. // enable content script injection in subframes
  614. nodeIntegrationInSubFrames: true,
  615. preload: path.join(contentScript, 'all_frames-preload.js')
  616. }
  617. });
  618. });
  619. afterEach(() =>
  620. closeWindow(w).then(() => {
  621. w = null as unknown as BrowserWindow;
  622. })
  623. );
  624. it('applies matching rules in subframes', async () => {
  625. const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2);
  626. w.loadURL(`http://127.0.0.1:${port}`);
  627. const frameEvents = await detailsPromise;
  628. await Promise.all(
  629. frameEvents.map(async frameEvent => {
  630. const [, isMainFrame, , frameRoutingId] = frameEvent;
  631. const result: any = await executeJavaScriptInFrame(
  632. w.webContents,
  633. frameRoutingId,
  634. `(() => {
  635. const a = document.getElementById('all_frames_enabled')
  636. const b = document.getElementById('all_frames_disabled')
  637. return {
  638. enabledColor: getComputedStyle(a).backgroundColor,
  639. disabledColor: getComputedStyle(b).backgroundColor
  640. }
  641. })()`
  642. );
  643. expect(result.enabledColor).to.equal(COLOR_RED);
  644. expect(result.disabledColor).to.equal(isMainFrame ? COLOR_BLUE : COLOR_TRANSPARENT);
  645. })
  646. );
  647. });
  648. });
  649. });
  650. };
  651. generateTests(false, false);
  652. generateTests(false, true);
  653. generateTests(true, false);
  654. generateTests(true, true);
  655. });
  656. describe('extension ui pages', () => {
  657. afterEach(() => {
  658. for (const e of session.defaultSession.getAllExtensions()) {
  659. session.defaultSession.removeExtension(e.id);
  660. }
  661. });
  662. it('loads a ui page of an extension', async () => {
  663. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  664. const w = new BrowserWindow({ show: false });
  665. await w.loadURL(`chrome-extension://${id}/bare-page.html`);
  666. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  667. expect(textContent).to.equal('ui page loaded ok\n');
  668. });
  669. it('can load resources', async () => {
  670. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  671. const w = new BrowserWindow({ show: false });
  672. await w.loadURL(`chrome-extension://${id}/page-script-load.html`);
  673. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  674. expect(textContent).to.equal('script loaded ok\n');
  675. });
  676. });
  677. describe('manifest v3', () => {
  678. it('registers background service worker', async () => {
  679. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  680. const registrationPromise = new Promise<string>(resolve => {
  681. customSession.serviceWorkers.once('registration-completed', (event, { scope }) => resolve(scope));
  682. });
  683. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
  684. const scope = await registrationPromise;
  685. expect(scope).equals(extension.url);
  686. });
  687. it('can run chrome extension APIs', async () => {
  688. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  689. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  690. await customSession.loadExtension(path.join(fixtures, 'extensions', 'mv3-service-worker'));
  691. await w.loadURL(url);
  692. w.webContents.executeJavaScript('window.postMessage(\'fetch-confirmation\', \'*\')');
  693. const [, , responseString] = await once(w.webContents, 'console-message');
  694. const { message } = JSON.parse(responseString);
  695. expect(message).to.equal('Hello from background.js');
  696. });
  697. describe('chrome.i18n', () => {
  698. let customSession: Session;
  699. let w = null as unknown as BrowserWindow;
  700. before(async () => {
  701. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  702. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n', 'v3'));
  703. });
  704. beforeEach(() => {
  705. w = new BrowserWindow({
  706. show: false,
  707. webPreferences: {
  708. session: customSession,
  709. nodeIntegration: true
  710. }
  711. });
  712. });
  713. afterEach(closeAllWindows);
  714. it('getAcceptLanguages', async () => {
  715. await w.loadURL(url);
  716. const message = { method: 'getAcceptLanguages' };
  717. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  718. const [,, responseString] = await once(w.webContents, 'console-message');
  719. const response = JSON.parse(responseString);
  720. expect(response).to.be.an('array').that.is.not.empty('languages array is empty');
  721. });
  722. it('getUILanguage', async () => {
  723. await w.loadURL(url);
  724. const message = { method: 'getUILanguage' };
  725. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  726. const [,, responseString] = await once(w.webContents, 'console-message');
  727. const response = JSON.parse(responseString);
  728. expect(response).to.be.a('string');
  729. });
  730. it('getMessage', async () => {
  731. await w.loadURL(url);
  732. const message = { method: 'getMessage' };
  733. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  734. const [, , responseString] = await once(w.webContents, 'console-message');
  735. const response = JSON.parse(responseString);
  736. expect(response).to.equal('Hola mundo!!');
  737. });
  738. it('detectLanguage', async () => {
  739. await w.loadURL(url);
  740. const greetings = [
  741. 'Ich liebe dich', // German
  742. 'Mahal kita', // Filipino
  743. '愛してます', // Japanese
  744. 'دوستت دارم', // Persian
  745. 'Minä rakastan sinua' // Finnish
  746. ];
  747. const message = { method: 'detectLanguage', args: [greetings] };
  748. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  749. const [, , responseString] = await once(w.webContents, 'console-message');
  750. const response = JSON.parse(responseString);
  751. expect(response).to.be.an('array');
  752. for (const item of response) {
  753. expect(Object.keys(item)).to.deep.equal(['isReliable', 'languages']);
  754. }
  755. const languages = response.map((r: { isReliable: boolean, languages: any[] }) => r.languages[0]);
  756. expect(languages).to.deep.equal([
  757. { language: 'de', percentage: 100 },
  758. { language: 'fil', percentage: 100 },
  759. { language: 'ja', percentage: 100 },
  760. { language: 'ps', percentage: 100 },
  761. { language: 'fi', percentage: 100 }
  762. ]);
  763. });
  764. });
  765. describe('chrome.tabs', () => {
  766. let customSession: Session;
  767. let w = null as unknown as BrowserWindow;
  768. before(async () => {
  769. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  770. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'api-async'));
  771. });
  772. beforeEach(() => {
  773. w = new BrowserWindow({
  774. show: false,
  775. webPreferences: {
  776. session: customSession
  777. }
  778. });
  779. });
  780. afterEach(closeAllWindows);
  781. it('getZoom', async () => {
  782. await w.loadURL(url);
  783. const message = { method: 'getZoom' };
  784. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  785. const [,, responseString] = await once(w.webContents, 'console-message');
  786. const response = JSON.parse(responseString);
  787. expect(response).to.equal(1);
  788. });
  789. it('setZoom', async () => {
  790. await w.loadURL(url);
  791. const message = { method: 'setZoom', args: [2] };
  792. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  793. const [,, responseString] = await once(w.webContents, 'console-message');
  794. const response = JSON.parse(responseString);
  795. expect(response).to.deep.equal(2);
  796. });
  797. it('getZoomSettings', async () => {
  798. await w.loadURL(url);
  799. const message = { method: 'getZoomSettings' };
  800. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  801. const [,, responseString] = await once(w.webContents, 'console-message');
  802. const response = JSON.parse(responseString);
  803. expect(response).to.deep.equal({
  804. defaultZoomFactor: 1,
  805. mode: 'automatic',
  806. scope: 'per-origin'
  807. });
  808. });
  809. it('setZoomSettings', async () => {
  810. await w.loadURL(url);
  811. const message = { method: 'setZoomSettings', args: [{ mode: 'disabled' }] };
  812. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  813. const [,, responseString] = await once(w.webContents, 'console-message');
  814. const response = JSON.parse(responseString);
  815. expect(response).to.deep.equal({
  816. defaultZoomFactor: 1,
  817. mode: 'disabled',
  818. scope: 'per-tab'
  819. });
  820. });
  821. describe('get', () => {
  822. it('returns tab properties', async () => {
  823. await w.loadURL(url);
  824. const message = { method: 'get' };
  825. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  826. const [,, responseString] = await once(w.webContents, 'console-message');
  827. const response = JSON.parse(responseString);
  828. expect(response).to.have.property('url').that.is.a('string');
  829. expect(response).to.have.property('title').that.is.a('string');
  830. expect(response).to.have.property('active').that.is.a('boolean');
  831. expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
  832. expect(response).to.have.property('discarded').that.is.a('boolean');
  833. expect(response).to.have.property('groupId').that.is.a('number');
  834. expect(response).to.have.property('highlighted').that.is.a('boolean');
  835. expect(response).to.have.property('id').that.is.a('number');
  836. expect(response).to.have.property('incognito').that.is.a('boolean');
  837. expect(response).to.have.property('index').that.is.a('number');
  838. expect(response).to.have.property('pinned').that.is.a('boolean');
  839. expect(response).to.have.property('selected').that.is.a('boolean');
  840. expect(response).to.have.property('windowId').that.is.a('number');
  841. });
  842. it('does not return privileged properties without tabs permission', async () => {
  843. const noPrivilegeSes = session.fromPartition(`persist:${uuid.v4()}`);
  844. await noPrivilegeSes.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'no-privileges'));
  845. w = new BrowserWindow({ show: false, webPreferences: { session: noPrivilegeSes } });
  846. await w.loadURL(url);
  847. w.webContents.executeJavaScript('window.postMessage(\'{}\', \'*\')');
  848. const [,, responseString] = await once(w.webContents, 'console-message');
  849. const response = JSON.parse(responseString);
  850. expect(response).not.to.have.property('url');
  851. expect(response).not.to.have.property('title');
  852. expect(response).to.have.property('active').that.is.a('boolean');
  853. expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
  854. expect(response).to.have.property('discarded').that.is.a('boolean');
  855. expect(response).to.have.property('groupId').that.is.a('number');
  856. expect(response).to.have.property('highlighted').that.is.a('boolean');
  857. expect(response).to.have.property('id').that.is.a('number');
  858. expect(response).to.have.property('incognito').that.is.a('boolean');
  859. expect(response).to.have.property('index').that.is.a('number');
  860. expect(response).to.have.property('pinned').that.is.a('boolean');
  861. expect(response).to.have.property('selected').that.is.a('boolean');
  862. expect(response).to.have.property('windowId').that.is.a('number');
  863. });
  864. });
  865. it('reload', async () => {
  866. await w.loadURL(url);
  867. const message = { method: 'reload' };
  868. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  869. const consoleMessage = once(w.webContents, 'console-message');
  870. const finish = once(w.webContents, 'did-finish-load');
  871. await Promise.all([consoleMessage, finish]).then(([[,, responseString]]) => {
  872. const response = JSON.parse(responseString);
  873. expect(response.status).to.equal('reloaded');
  874. });
  875. });
  876. describe('update', () => {
  877. it('can update muted status', async () => {
  878. await w.loadURL(url);
  879. const message = { method: 'update', args: [{ muted: true }] };
  880. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  881. const [,, responseString] = await once(w.webContents, 'console-message');
  882. const response = JSON.parse(responseString);
  883. expect(response).to.have.property('mutedInfo').that.is.a('object');
  884. const { mutedInfo } = response;
  885. expect(mutedInfo).to.deep.eq({
  886. muted: true,
  887. reason: 'user'
  888. });
  889. });
  890. it('fails when navigating to an invalid url', async () => {
  891. await w.loadURL(url);
  892. const message = { method: 'update', args: [{ url: 'chrome://crash' }] };
  893. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  894. const [,, responseString] = await once(w.webContents, 'console-message');
  895. const { error } = JSON.parse(responseString);
  896. expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.');
  897. });
  898. it('fails when navigating to prohibited url', async () => {
  899. await w.loadURL(url);
  900. const message = { method: 'update', args: [{ url: 'chrome://crash' }] };
  901. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  902. const [,, responseString] = await once(w.webContents, 'console-message');
  903. const { error } = JSON.parse(responseString);
  904. expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.');
  905. });
  906. it('fails when navigating to a devtools url without permission', async () => {
  907. await w.loadURL(url);
  908. const message = { method: 'update', args: [{ url: 'devtools://blah' }] };
  909. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  910. const [, , responseString] = await once(w.webContents, 'console-message');
  911. const { error } = JSON.parse(responseString);
  912. expect(error).to.eq('Cannot navigate to a devtools:// page without either the devtools or debugger permission.');
  913. });
  914. it('fails when navigating to a chrome-untrusted url', async () => {
  915. await w.loadURL(url);
  916. const message = { method: 'update', args: [{ url: 'chrome-untrusted://blah' }] };
  917. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  918. const [, , responseString] = await once(w.webContents, 'console-message');
  919. const { error } = JSON.parse(responseString);
  920. expect(error).to.eq('Cannot navigate to a chrome-untrusted:// page.');
  921. });
  922. it('fails when navigating to a file url withotut file access', async () => {
  923. await w.loadURL(url);
  924. const message = { method: 'update', args: [{ url: 'file://blah' }] };
  925. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  926. const [, , responseString] = await once(w.webContents, 'console-message');
  927. const { error } = JSON.parse(responseString);
  928. expect(error).to.eq('Cannot navigate to a file URL without local file access.');
  929. });
  930. });
  931. describe('query', () => {
  932. it('can query for a tab with specific properties', async () => {
  933. await w.loadURL(url);
  934. expect(w.webContents.isAudioMuted()).to.be.false('muted');
  935. w.webContents.setAudioMuted(true);
  936. expect(w.webContents.isAudioMuted()).to.be.true('not muted');
  937. const message = { method: 'query', args: [{ muted: true }] };
  938. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  939. const [, , responseString] = await once(w.webContents, 'console-message');
  940. const response = JSON.parse(responseString);
  941. expect(response).to.have.lengthOf(1);
  942. const tab = response[0];
  943. expect(tab.mutedInfo).to.deep.equal({
  944. muted: true,
  945. reason: 'user'
  946. });
  947. });
  948. it('only returns tabs in the same session', async () => {
  949. await w.loadURL(url);
  950. w.webContents.setAudioMuted(true);
  951. const sameSessionWin = new BrowserWindow({
  952. show: false,
  953. webPreferences: {
  954. session: customSession
  955. }
  956. });
  957. sameSessionWin.webContents.setAudioMuted(true);
  958. const newSession = session.fromPartition(`persist:${uuid.v4()}`);
  959. const differentSessionWin = new BrowserWindow({
  960. show: false,
  961. webPreferences: {
  962. session: newSession
  963. }
  964. });
  965. differentSessionWin.webContents.setAudioMuted(true);
  966. const message = { method: 'query', args: [{ muted: true }] };
  967. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  968. const [, , responseString] = await once(w.webContents, 'console-message');
  969. const response = JSON.parse(responseString);
  970. expect(response).to.have.lengthOf(2);
  971. for (const tab of response) {
  972. expect(tab.mutedInfo).to.deep.equal({
  973. muted: true,
  974. reason: 'user'
  975. });
  976. }
  977. });
  978. });
  979. });
  980. describe('chrome.scripting', () => {
  981. let customSession: Session;
  982. let w = null as unknown as BrowserWindow;
  983. before(async () => {
  984. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  985. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-scripting'));
  986. });
  987. beforeEach(() => {
  988. w = new BrowserWindow({
  989. show: false,
  990. webPreferences: {
  991. session: customSession,
  992. nodeIntegration: true
  993. }
  994. });
  995. });
  996. afterEach(closeAllWindows);
  997. it('executeScript', async () => {
  998. await w.loadURL(url);
  999. const message = { method: 'executeScript' };
  1000. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  1001. const updated = await once(w.webContents, 'page-title-updated');
  1002. expect(updated[1]).to.equal('HEY HEY HEY');
  1003. });
  1004. it('registerContentScripts', async () => {
  1005. await w.loadURL(url);
  1006. const message = { method: 'registerContentScripts' };
  1007. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  1008. const [,, responseString] = await once(w.webContents, 'console-message');
  1009. const response = JSON.parse(responseString);
  1010. expect(response).to.be.an('array').with.lengthOf(1);
  1011. expect(response[0]).to.deep.equal({
  1012. allFrames: false,
  1013. id: 'session-script',
  1014. js: ['content.js'],
  1015. matchOriginAsFallback: false,
  1016. matches: ['<all_urls>'],
  1017. persistAcrossSessions: false,
  1018. runAt: 'document_start',
  1019. world: 'ISOLATED'
  1020. });
  1021. });
  1022. it('insertCSS', async () => {
  1023. await w.loadURL(url);
  1024. const bgBefore = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
  1025. expect(bgBefore).to.equal('rgba(0, 0, 0, 0)');
  1026. const message = { method: 'insertCSS' };
  1027. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  1028. const [,, responseString] = await once(w.webContents, 'console-message');
  1029. const response = JSON.parse(responseString);
  1030. expect(response.success).to.be.true();
  1031. const bgAfter = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
  1032. expect(bgAfter).to.equal('rgb(255, 0, 0)');
  1033. });
  1034. });
  1035. });
  1036. });