extensions-spec.ts 51 KB

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