extensions-spec.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. import { expect } from 'chai';
  2. import { app, session, BrowserWindow, ipcMain, WebContents, Extension, Session } from 'electron/main';
  3. import { closeAllWindows, closeWindow } from './window-helpers';
  4. import * as http from 'http';
  5. import { AddressInfo } from 'net';
  6. import * as path from 'path';
  7. import * as fs from 'fs';
  8. import * as WebSocket from 'ws';
  9. import { emittedOnce, emittedNTimes } from './events-helpers';
  10. const uuid = require('uuid');
  11. const fixtures = path.join(__dirname, 'fixtures');
  12. describe('chrome extensions', () => {
  13. const emptyPage = '<script>console.log("loaded")</script>';
  14. // NB. extensions are only allowed on http://, https:// and ftp:// (!) urls by default.
  15. let server: http.Server;
  16. let url: string;
  17. let port: string;
  18. before(async () => {
  19. server = http.createServer((req, res) => {
  20. if (req.url === '/cors') {
  21. res.setHeader('Access-Control-Allow-Origin', 'http://example.com');
  22. }
  23. res.end(emptyPage);
  24. });
  25. const wss = new WebSocket.Server({ noServer: true });
  26. wss.on('connection', function connection (ws) {
  27. ws.on('message', function incoming (message) {
  28. if (message === 'foo') {
  29. ws.send('bar');
  30. }
  31. });
  32. });
  33. await new Promise(resolve => server.listen(0, '127.0.0.1', () => {
  34. port = String((server.address() as AddressInfo).port);
  35. url = `http://127.0.0.1:${port}`;
  36. resolve();
  37. }));
  38. });
  39. after(() => {
  40. server.close();
  41. });
  42. afterEach(closeAllWindows);
  43. afterEach(() => {
  44. session.defaultSession.getAllExtensions().forEach((e: any) => {
  45. session.defaultSession.removeExtension(e.id);
  46. });
  47. });
  48. it('does not crash when using chrome.management', async () => {
  49. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  50. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  51. w.loadURL('about:blank');
  52. await emittedOnce(w.webContents, 'dom-ready');
  53. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  54. const args: any = await emittedOnce(app, 'web-contents-created');
  55. const wc: Electron.WebContents = args[1];
  56. await expect(wc.executeJavaScript(`
  57. (() => {
  58. return new Promise((resolve) => {
  59. chrome.management.getSelf((info) => {
  60. resolve(info);
  61. });
  62. })
  63. })();
  64. `)).to.eventually.have.property('id');
  65. });
  66. it('can open WebSQLDatabase in a background page', async () => {
  67. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  68. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  69. w.loadURL('about:blank');
  70. await emittedOnce(w.webContents, 'dom-ready');
  71. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  72. const args: any = await emittedOnce(app, 'web-contents-created');
  73. const wc: Electron.WebContents = args[1];
  74. await expect(wc.executeJavaScript('(()=>{try{openDatabase("t", "1.0", "test", 2e5);return true;}catch(e){throw e}})()')).to.not.be.rejected();
  75. });
  76. function fetch (contents: WebContents, url: string) {
  77. return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
  78. }
  79. it('bypasses CORS in requests made from extensions', async () => {
  80. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  81. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } });
  82. const extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  83. w.loadURL(`${extension.url}bare-page.html`);
  84. await emittedOnce(w.webContents, 'dom-ready');
  85. await expect(fetch(w.webContents, `${url}/cors`)).to.not.be.rejectedWith(TypeError);
  86. });
  87. it('loads an extension', async () => {
  88. // NB. we have to use a persist: session (i.e. non-OTR) because the
  89. // extension registry is redirected to the main session. so installing an
  90. // extension in an in-memory session results in it being installed in the
  91. // default session.
  92. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  93. await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  94. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  95. w.loadURL(url);
  96. await emittedOnce(w.webContents, 'dom-ready');
  97. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  98. expect(bg).to.equal('red');
  99. });
  100. it('does not crash when failing to load an extension', async () => {
  101. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  102. const promise = customSession.loadExtension(path.join(fixtures, 'extensions', 'load-error'));
  103. await expect(promise).to.eventually.be.rejected();
  104. });
  105. it('serializes a loaded extension', async () => {
  106. const extensionPath = path.join(fixtures, 'extensions', 'red-bg');
  107. const manifest = JSON.parse(fs.readFileSync(path.join(extensionPath, 'manifest.json'), 'utf-8'));
  108. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  109. const extension = await customSession.loadExtension(extensionPath);
  110. expect(extension.id).to.be.a('string');
  111. expect(extension.name).to.be.a('string');
  112. expect(extension.path).to.be.a('string');
  113. expect(extension.version).to.be.a('string');
  114. expect(extension.url).to.be.a('string');
  115. expect(extension.manifest).to.deep.equal(manifest);
  116. });
  117. it('removes an extension', async () => {
  118. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  119. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  120. {
  121. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  122. await w.loadURL(url);
  123. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  124. expect(bg).to.equal('red');
  125. }
  126. customSession.removeExtension(id);
  127. {
  128. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  129. await w.loadURL(url);
  130. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  131. expect(bg).to.equal('');
  132. }
  133. });
  134. it('lists loaded extensions in getAllExtensions', async () => {
  135. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  136. const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  137. expect(customSession.getAllExtensions()).to.deep.equal([e]);
  138. customSession.removeExtension(e.id);
  139. expect(customSession.getAllExtensions()).to.deep.equal([]);
  140. });
  141. it('gets an extension by id', async () => {
  142. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  143. const e = await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  144. expect(customSession.getExtension(e.id)).to.deep.equal(e);
  145. });
  146. it('confines an extension to the session it was loaded in', async () => {
  147. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  148. await customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'));
  149. const w = new BrowserWindow({ show: false }); // not in the session
  150. w.loadURL(url);
  151. await emittedOnce(w.webContents, 'dom-ready');
  152. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  153. expect(bg).to.equal('');
  154. });
  155. it('loading an extension in a temporary session throws an error', async () => {
  156. const customSession = session.fromPartition(uuid.v4());
  157. await expect(customSession.loadExtension(path.join(fixtures, 'extensions', 'red-bg'))).to.eventually.be.rejectedWith('Extensions cannot be loaded in a temporary session');
  158. });
  159. describe('chrome.i18n', () => {
  160. let w: BrowserWindow;
  161. let extension: Extension;
  162. const exec = async (name: string) => {
  163. const p = emittedOnce(ipcMain, 'success');
  164. await w.webContents.executeJavaScript(`exec('${name}')`);
  165. const [, result] = await p;
  166. return result;
  167. };
  168. beforeEach(async () => {
  169. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  170. extension = await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-i18n'));
  171. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  172. w.loadURL(url);
  173. await emittedOnce(w.webContents, 'dom-ready');
  174. });
  175. it('getAcceptLanguages()', async () => {
  176. const result = await exec('getAcceptLanguages');
  177. expect(result).to.be.an('array').and.deep.equal(['en-US']);
  178. });
  179. it('getMessage()', async () => {
  180. const result = await exec('getMessage');
  181. expect(result.id).to.be.a('string').and.equal(extension.id);
  182. expect(result.name).to.be.a('string').and.equal('chrome-i18n');
  183. });
  184. });
  185. describe('chrome.runtime', () => {
  186. let content: any;
  187. before(async () => {
  188. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  189. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-runtime'));
  190. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  191. try {
  192. w.loadURL(url);
  193. await emittedOnce(w.webContents, 'dom-ready');
  194. content = JSON.parse(await w.webContents.executeJavaScript('document.documentElement.textContent'));
  195. expect(content).to.be.an('object');
  196. } finally {
  197. w.destroy();
  198. }
  199. });
  200. it('getManifest()', () => {
  201. expect(content.manifest).to.be.an('object').with.property('name', 'chrome-runtime');
  202. });
  203. it('id', () => {
  204. expect(content.id).to.be.a('string').with.lengthOf(32);
  205. });
  206. it('getURL()', () => {
  207. expect(content.url).to.be.a('string').and.match(/^chrome-extension:\/\/.*main.js$/);
  208. });
  209. });
  210. describe('chrome.storage', () => {
  211. it('stores and retrieves a key', async () => {
  212. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  213. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-storage'));
  214. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  215. try {
  216. const p = emittedOnce(ipcMain, 'storage-success');
  217. await w.loadURL(url);
  218. const [, v] = await p;
  219. expect(v).to.equal('value');
  220. } finally {
  221. w.destroy();
  222. }
  223. });
  224. });
  225. describe('chrome.webRequest', () => {
  226. function fetch (contents: WebContents, url: string) {
  227. return contents.executeJavaScript(`fetch(${JSON.stringify(url)})`);
  228. }
  229. let customSession: Session;
  230. let w: BrowserWindow;
  231. beforeEach(() => {
  232. customSession = session.fromPartition(`persist:${uuid.v4()}`);
  233. w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true, contextIsolation: true } });
  234. });
  235. describe('onBeforeRequest', () => {
  236. it('can cancel http requests', async () => {
  237. await w.loadURL(url);
  238. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
  239. await expect(fetch(w.webContents, url)).to.eventually.be.rejectedWith(TypeError);
  240. });
  241. it('does not cancel http requests when no extension loaded', async () => {
  242. await w.loadURL(url);
  243. await expect(fetch(w.webContents, url)).to.not.be.rejectedWith(TypeError);
  244. });
  245. });
  246. it('does not take precedence over Electron webRequest - http', async () => {
  247. return new Promise((resolve) => {
  248. (async () => {
  249. customSession.webRequest.onBeforeRequest((details, callback) => {
  250. resolve();
  251. callback({ cancel: true });
  252. });
  253. await w.loadURL(url);
  254. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest'));
  255. fetch(w.webContents, url);
  256. })();
  257. });
  258. });
  259. it('does not take precedence over Electron webRequest - WebSocket', () => {
  260. return new Promise((resolve) => {
  261. (async () => {
  262. customSession.webRequest.onBeforeSendHeaders(() => {
  263. resolve();
  264. });
  265. await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port } });
  266. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
  267. })();
  268. });
  269. });
  270. describe('WebSocket', () => {
  271. it('can be proxied', async () => {
  272. await w.loadFile(path.join(fixtures, 'api', 'webrequest.html'), { query: { port } });
  273. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-webRequest-wss'));
  274. customSession.webRequest.onSendHeaders((details) => {
  275. if (details.url.startsWith('ws://')) {
  276. expect(details.requestHeaders.foo).be.equal('bar');
  277. }
  278. });
  279. });
  280. });
  281. });
  282. describe('chrome.tabs', () => {
  283. it('executeScript', async () => {
  284. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  285. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  286. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  287. await w.loadURL(url);
  288. const message = { method: 'executeScript', args: ['1 + 2'] };
  289. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  290. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  291. const response = JSON.parse(responseString);
  292. expect(response).to.equal(3);
  293. });
  294. it('connect', async () => {
  295. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  296. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  297. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  298. await w.loadURL(url);
  299. const portName = uuid.v4();
  300. const message = { method: 'connectTab', args: [portName] };
  301. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  302. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  303. const response = responseString.split(',');
  304. expect(response[0]).to.equal(portName);
  305. expect(response[1]).to.equal('howdy');
  306. });
  307. it('sendMessage receives the response', async function () {
  308. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  309. await customSession.loadExtension(path.join(fixtures, 'extensions', 'chrome-api'));
  310. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  311. await w.loadURL(url);
  312. const message = { method: 'sendMessage', args: ['Hello World!'] };
  313. w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
  314. const [,, responseString] = await emittedOnce(w.webContents, 'console-message');
  315. const response = JSON.parse(responseString);
  316. expect(response.message).to.equal('Hello World!');
  317. expect(response.tabId).to.equal(w.webContents.id);
  318. });
  319. });
  320. describe('background pages', () => {
  321. it('loads a lazy background page when sending a message', async () => {
  322. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  323. await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  324. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, nodeIntegration: true } });
  325. try {
  326. w.loadURL(url);
  327. const [, resp] = await emittedOnce(ipcMain, 'bg-page-message-response');
  328. expect(resp.message).to.deep.equal({ some: 'message' });
  329. expect(resp.sender.id).to.be.a('string');
  330. expect(resp.sender.origin).to.equal(url);
  331. expect(resp.sender.url).to.equal(url + '/');
  332. } finally {
  333. w.destroy();
  334. }
  335. });
  336. it('can use extension.getBackgroundPage from a ui page', async () => {
  337. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  338. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  339. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  340. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  341. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  342. expect(receivedMessage).to.deep.equal({ some: 'message' });
  343. });
  344. it('can use extension.getBackgroundPage from a ui page', async () => {
  345. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  346. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  347. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  348. await w.loadURL(`chrome-extension://${id}/page-get-background.html`);
  349. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  350. expect(receivedMessage).to.deep.equal({ some: 'message' });
  351. });
  352. it('can use runtime.getBackgroundPage from a ui page', async () => {
  353. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  354. const { id } = await customSession.loadExtension(path.join(fixtures, 'extensions', 'lazy-background-page'));
  355. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  356. await w.loadURL(`chrome-extension://${id}/page-runtime-get-background.html`);
  357. const receivedMessage = await w.webContents.executeJavaScript('window.completionPromise');
  358. expect(receivedMessage).to.deep.equal({ some: 'message' });
  359. });
  360. it('has session in background page', async () => {
  361. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  362. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  363. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  364. const promise = emittedOnce(app, 'web-contents-created');
  365. await w.loadURL('about:blank');
  366. const [, bgPageContents] = await promise;
  367. expect(bgPageContents.session).to.not.equal(undefined);
  368. });
  369. it('can open devtools of background page', async () => {
  370. const customSession = session.fromPartition(`persist:${require('uuid').v4()}`);
  371. await customSession.loadExtension(path.join(fixtures, 'extensions', 'persistent-background-page'));
  372. const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  373. const promise = emittedOnce(app, 'web-contents-created');
  374. await w.loadURL('about:blank');
  375. const [, bgPageContents] = await promise;
  376. expect(bgPageContents.getType()).to.equal('backgroundPage');
  377. bgPageContents.openDevTools();
  378. bgPageContents.closeDevTools();
  379. });
  380. });
  381. describe('devtools extensions', () => {
  382. let showPanelTimeoutId: any = null;
  383. afterEach(() => {
  384. if (showPanelTimeoutId) clearTimeout(showPanelTimeoutId);
  385. });
  386. const showLastDevToolsPanel = (w: BrowserWindow) => {
  387. w.webContents.once('devtools-opened', () => {
  388. const show = () => {
  389. if (w == null || w.isDestroyed()) return;
  390. const { devToolsWebContents } = w as unknown as { devToolsWebContents: WebContents | undefined };
  391. if (devToolsWebContents == null || devToolsWebContents.isDestroyed()) {
  392. return;
  393. }
  394. const showLastPanel = () => {
  395. // this is executed in the devtools context, where UI is a global
  396. const { UI } = (window as any);
  397. const lastPanelId = UI.inspectorView._tabbedPane._tabs.peekLast().id;
  398. UI.inspectorView.showPanel(lastPanelId);
  399. };
  400. devToolsWebContents.executeJavaScript(`(${showLastPanel})()`, false).then(() => {
  401. showPanelTimeoutId = setTimeout(show, 100);
  402. });
  403. };
  404. showPanelTimeoutId = setTimeout(show, 100);
  405. });
  406. };
  407. it('loads a devtools extension', async () => {
  408. const customSession = session.fromPartition(`persist:${uuid.v4()}`);
  409. customSession.loadExtension(path.join(fixtures, 'extensions', 'devtools-extension'));
  410. const winningMessage = emittedOnce(ipcMain, 'winning');
  411. const w = new BrowserWindow({ show: true, webPreferences: { session: customSession, nodeIntegration: true } });
  412. await w.loadURL(url);
  413. w.webContents.openDevTools();
  414. showLastDevToolsPanel(w);
  415. await winningMessage;
  416. });
  417. });
  418. describe('deprecation shims', () => {
  419. it('loads an extension through BrowserWindow.addExtension', async () => {
  420. BrowserWindow.addExtension(path.join(fixtures, 'extensions', 'red-bg'));
  421. const w = new BrowserWindow({ show: false });
  422. await w.loadURL(url);
  423. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  424. expect(bg).to.equal('red');
  425. });
  426. it('loads an extension through BrowserWindow.addDevToolsExtension', async () => {
  427. BrowserWindow.addDevToolsExtension(path.join(fixtures, 'extensions', 'red-bg'));
  428. const w = new BrowserWindow({ show: false });
  429. await w.loadURL(url);
  430. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  431. expect(bg).to.equal('red');
  432. });
  433. it('removes an extension through BrowserWindow.removeExtension', async () => {
  434. await (BrowserWindow.addExtension(path.join(fixtures, 'extensions', 'red-bg')) as any);
  435. BrowserWindow.removeExtension('red-bg');
  436. const w = new BrowserWindow({ show: false });
  437. await w.loadURL(url);
  438. const bg = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  439. expect(bg).to.equal('');
  440. });
  441. });
  442. describe('chrome extension content scripts', () => {
  443. const fixtures = path.resolve(__dirname, 'fixtures');
  444. const extensionPath = path.resolve(fixtures, 'extensions');
  445. const addExtension = (name: string) => session.defaultSession.loadExtension(path.resolve(extensionPath, name));
  446. const removeAllExtensions = () => {
  447. Object.keys(session.defaultSession.getAllExtensions()).map(extName => {
  448. session.defaultSession.removeExtension(extName);
  449. });
  450. };
  451. let responseIdCounter = 0;
  452. const executeJavaScriptInFrame = (webContents: WebContents, frameRoutingId: number, code: string) => {
  453. return new Promise(resolve => {
  454. const responseId = responseIdCounter++;
  455. ipcMain.once(`executeJavaScriptInFrame_${responseId}`, (event, result) => {
  456. resolve(result);
  457. });
  458. webContents.send('executeJavaScriptInFrame', frameRoutingId, code, responseId);
  459. });
  460. };
  461. const generateTests = (sandboxEnabled: boolean, contextIsolationEnabled: boolean) => {
  462. describe(`with sandbox ${sandboxEnabled ? 'enabled' : 'disabled'} and context isolation ${contextIsolationEnabled ? 'enabled' : 'disabled'}`, () => {
  463. let w: BrowserWindow;
  464. describe('supports "run_at" option', () => {
  465. beforeEach(async () => {
  466. await closeWindow(w);
  467. w = new BrowserWindow({
  468. show: false,
  469. width: 400,
  470. height: 400,
  471. webPreferences: {
  472. contextIsolation: contextIsolationEnabled,
  473. sandbox: sandboxEnabled
  474. }
  475. });
  476. });
  477. afterEach(() => {
  478. removeAllExtensions();
  479. return closeWindow(w).then(() => { w = null as unknown as BrowserWindow; });
  480. });
  481. it('should run content script at document_start', async () => {
  482. await addExtension('content-script-document-start');
  483. w.webContents.once('dom-ready', async () => {
  484. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  485. expect(result).to.equal('red');
  486. });
  487. w.loadURL(url);
  488. });
  489. it('should run content script at document_idle', async () => {
  490. await addExtension('content-script-document-idle');
  491. w.loadURL(url);
  492. const result = await w.webContents.executeJavaScript('document.body.style.backgroundColor');
  493. expect(result).to.equal('red');
  494. });
  495. it('should run content script at document_end', async () => {
  496. await addExtension('content-script-document-end');
  497. w.webContents.once('did-finish-load', async () => {
  498. const result = await w.webContents.executeJavaScript('document.documentElement.style.backgroundColor');
  499. expect(result).to.equal('red');
  500. });
  501. w.loadURL(url);
  502. });
  503. });
  504. // TODO(nornagon): real extensions don't load on file: urls, so this
  505. // test needs to be updated to serve its content over http.
  506. describe.skip('supports "all_frames" option', () => {
  507. const contentScript = path.resolve(fixtures, 'extensions/content-script');
  508. // Computed style values
  509. const COLOR_RED = 'rgb(255, 0, 0)';
  510. const COLOR_BLUE = 'rgb(0, 0, 255)';
  511. const COLOR_TRANSPARENT = 'rgba(0, 0, 0, 0)';
  512. before(() => {
  513. BrowserWindow.addExtension(contentScript);
  514. });
  515. after(() => {
  516. BrowserWindow.removeExtension('content-script-test');
  517. });
  518. beforeEach(() => {
  519. w = new BrowserWindow({
  520. show: false,
  521. webPreferences: {
  522. // enable content script injection in subframes
  523. nodeIntegrationInSubFrames: true,
  524. preload: path.join(contentScript, 'all_frames-preload.js')
  525. }
  526. });
  527. });
  528. afterEach(() =>
  529. closeWindow(w).then(() => {
  530. w = null as unknown as BrowserWindow;
  531. })
  532. );
  533. it('applies matching rules in subframes', async () => {
  534. const detailsPromise = emittedNTimes(w.webContents, 'did-frame-finish-load', 2);
  535. w.loadFile(path.join(contentScript, 'frame-with-frame.html'));
  536. const frameEvents = await detailsPromise;
  537. await Promise.all(
  538. frameEvents.map(async frameEvent => {
  539. const [, isMainFrame, , frameRoutingId] = frameEvent;
  540. const result: any = await executeJavaScriptInFrame(
  541. w.webContents,
  542. frameRoutingId,
  543. `(() => {
  544. const a = document.getElementById('all_frames_enabled')
  545. const b = document.getElementById('all_frames_disabled')
  546. return {
  547. enabledColor: getComputedStyle(a).backgroundColor,
  548. disabledColor: getComputedStyle(b).backgroundColor
  549. }
  550. })()`
  551. );
  552. expect(result.enabledColor).to.equal(COLOR_RED);
  553. if (isMainFrame) {
  554. expect(result.disabledColor).to.equal(COLOR_BLUE);
  555. } else {
  556. expect(result.disabledColor).to.equal(COLOR_TRANSPARENT); // null color
  557. }
  558. })
  559. );
  560. });
  561. });
  562. });
  563. };
  564. generateTests(false, false);
  565. generateTests(false, true);
  566. generateTests(true, false);
  567. generateTests(true, true);
  568. });
  569. describe('extension ui pages', () => {
  570. afterEach(() => {
  571. session.defaultSession.getAllExtensions().forEach(e => {
  572. session.defaultSession.removeExtension(e.id);
  573. });
  574. });
  575. it('loads a ui page of an extension', async () => {
  576. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  577. const w = new BrowserWindow({ show: false });
  578. w.loadURL(`chrome-extension://${id}/bare-page.html`);
  579. await emittedOnce(w.webContents, 'dom-ready');
  580. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  581. expect(textContent).to.equal('ui page loaded ok\n');
  582. });
  583. it('can load resources', async () => {
  584. const { id } = await session.defaultSession.loadExtension(path.join(fixtures, 'extensions', 'ui-page'));
  585. const w = new BrowserWindow({ show: false });
  586. w.loadURL(`chrome-extension://${id}/page-script-load.html`);
  587. await emittedOnce(w.webContents, 'dom-ready');
  588. const textContent = await w.webContents.executeJavaScript('document.body.textContent');
  589. expect(textContent).to.equal('script loaded ok\n');
  590. });
  591. });
  592. });