extensions-spec.ts 53 KB

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