extensions-spec.ts 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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/promises';
  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(await fs.readFile(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(async (_, res) => {
  593. try {
  594. const content = await fs.readFile(contentPath, 'utf-8');
  595. res.writeHead(200, { 'Content-Type': 'text/html' });
  596. res.end(content, 'utf-8');
  597. } catch (error) {
  598. res.writeHead(500);
  599. res.end(`Failed to load ${contentPath} : ${(error as NodeJS.ErrnoException).code}`);
  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. // chrome.action is not supported in Electron. These tests only ensure
  765. // it does not explode.
  766. describe('chrome.action', () => {
  767. let customSession: Session;
  768. let w = null as unknown as BrowserWindow;
  769. before(async () => {
  770. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  771. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-action-fail'));
  772. });
  773. beforeEach(() => {
  774. w = new BrowserWindow({
  775. show: false,
  776. webPreferences: {
  777. session: customSession
  778. }
  779. });
  780. });
  781. afterEach(closeAllWindows);
  782. it('isEnabled', async () => {
  783. await w.loadURL(url);
  784. const message = { method: 'isEnabled' };
  785. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  786. const [, , responseString] = await once(w.webContents, 'console-message');
  787. const response = JSON.parse(responseString);
  788. expect(response).to.equal(false);
  789. });
  790. it('setIcon', async () => {
  791. await w.loadURL(url);
  792. const message = { method: 'setIcon' };
  793. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  794. const [, , responseString] = await once(w.webContents, 'console-message');
  795. const response = JSON.parse(responseString);
  796. expect(response).to.equal(null);
  797. });
  798. it('getBadgeText', async () => {
  799. await w.loadURL(url);
  800. const message = { method: 'getBadgeText' };
  801. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  802. const [, , responseString] = await once(w.webContents, 'console-message');
  803. const response = JSON.parse(responseString);
  804. expect(response).to.equal('');
  805. });
  806. });
  807. describe('chrome.tabs', () => {
  808. let customSession: Session;
  809. let w = null as unknown as BrowserWindow;
  810. before(async () => {
  811. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  812. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'api-async'));
  813. });
  814. beforeEach(() => {
  815. w = new BrowserWindow({
  816. show: false,
  817. webPreferences: {
  818. session: customSession
  819. }
  820. });
  821. });
  822. afterEach(closeAllWindows);
  823. it('getZoom', async () => {
  824. await w.loadURL(url);
  825. const message = { method: 'getZoom' };
  826. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  827. const [,, responseString] = await once(w.webContents, 'console-message');
  828. const response = JSON.parse(responseString);
  829. expect(response).to.equal(1);
  830. });
  831. it('setZoom', async () => {
  832. await w.loadURL(url);
  833. const message = { method: 'setZoom', args: [2] };
  834. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  835. const [,, responseString] = await once(w.webContents, 'console-message');
  836. const response = JSON.parse(responseString);
  837. expect(response).to.deep.equal(2);
  838. });
  839. it('getZoomSettings', async () => {
  840. await w.loadURL(url);
  841. const message = { method: 'getZoomSettings' };
  842. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  843. const [,, responseString] = await once(w.webContents, 'console-message');
  844. const response = JSON.parse(responseString);
  845. expect(response).to.deep.equal({
  846. defaultZoomFactor: 1,
  847. mode: 'automatic',
  848. scope: 'per-origin'
  849. });
  850. });
  851. it('setZoomSettings', async () => {
  852. await w.loadURL(url);
  853. const message = { method: 'setZoomSettings', args: [{ mode: 'disabled' }] };
  854. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  855. const [,, responseString] = await once(w.webContents, 'console-message');
  856. const response = JSON.parse(responseString);
  857. expect(response).to.deep.equal({
  858. defaultZoomFactor: 1,
  859. mode: 'disabled',
  860. scope: 'per-tab'
  861. });
  862. });
  863. describe('get', () => {
  864. it('returns tab properties', async () => {
  865. await w.loadURL(url);
  866. const message = { method: 'get' };
  867. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  868. const [,, responseString] = await once(w.webContents, 'console-message');
  869. const response = JSON.parse(responseString);
  870. expect(response).to.have.property('url').that.is.a('string');
  871. expect(response).to.have.property('title').that.is.a('string');
  872. expect(response).to.have.property('active').that.is.a('boolean');
  873. expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
  874. expect(response).to.have.property('discarded').that.is.a('boolean');
  875. expect(response).to.have.property('groupId').that.is.a('number');
  876. expect(response).to.have.property('highlighted').that.is.a('boolean');
  877. expect(response).to.have.property('id').that.is.a('number');
  878. expect(response).to.have.property('incognito').that.is.a('boolean');
  879. expect(response).to.have.property('index').that.is.a('number');
  880. expect(response).to.have.property('pinned').that.is.a('boolean');
  881. expect(response).to.have.property('selected').that.is.a('boolean');
  882. expect(response).to.have.property('windowId').that.is.a('number');
  883. });
  884. it('does not return privileged properties without tabs permission', async () => {
  885. const noPrivilegeSes = session.fromPartition(`persist:${uuid.v4()}`);
  886. await noPrivilegeSes.loadExtension(path.join(fixtures, 'extensions', 'chrome-tabs', 'no-privileges'));
  887. w = new BrowserWindow({ show: false, webPreferences: { session: noPrivilegeSes } });
  888. await w.loadURL(url);
  889. w.webContents.executeJavaScript('window.postMessage(\'{}\', \'*\')');
  890. const [,, responseString] = await once(w.webContents, 'console-message');
  891. const response = JSON.parse(responseString);
  892. expect(response).not.to.have.property('url');
  893. expect(response).not.to.have.property('title');
  894. expect(response).to.have.property('active').that.is.a('boolean');
  895. expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
  896. expect(response).to.have.property('discarded').that.is.a('boolean');
  897. expect(response).to.have.property('groupId').that.is.a('number');
  898. expect(response).to.have.property('highlighted').that.is.a('boolean');
  899. expect(response).to.have.property('id').that.is.a('number');
  900. expect(response).to.have.property('incognito').that.is.a('boolean');
  901. expect(response).to.have.property('index').that.is.a('number');
  902. expect(response).to.have.property('pinned').that.is.a('boolean');
  903. expect(response).to.have.property('selected').that.is.a('boolean');
  904. expect(response).to.have.property('windowId').that.is.a('number');
  905. });
  906. });
  907. it('reload', async () => {
  908. await w.loadURL(url);
  909. const message = { method: 'reload' };
  910. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  911. const consoleMessage = once(w.webContents, 'console-message');
  912. const finish = once(w.webContents, 'did-finish-load');
  913. await Promise.all([consoleMessage, finish]).then(([[,, responseString]]) => {
  914. const response = JSON.parse(responseString);
  915. expect(response.status).to.equal('reloaded');
  916. });
  917. });
  918. describe('update', () => {
  919. it('can update muted status', async () => {
  920. await w.loadURL(url);
  921. const message = { method: 'update', args: [{ muted: true }] };
  922. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  923. const [,, responseString] = await once(w.webContents, 'console-message');
  924. const response = JSON.parse(responseString);
  925. expect(response).to.have.property('mutedInfo').that.is.a('object');
  926. const { mutedInfo } = response;
  927. expect(mutedInfo).to.deep.eq({
  928. muted: true,
  929. reason: 'user'
  930. });
  931. });
  932. it('fails when navigating to an invalid url', async () => {
  933. await w.loadURL(url);
  934. const message = { method: 'update', args: [{ url: 'chrome://crash' }] };
  935. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  936. const [,, responseString] = await once(w.webContents, 'console-message');
  937. const { error } = JSON.parse(responseString);
  938. expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.');
  939. });
  940. it('fails when navigating to prohibited url', async () => {
  941. await w.loadURL(url);
  942. const message = { method: 'update', args: [{ url: 'chrome://crash' }] };
  943. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  944. const [,, responseString] = await once(w.webContents, 'console-message');
  945. const { error } = JSON.parse(responseString);
  946. expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.');
  947. });
  948. it('fails when navigating to a devtools url without permission', async () => {
  949. await w.loadURL(url);
  950. const message = { method: 'update', args: [{ url: 'devtools://blah' }] };
  951. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  952. const [, , responseString] = await once(w.webContents, 'console-message');
  953. const { error } = JSON.parse(responseString);
  954. expect(error).to.eq('Cannot navigate to a devtools:// page without either the devtools or debugger permission.');
  955. });
  956. it('fails when navigating to a chrome-untrusted url', async () => {
  957. await w.loadURL(url);
  958. const message = { method: 'update', args: [{ url: 'chrome-untrusted://blah' }] };
  959. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  960. const [, , responseString] = await once(w.webContents, 'console-message');
  961. const { error } = JSON.parse(responseString);
  962. expect(error).to.eq('Cannot navigate to a chrome-untrusted:// page.');
  963. });
  964. it('fails when navigating to a file url withotut file access', async () => {
  965. await w.loadURL(url);
  966. const message = { method: 'update', args: [{ url: 'file://blah' }] };
  967. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  968. const [, , responseString] = await once(w.webContents, 'console-message');
  969. const { error } = JSON.parse(responseString);
  970. expect(error).to.eq('Cannot navigate to a file URL without local file access.');
  971. });
  972. });
  973. describe('query', () => {
  974. it('can query for a tab with specific properties', async () => {
  975. await w.loadURL(url);
  976. expect(w.webContents.isAudioMuted()).to.be.false('muted');
  977. w.webContents.setAudioMuted(true);
  978. expect(w.webContents.isAudioMuted()).to.be.true('not muted');
  979. const message = { method: 'query', args: [{ muted: true }] };
  980. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  981. const [, , responseString] = await once(w.webContents, 'console-message');
  982. const response = JSON.parse(responseString);
  983. expect(response).to.have.lengthOf(1);
  984. const tab = response[0];
  985. expect(tab.mutedInfo).to.deep.equal({
  986. muted: true,
  987. reason: 'user'
  988. });
  989. });
  990. it('only returns tabs in the same session', async () => {
  991. await w.loadURL(url);
  992. w.webContents.setAudioMuted(true);
  993. const sameSessionWin = new BrowserWindow({
  994. show: false,
  995. webPreferences: {
  996. session: customSession
  997. }
  998. });
  999. sameSessionWin.webContents.setAudioMuted(true);
  1000. const newSession = session.fromPartition(`persist:${uuid.v4()}`);
  1001. const differentSessionWin = new BrowserWindow({
  1002. show: false,
  1003. webPreferences: {
  1004. session: newSession
  1005. }
  1006. });
  1007. differentSessionWin.webContents.setAudioMuted(true);
  1008. const message = { method: 'query', args: [{ muted: true }] };
  1009. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  1010. const [, , responseString] = await once(w.webContents, 'console-message');
  1011. const response = JSON.parse(responseString);
  1012. expect(response).to.have.lengthOf(2);
  1013. for (const tab of response) {
  1014. expect(tab.mutedInfo).to.deep.equal({
  1015. muted: true,
  1016. reason: 'user'
  1017. });
  1018. }
  1019. });
  1020. });
  1021. });
  1022. describe('chrome.scripting', () => {
  1023. let customSession: Session;
  1024. let w = null as unknown as BrowserWindow;
  1025. before(async () => {
  1026. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  1027. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-scripting'));
  1028. });
  1029. beforeEach(() => {
  1030. w = new BrowserWindow({
  1031. show: false,
  1032. webPreferences: {
  1033. session: customSession,
  1034. nodeIntegration: true
  1035. }
  1036. });
  1037. });
  1038. afterEach(closeAllWindows);
  1039. it('executeScript', async () => {
  1040. await w.loadURL(url);
  1041. const message = { method: 'executeScript' };
  1042. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  1043. const updated = await once(w.webContents, 'page-title-updated');
  1044. expect(updated[1]).to.equal('HEY HEY HEY');
  1045. });
  1046. it('registerContentScripts', async () => {
  1047. await w.loadURL(url);
  1048. const message = { method: 'registerContentScripts' };
  1049. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  1050. const [,, responseString] = await once(w.webContents, 'console-message');
  1051. const response = JSON.parse(responseString);
  1052. expect(response).to.be.an('array').with.lengthOf(1);
  1053. expect(response[0]).to.deep.equal({
  1054. allFrames: false,
  1055. id: 'session-script',
  1056. js: ['content.js'],
  1057. matchOriginAsFallback: false,
  1058. matches: ['<all_urls>'],
  1059. persistAcrossSessions: false,
  1060. runAt: 'document_start',
  1061. world: 'ISOLATED'
  1062. });
  1063. });
  1064. it('insertCSS', async () => {
  1065. await w.loadURL(url);
  1066. const bgBefore = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
  1067. expect(bgBefore).to.equal('rgba(0, 0, 0, 0)');
  1068. const message = { method: 'insertCSS' };
  1069. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  1070. const [,, responseString] = await once(w.webContents, 'console-message');
  1071. const response = JSON.parse(responseString);
  1072. expect(response.success).to.be.true();
  1073. const bgAfter = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).backgroundColor');
  1074. expect(bgAfter).to.equal('rgb(255, 0, 0)');
  1075. });
  1076. });
  1077. });
  1078. });