extensions-spec.ts 52 KB

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