webview-spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. import * as path from 'path';
  2. import * as url from 'url';
  3. import { BrowserWindow, session, ipcMain, app, WebContents } from 'electron/main';
  4. import { closeAllWindows } from './window-helpers';
  5. import { emittedOnce, emittedUntil } from './events-helpers';
  6. import { ifit, delay } from './spec-helpers';
  7. import { expect } from 'chai';
  8. async function loadWebView (w: WebContents, attributes: Record<string, string>, openDevTools: boolean = false): Promise<void> {
  9. await w.executeJavaScript(`
  10. new Promise((resolve, reject) => {
  11. const webview = new WebView()
  12. for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
  13. webview.setAttribute(k, v)
  14. }
  15. document.body.appendChild(webview)
  16. webview.addEventListener('dom-ready', () => {
  17. if (${openDevTools}) {
  18. webview.openDevTools()
  19. }
  20. })
  21. webview.addEventListener('did-finish-load', () => {
  22. resolve()
  23. })
  24. })
  25. `);
  26. }
  27. describe('<webview> tag', function () {
  28. const fixtures = path.join(__dirname, '..', 'spec', 'fixtures');
  29. afterEach(closeAllWindows);
  30. function hideChildWindows (e: any, wc: WebContents) {
  31. wc.setWindowOpenHandler(() => ({
  32. action: 'allow',
  33. overrideBrowserWindowOptions: {
  34. show: false
  35. }
  36. }));
  37. }
  38. before(() => {
  39. app.on('web-contents-created', hideChildWindows);
  40. });
  41. after(() => {
  42. app.off('web-contents-created', hideChildWindows);
  43. });
  44. it('works without script tag in page', async () => {
  45. const w = new BrowserWindow({
  46. show: false,
  47. webPreferences: {
  48. webviewTag: true,
  49. nodeIntegration: true,
  50. contextIsolation: false
  51. }
  52. });
  53. w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
  54. await emittedOnce(ipcMain, 'pong');
  55. });
  56. it('works with sandbox', async () => {
  57. const w = new BrowserWindow({
  58. show: false,
  59. webPreferences: {
  60. webviewTag: true,
  61. sandbox: true
  62. }
  63. });
  64. w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
  65. await emittedOnce(ipcMain, 'pong');
  66. });
  67. it('works with contextIsolation', async () => {
  68. const w = new BrowserWindow({
  69. show: false,
  70. webPreferences: {
  71. webviewTag: true,
  72. contextIsolation: true
  73. }
  74. });
  75. w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
  76. await emittedOnce(ipcMain, 'pong');
  77. });
  78. it('works with contextIsolation + sandbox', async () => {
  79. const w = new BrowserWindow({
  80. show: false,
  81. webPreferences: {
  82. webviewTag: true,
  83. contextIsolation: true,
  84. sandbox: true
  85. }
  86. });
  87. w.loadFile(path.join(fixtures, 'pages', 'webview-isolated.html'));
  88. await emittedOnce(ipcMain, 'pong');
  89. });
  90. it('works with Trusted Types', async () => {
  91. const w = new BrowserWindow({
  92. show: false,
  93. webPreferences: {
  94. webviewTag: true
  95. }
  96. });
  97. w.loadFile(path.join(fixtures, 'pages', 'webview-trusted-types.html'));
  98. await emittedOnce(ipcMain, 'pong');
  99. });
  100. it('is disabled by default', async () => {
  101. const w = new BrowserWindow({
  102. show: false,
  103. webPreferences: {
  104. preload: path.join(fixtures, 'module', 'preload-webview.js'),
  105. nodeIntegration: true
  106. }
  107. });
  108. const webview = emittedOnce(ipcMain, 'webview');
  109. w.loadFile(path.join(fixtures, 'pages', 'webview-no-script.html'));
  110. const [, type] = await webview;
  111. expect(type).to.equal('undefined', 'WebView still exists');
  112. });
  113. // FIXME(deepak1556): Ch69 follow up.
  114. xdescribe('document.visibilityState/hidden', () => {
  115. afterEach(() => {
  116. ipcMain.removeAllListeners('pong');
  117. });
  118. it('updates when the window is shown after the ready-to-show event', async () => {
  119. const w = new BrowserWindow({ show: false });
  120. const readyToShowSignal = emittedOnce(w, 'ready-to-show');
  121. const pongSignal1 = emittedOnce(ipcMain, 'pong');
  122. w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
  123. await pongSignal1;
  124. const pongSignal2 = emittedOnce(ipcMain, 'pong');
  125. await readyToShowSignal;
  126. w.show();
  127. const [, visibilityState, hidden] = await pongSignal2;
  128. expect(visibilityState).to.equal('visible');
  129. expect(hidden).to.be.false();
  130. });
  131. it('inherits the parent window visibility state and receives visibilitychange events', async () => {
  132. const w = new BrowserWindow({ show: false });
  133. w.loadFile(path.join(fixtures, 'pages', 'webview-visibilitychange.html'));
  134. const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong');
  135. expect(visibilityState).to.equal('hidden');
  136. expect(hidden).to.be.true();
  137. // We have to start waiting for the event
  138. // before we ask the webContents to resize.
  139. const getResponse = emittedOnce(ipcMain, 'pong');
  140. w.webContents.emit('-window-visibility-change', 'visible');
  141. return getResponse.then(([, visibilityState, hidden]) => {
  142. expect(visibilityState).to.equal('visible');
  143. expect(hidden).to.be.false();
  144. });
  145. });
  146. });
  147. describe('did-attach-webview event', () => {
  148. it('is emitted when a webview has been attached', async () => {
  149. const w = new BrowserWindow({
  150. show: false,
  151. webPreferences: {
  152. webviewTag: true,
  153. nodeIntegration: true,
  154. contextIsolation: false
  155. }
  156. });
  157. const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
  158. const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready');
  159. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  160. const [, webContents] = await didAttachWebview;
  161. const [, id] = await webviewDomReady;
  162. expect(webContents.id).to.equal(id);
  163. });
  164. });
  165. describe('did-attach event', () => {
  166. it('is emitted when a webview has been attached', async () => {
  167. const w = new BrowserWindow({
  168. webPreferences: {
  169. webviewTag: true
  170. }
  171. });
  172. await w.loadURL('about:blank');
  173. const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  174. const webview = new WebView()
  175. webview.setAttribute('src', 'about:blank')
  176. webview.addEventListener('did-attach', (e) => {
  177. resolve('ok')
  178. })
  179. document.body.appendChild(webview)
  180. })`);
  181. expect(message).to.equal('ok');
  182. });
  183. });
  184. describe('did-change-theme-color event', () => {
  185. it('emits when theme color changes', async () => {
  186. const w = new BrowserWindow({
  187. webPreferences: {
  188. webviewTag: true
  189. }
  190. });
  191. await w.loadURL('about:blank');
  192. const src = url.format({
  193. pathname: `${fixtures.replace(/\\/g, '/')}/pages/theme-color.html`,
  194. protocol: 'file',
  195. slashes: true
  196. });
  197. const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  198. const webview = new WebView()
  199. webview.setAttribute('src', '${src}')
  200. webview.addEventListener('did-change-theme-color', (e) => {
  201. resolve('ok')
  202. })
  203. document.body.appendChild(webview)
  204. })`);
  205. expect(message).to.equal('ok');
  206. });
  207. });
  208. // This test is flaky on WOA, so skip it there.
  209. ifit(process.platform !== 'win32' || process.arch !== 'arm64')('loads devtools extensions registered on the parent window', async () => {
  210. const w = new BrowserWindow({
  211. show: false,
  212. webPreferences: {
  213. webviewTag: true,
  214. nodeIntegration: true,
  215. contextIsolation: false
  216. }
  217. });
  218. w.webContents.session.removeExtension('foo');
  219. const extensionPath = path.join(__dirname, 'fixtures', 'devtools-extensions', 'foo');
  220. await w.webContents.session.loadExtension(extensionPath);
  221. w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'webview-devtools.html'));
  222. loadWebView(w.webContents, {
  223. nodeintegration: 'on',
  224. webpreferences: 'contextIsolation=no',
  225. src: `file://${path.join(__dirname, 'fixtures', 'blank.html')}`
  226. }, true);
  227. let childWebContentsId = 0;
  228. app.once('web-contents-created', (e, webContents) => {
  229. childWebContentsId = webContents.id;
  230. webContents.on('devtools-opened', function () {
  231. const showPanelIntervalId = setInterval(function () {
  232. if (!webContents.isDestroyed() && webContents.devToolsWebContents) {
  233. webContents.devToolsWebContents.executeJavaScript('(' + function () {
  234. const { UI } = (window as any);
  235. const tabs = UI.inspectorView.tabbedPane.tabs;
  236. const lastPanelId: any = tabs[tabs.length - 1].id;
  237. UI.inspectorView.showPanel(lastPanelId);
  238. }.toString() + ')()');
  239. } else {
  240. clearInterval(showPanelIntervalId);
  241. }
  242. }, 100);
  243. });
  244. });
  245. const [, { runtimeId, tabId }] = await emittedOnce(ipcMain, 'answer');
  246. expect(runtimeId).to.match(/^[a-z]{32}$/);
  247. expect(tabId).to.equal(childWebContentsId);
  248. });
  249. describe('zoom behavior', () => {
  250. const zoomScheme = standardScheme;
  251. const webviewSession = session.fromPartition('webview-temp');
  252. before(() => {
  253. const protocol = webviewSession.protocol;
  254. protocol.registerStringProtocol(zoomScheme, (request, callback) => {
  255. callback('hello');
  256. });
  257. });
  258. after(() => {
  259. const protocol = webviewSession.protocol;
  260. protocol.unregisterProtocol(zoomScheme);
  261. });
  262. it('inherits the zoomFactor of the parent window', async () => {
  263. const w = new BrowserWindow({
  264. show: false,
  265. webPreferences: {
  266. webviewTag: true,
  267. nodeIntegration: true,
  268. zoomFactor: 1.2,
  269. contextIsolation: false
  270. }
  271. });
  272. const zoomEventPromise = emittedOnce(ipcMain, 'webview-parent-zoom-level');
  273. w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-factor.html'));
  274. const [, zoomFactor, zoomLevel] = await zoomEventPromise;
  275. expect(zoomFactor).to.equal(1.2);
  276. expect(zoomLevel).to.equal(1);
  277. });
  278. it('maintains zoom level on navigation', async () => {
  279. const w = new BrowserWindow({
  280. show: false,
  281. webPreferences: {
  282. webviewTag: true,
  283. nodeIntegration: true,
  284. zoomFactor: 1.2,
  285. contextIsolation: false
  286. }
  287. });
  288. const promise = new Promise<void>((resolve) => {
  289. ipcMain.on('webview-zoom-level', (event, zoomLevel, zoomFactor, newHost, final) => {
  290. if (!newHost) {
  291. expect(zoomFactor).to.equal(1.44);
  292. expect(zoomLevel).to.equal(2.0);
  293. } else {
  294. expect(zoomFactor).to.equal(1.2);
  295. expect(zoomLevel).to.equal(1);
  296. }
  297. if (final) {
  298. resolve();
  299. }
  300. });
  301. });
  302. w.loadFile(path.join(fixtures, 'pages', 'webview-custom-zoom-level.html'));
  303. await promise;
  304. });
  305. it('maintains zoom level when navigating within same page', async () => {
  306. const w = new BrowserWindow({
  307. show: false,
  308. webPreferences: {
  309. webviewTag: true,
  310. nodeIntegration: true,
  311. zoomFactor: 1.2,
  312. contextIsolation: false
  313. }
  314. });
  315. const promise = new Promise<void>((resolve) => {
  316. ipcMain.on('webview-zoom-in-page', (event, zoomLevel, zoomFactor, final) => {
  317. expect(zoomFactor).to.equal(1.44);
  318. expect(zoomLevel).to.equal(2.0);
  319. if (final) {
  320. resolve();
  321. }
  322. });
  323. });
  324. w.loadFile(path.join(fixtures, 'pages', 'webview-in-page-navigate.html'));
  325. await promise;
  326. });
  327. it('inherits zoom level for the origin when available', async () => {
  328. const w = new BrowserWindow({
  329. show: false,
  330. webPreferences: {
  331. webviewTag: true,
  332. nodeIntegration: true,
  333. zoomFactor: 1.2,
  334. contextIsolation: false
  335. }
  336. });
  337. w.loadFile(path.join(fixtures, 'pages', 'webview-origin-zoom-level.html'));
  338. const [, zoomLevel] = await emittedOnce(ipcMain, 'webview-origin-zoom-level');
  339. expect(zoomLevel).to.equal(2.0);
  340. });
  341. it('does not crash when navigating with zoom level inherited from parent', async () => {
  342. const w = new BrowserWindow({
  343. show: false,
  344. webPreferences: {
  345. webviewTag: true,
  346. nodeIntegration: true,
  347. zoomFactor: 1.2,
  348. session: webviewSession,
  349. contextIsolation: false
  350. }
  351. });
  352. const attachPromise = emittedOnce(w.webContents, 'did-attach-webview');
  353. const readyPromise = emittedOnce(ipcMain, 'dom-ready');
  354. w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
  355. const [, webview] = await attachPromise;
  356. await readyPromise;
  357. expect(webview.getZoomFactor()).to.equal(1.2);
  358. await w.loadURL(`${zoomScheme}://host1`);
  359. });
  360. it('does not crash when changing zoom level after webview is destroyed', async () => {
  361. const w = new BrowserWindow({
  362. show: false,
  363. webPreferences: {
  364. webviewTag: true,
  365. nodeIntegration: true,
  366. session: webviewSession,
  367. contextIsolation: false
  368. }
  369. });
  370. const attachPromise = emittedOnce(w.webContents, 'did-attach-webview');
  371. await w.loadFile(path.join(fixtures, 'pages', 'webview-zoom-inherited.html'));
  372. await attachPromise;
  373. await w.webContents.executeJavaScript('view.remove()');
  374. w.webContents.setZoomLevel(0.5);
  375. });
  376. });
  377. describe('requestFullscreen from webview', () => {
  378. const loadWebViewWindow = async () => {
  379. const w = new BrowserWindow({
  380. webPreferences: {
  381. webviewTag: true,
  382. nodeIntegration: true,
  383. contextIsolation: false
  384. }
  385. });
  386. const attachPromise = emittedOnce(w.webContents, 'did-attach-webview');
  387. const loadPromise = emittedOnce(w.webContents, 'did-finish-load');
  388. const readyPromise = emittedOnce(ipcMain, 'webview-ready');
  389. w.loadFile(path.join(__dirname, 'fixtures', 'webview', 'fullscreen', 'main.html'));
  390. const [, webview] = await attachPromise;
  391. await Promise.all([readyPromise, loadPromise]);
  392. return [w, webview];
  393. };
  394. afterEach(async () => {
  395. // The leaving animation is un-observable but can interfere with future tests
  396. // Specifically this is async on macOS but can be on other platforms too
  397. await delay(1000);
  398. closeAllWindows();
  399. });
  400. ifit(process.platform !== 'darwin')('should make parent frame element fullscreen too (non-macOS)', async () => {
  401. const [w, webview] = await loadWebViewWindow();
  402. expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
  403. const parentFullscreen = emittedOnce(ipcMain, 'fullscreenchange');
  404. await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  405. await parentFullscreen;
  406. expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
  407. const close = emittedOnce(w, 'closed');
  408. w.close();
  409. await close;
  410. });
  411. ifit(process.platform === 'darwin')('should make parent frame element fullscreen too (macOS)', async () => {
  412. const [w, webview] = await loadWebViewWindow();
  413. expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.false();
  414. const parentFullscreen = emittedOnce(ipcMain, 'fullscreenchange');
  415. const enterHTMLFS = emittedOnce(w.webContents, 'enter-html-full-screen');
  416. const leaveHTMLFS = emittedOnce(w.webContents, 'leave-html-full-screen');
  417. await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  418. expect(await w.webContents.executeJavaScript('isIframeFullscreen()')).to.be.true();
  419. await webview.executeJavaScript('document.exitFullscreen()');
  420. await Promise.all([enterHTMLFS, leaveHTMLFS, parentFullscreen]);
  421. const close = emittedOnce(w, 'closed');
  422. w.close();
  423. await close;
  424. });
  425. // FIXME(zcbenz): Fullscreen events do not work on Linux.
  426. ifit(process.platform !== 'linux')('exiting fullscreen should unfullscreen window', async () => {
  427. const [w, webview] = await loadWebViewWindow();
  428. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  429. await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  430. await enterFullScreen;
  431. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  432. await webview.executeJavaScript('document.exitFullscreen()', true);
  433. await leaveFullScreen;
  434. await delay(0);
  435. expect(w.isFullScreen()).to.be.false();
  436. const close = emittedOnce(w, 'closed');
  437. w.close();
  438. await close;
  439. });
  440. // Sending ESC via sendInputEvent only works on Windows.
  441. ifit(process.platform === 'win32')('pressing ESC should unfullscreen window', async () => {
  442. const [w, webview] = await loadWebViewWindow();
  443. const enterFullScreen = emittedOnce(w, 'enter-full-screen');
  444. await webview.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  445. await enterFullScreen;
  446. const leaveFullScreen = emittedOnce(w, 'leave-full-screen');
  447. w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
  448. await leaveFullScreen;
  449. await delay(0);
  450. expect(w.isFullScreen()).to.be.false();
  451. const close = emittedOnce(w, 'closed');
  452. w.close();
  453. await close;
  454. });
  455. it('pressing ESC should emit the leave-html-full-screen event', async () => {
  456. const w = new BrowserWindow({
  457. show: false,
  458. webPreferences: {
  459. webviewTag: true,
  460. nodeIntegration: true,
  461. contextIsolation: false
  462. }
  463. });
  464. const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview');
  465. w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html'));
  466. const [, webContents] = await didAttachWebview;
  467. const enterFSWindow = emittedOnce(w, 'enter-html-full-screen');
  468. const enterFSWebview = emittedOnce(webContents, 'enter-html-full-screen');
  469. await webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true);
  470. await enterFSWindow;
  471. await enterFSWebview;
  472. const leaveFSWindow = emittedOnce(w, 'leave-html-full-screen');
  473. const leaveFSWebview = emittedOnce(webContents, 'leave-html-full-screen');
  474. webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' });
  475. await leaveFSWebview;
  476. await leaveFSWindow;
  477. const close = emittedOnce(w, 'closed');
  478. w.close();
  479. await close;
  480. });
  481. it('should support user gesture', async () => {
  482. const [w, webview] = await loadWebViewWindow();
  483. const waitForEnterHtmlFullScreen = emittedOnce(webview, 'enter-html-full-screen');
  484. const jsScript = "document.querySelector('video').webkitRequestFullscreen()";
  485. webview.executeJavaScript(jsScript, true);
  486. await waitForEnterHtmlFullScreen;
  487. const close = emittedOnce(w, 'closed');
  488. w.close();
  489. await close;
  490. });
  491. });
  492. describe('child windows', () => {
  493. let w: BrowserWindow;
  494. beforeEach(async () => {
  495. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
  496. await w.loadURL('about:blank');
  497. });
  498. afterEach(closeAllWindows);
  499. it('opens window of about:blank with cross-scripting enabled', async () => {
  500. // Don't wait for loading to finish.
  501. loadWebView(w.webContents, {
  502. allowpopups: 'on',
  503. nodeintegration: 'on',
  504. webpreferences: 'contextIsolation=no',
  505. src: `file://${path.join(fixtures, 'api', 'native-window-open-blank.html')}`
  506. });
  507. const [, content] = await emittedOnce(ipcMain, 'answer');
  508. expect(content).to.equal('Hello');
  509. });
  510. it('opens window of same domain with cross-scripting enabled', async () => {
  511. // Don't wait for loading to finish.
  512. loadWebView(w.webContents, {
  513. allowpopups: 'on',
  514. nodeintegration: 'on',
  515. webpreferences: 'contextIsolation=no',
  516. src: `file://${path.join(fixtures, 'api', 'native-window-open-file.html')}`
  517. });
  518. const [, content] = await emittedOnce(ipcMain, 'answer');
  519. expect(content).to.equal('Hello');
  520. });
  521. it('returns null from window.open when allowpopups is not set', async () => {
  522. // Don't wait for loading to finish.
  523. loadWebView(w.webContents, {
  524. nodeintegration: 'on',
  525. webpreferences: 'contextIsolation=no',
  526. src: `file://${path.join(fixtures, 'api', 'native-window-open-no-allowpopups.html')}`
  527. });
  528. const [, { windowOpenReturnedNull }] = await emittedOnce(ipcMain, 'answer');
  529. expect(windowOpenReturnedNull).to.be.true();
  530. });
  531. it('blocks accessing cross-origin frames', async () => {
  532. // Don't wait for loading to finish.
  533. loadWebView(w.webContents, {
  534. allowpopups: 'on',
  535. nodeintegration: 'on',
  536. webpreferences: 'contextIsolation=no',
  537. src: `file://${path.join(fixtures, 'api', 'native-window-open-cross-origin.html')}`
  538. });
  539. const [, content] = await emittedOnce(ipcMain, 'answer');
  540. const expectedContent =
  541. 'Blocked a frame with origin "file://" from accessing a cross-origin frame.';
  542. expect(content).to.equal(expectedContent);
  543. });
  544. it('emits a new-window event', async () => {
  545. // Don't wait for loading to finish.
  546. const attributes = {
  547. allowpopups: 'on',
  548. nodeintegration: 'on',
  549. webpreferences: 'contextIsolation=no',
  550. src: `file://${fixtures}/pages/window-open.html`
  551. };
  552. const { url, frameName } = await w.webContents.executeJavaScript(`
  553. new Promise((resolve, reject) => {
  554. const webview = document.createElement('webview')
  555. for (const [k, v] of Object.entries(${JSON.stringify(attributes)})) {
  556. webview.setAttribute(k, v)
  557. }
  558. document.body.appendChild(webview)
  559. webview.addEventListener('new-window', (e) => {
  560. resolve({url: e.url, frameName: e.frameName})
  561. })
  562. })
  563. `);
  564. expect(url).to.equal('http://host/');
  565. expect(frameName).to.equal('host');
  566. });
  567. it('emits a browser-window-created event', async () => {
  568. // Don't wait for loading to finish.
  569. loadWebView(w.webContents, {
  570. allowpopups: 'on',
  571. webpreferences: 'contextIsolation=no',
  572. src: `file://${fixtures}/pages/window-open.html`
  573. });
  574. await emittedOnce(app, 'browser-window-created');
  575. });
  576. it('emits a web-contents-created event', async () => {
  577. const webContentsCreated = emittedUntil(app, 'web-contents-created',
  578. (event: Electron.Event, contents: Electron.WebContents) => contents.getType() === 'window');
  579. loadWebView(w.webContents, {
  580. allowpopups: 'on',
  581. webpreferences: 'contextIsolation=no',
  582. src: `file://${fixtures}/pages/window-open.html`
  583. });
  584. await webContentsCreated;
  585. });
  586. it('does not crash when creating window with noopener', async () => {
  587. loadWebView(w.webContents, {
  588. allowpopups: 'on',
  589. src: `file://${path.join(fixtures, 'api', 'native-window-open-noopener.html')}`
  590. });
  591. await emittedOnce(app, 'browser-window-created');
  592. });
  593. });
  594. describe('webpreferences attribute', () => {
  595. let w: BrowserWindow;
  596. beforeEach(async () => {
  597. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true } });
  598. await w.loadURL('about:blank');
  599. });
  600. afterEach(closeAllWindows);
  601. it('can enable context isolation', async () => {
  602. loadWebView(w.webContents, {
  603. allowpopups: 'yes',
  604. preload: `file://${fixtures}/api/isolated-preload.js`,
  605. src: `file://${fixtures}/api/isolated.html`,
  606. webpreferences: 'contextIsolation=yes'
  607. });
  608. const [, data] = await emittedOnce(ipcMain, 'isolated-world');
  609. expect(data).to.deep.equal({
  610. preloadContext: {
  611. preloadProperty: 'number',
  612. pageProperty: 'undefined',
  613. typeofRequire: 'function',
  614. typeofProcess: 'object',
  615. typeofArrayPush: 'function',
  616. typeofFunctionApply: 'function',
  617. typeofPreloadExecuteJavaScriptProperty: 'undefined'
  618. },
  619. pageContext: {
  620. preloadProperty: 'undefined',
  621. pageProperty: 'string',
  622. typeofRequire: 'undefined',
  623. typeofProcess: 'undefined',
  624. typeofArrayPush: 'number',
  625. typeofFunctionApply: 'boolean',
  626. typeofPreloadExecuteJavaScriptProperty: 'number',
  627. typeofOpenedWindow: 'object'
  628. }
  629. });
  630. });
  631. });
  632. describe('permission request handlers', () => {
  633. let w: BrowserWindow;
  634. beforeEach(async () => {
  635. w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, webviewTag: true, contextIsolation: false } });
  636. await w.loadURL('about:blank');
  637. });
  638. afterEach(closeAllWindows);
  639. const partition = 'permissionTest';
  640. function setUpRequestHandler (webContentsId: number, requestedPermission: string) {
  641. return new Promise<void>((resolve, reject) => {
  642. session.fromPartition(partition).setPermissionRequestHandler(function (webContents, permission, callback) {
  643. if (webContents.id === webContentsId) {
  644. // requestMIDIAccess with sysex requests both midi and midiSysex so
  645. // grant the first midi one and then reject the midiSysex one
  646. if (requestedPermission === 'midiSysex' && permission === 'midi') {
  647. return callback(true);
  648. }
  649. try {
  650. expect(permission).to.equal(requestedPermission);
  651. } catch (e) {
  652. return reject(e);
  653. }
  654. callback(false);
  655. resolve();
  656. }
  657. });
  658. });
  659. }
  660. afterEach(() => {
  661. session.fromPartition(partition).setPermissionRequestHandler(null);
  662. });
  663. // This is disabled because CI machines don't have cameras or microphones,
  664. // so Chrome responds with "NotFoundError" instead of
  665. // "PermissionDeniedError". It should be re-enabled if we find a way to mock
  666. // the presence of a microphone & camera.
  667. xit('emits when using navigator.getUserMedia api', async () => {
  668. const errorFromRenderer = emittedOnce(ipcMain, 'message');
  669. loadWebView(w.webContents, {
  670. src: `file://${fixtures}/pages/permissions/media.html`,
  671. partition,
  672. nodeintegration: 'on'
  673. });
  674. const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
  675. setUpRequestHandler(webViewContents.id, 'media');
  676. const [, errorName] = await errorFromRenderer;
  677. expect(errorName).to.equal('PermissionDeniedError');
  678. });
  679. it('emits when using navigator.geolocation api', async () => {
  680. const errorFromRenderer = emittedOnce(ipcMain, 'message');
  681. loadWebView(w.webContents, {
  682. src: `file://${fixtures}/pages/permissions/geolocation.html`,
  683. partition,
  684. nodeintegration: 'on',
  685. webpreferences: 'contextIsolation=no'
  686. });
  687. const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
  688. setUpRequestHandler(webViewContents.id, 'geolocation');
  689. const [, error] = await errorFromRenderer;
  690. expect(error).to.equal('User denied Geolocation');
  691. });
  692. it('emits when using navigator.requestMIDIAccess without sysex api', async () => {
  693. const errorFromRenderer = emittedOnce(ipcMain, 'message');
  694. loadWebView(w.webContents, {
  695. src: `file://${fixtures}/pages/permissions/midi.html`,
  696. partition,
  697. nodeintegration: 'on',
  698. webpreferences: 'contextIsolation=no'
  699. });
  700. const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
  701. setUpRequestHandler(webViewContents.id, 'midi');
  702. const [, error] = await errorFromRenderer;
  703. expect(error).to.equal('SecurityError');
  704. });
  705. it('emits when using navigator.requestMIDIAccess with sysex api', async () => {
  706. const errorFromRenderer = emittedOnce(ipcMain, 'message');
  707. loadWebView(w.webContents, {
  708. src: `file://${fixtures}/pages/permissions/midi-sysex.html`,
  709. partition,
  710. nodeintegration: 'on',
  711. webpreferences: 'contextIsolation=no'
  712. });
  713. const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
  714. setUpRequestHandler(webViewContents.id, 'midiSysex');
  715. const [, error] = await errorFromRenderer;
  716. expect(error).to.equal('SecurityError');
  717. });
  718. it('emits when accessing external protocol', async () => {
  719. loadWebView(w.webContents, {
  720. src: 'magnet:test',
  721. partition
  722. });
  723. const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
  724. await setUpRequestHandler(webViewContents.id, 'openExternal');
  725. });
  726. it('emits when using Notification.requestPermission', async () => {
  727. const errorFromRenderer = emittedOnce(ipcMain, 'message');
  728. loadWebView(w.webContents, {
  729. src: `file://${fixtures}/pages/permissions/notification.html`,
  730. partition,
  731. nodeintegration: 'on',
  732. webpreferences: 'contextIsolation=no'
  733. });
  734. const [, webViewContents] = await emittedOnce(app, 'web-contents-created');
  735. await setUpRequestHandler(webViewContents.id, 'notifications');
  736. const [, error] = await errorFromRenderer;
  737. expect(error).to.equal('denied');
  738. });
  739. });
  740. describe('DOM events', () => {
  741. afterEach(closeAllWindows);
  742. it('receives extra properties on DOM events when contextIsolation is enabled', async () => {
  743. const w = new BrowserWindow({
  744. show: false,
  745. webPreferences: {
  746. webviewTag: true,
  747. contextIsolation: true
  748. }
  749. });
  750. await w.loadURL('about:blank');
  751. const message = await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  752. const webview = new WebView()
  753. webview.setAttribute('src', 'data:text/html,<script>console.log("hi")</script>')
  754. webview.addEventListener('console-message', (e) => {
  755. resolve(e.message)
  756. })
  757. document.body.appendChild(webview)
  758. })`);
  759. expect(message).to.equal('hi');
  760. });
  761. it('emits focus event when contextIsolation is enabled', async () => {
  762. const w = new BrowserWindow({
  763. show: false,
  764. webPreferences: {
  765. webviewTag: true,
  766. contextIsolation: true
  767. }
  768. });
  769. await w.loadURL('about:blank');
  770. await w.webContents.executeJavaScript(`new Promise((resolve, reject) => {
  771. const webview = new WebView()
  772. webview.setAttribute('src', 'about:blank')
  773. webview.addEventListener('dom-ready', () => {
  774. webview.focus()
  775. })
  776. webview.addEventListener('focus', () => {
  777. resolve();
  778. })
  779. document.body.appendChild(webview)
  780. })`);
  781. });
  782. });
  783. });