extensions-spec.ts 53 KB

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