extensions-spec.ts 52 KB

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