webview-spec.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. const { expect } = require('chai');
  2. const path = require('path');
  3. const http = require('http');
  4. const url = require('url');
  5. const { ipcRenderer } = require('electron');
  6. const { emittedOnce, waitForEvent } = require('./events-helpers');
  7. const { ifdescribe, ifit, delay } = require('./spec-helpers');
  8. const features = process._linkedBinding('electron_common_features');
  9. const nativeModulesEnabled = process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS;
  10. /* Most of the APIs here don't use standard callbacks */
  11. /* eslint-disable standard/no-callback-literal */
  12. describe('<webview> tag', function () {
  13. this.timeout(3 * 60 * 1000);
  14. const fixtures = path.join(__dirname, 'fixtures');
  15. let webview = null;
  16. const loadWebView = async (webview, attributes = {}) => {
  17. for (const [name, value] of Object.entries(attributes)) {
  18. webview.setAttribute(name, value);
  19. }
  20. document.body.appendChild(webview);
  21. await waitForEvent(webview, 'did-finish-load');
  22. return webview;
  23. };
  24. const startLoadingWebViewAndWaitForMessage = async (webview, attributes = {}) => {
  25. loadWebView(webview, attributes); // Don't wait for load to be finished.
  26. const event = await waitForEvent(webview, 'console-message');
  27. return event.message;
  28. };
  29. async function loadFileInWebView (webview, attributes = {}) {
  30. const thisFile = url.format({
  31. pathname: __filename.replace(/\\/g, '/'),
  32. protocol: 'file',
  33. slashes: true
  34. });
  35. const src = `<script>
  36. function loadFile() {
  37. return new Promise((resolve) => {
  38. fetch('${thisFile}').then(
  39. () => resolve('loaded'),
  40. () => resolve('failed')
  41. )
  42. });
  43. }
  44. console.log('ok');
  45. </script>`;
  46. attributes.src = `data:text/html;base64,${btoa(unescape(encodeURIComponent(src)))}`;
  47. await startLoadingWebViewAndWaitForMessage(webview, attributes);
  48. return await webview.executeJavaScript('loadFile()');
  49. }
  50. beforeEach(() => {
  51. webview = new WebView();
  52. });
  53. afterEach(() => {
  54. if (!document.body.contains(webview)) {
  55. document.body.appendChild(webview);
  56. }
  57. webview.remove();
  58. });
  59. describe('src attribute', () => {
  60. it('specifies the page to load', async () => {
  61. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  62. src: `file://${fixtures}/pages/a.html`
  63. });
  64. expect(message).to.equal('a');
  65. });
  66. it('navigates to new page when changed', async () => {
  67. await loadWebView(webview, {
  68. src: `file://${fixtures}/pages/a.html`
  69. });
  70. webview.src = `file://${fixtures}/pages/b.html`;
  71. const { message } = await waitForEvent(webview, 'console-message');
  72. expect(message).to.equal('b');
  73. });
  74. it('resolves relative URLs', async () => {
  75. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  76. src: '../fixtures/pages/e.html'
  77. });
  78. expect(message).to.equal('Window script is loaded before preload script');
  79. });
  80. it('ignores empty values', () => {
  81. expect(webview.src).to.equal('');
  82. for (const emptyValue of ['', null, undefined]) {
  83. webview.src = emptyValue;
  84. expect(webview.src).to.equal('');
  85. }
  86. });
  87. it('does not wait until loadURL is resolved', async () => {
  88. await loadWebView(webview, { src: 'about:blank' });
  89. const before = Date.now();
  90. webview.src = 'https://github.com';
  91. const now = Date.now();
  92. // Setting src is essentially sending a sync IPC message, which should
  93. // not exceed more than a few ms.
  94. //
  95. // This is for testing #18638.
  96. expect(now - before).to.be.below(100);
  97. });
  98. });
  99. describe('nodeintegration attribute', () => {
  100. it('inserts no node symbols when not set', async () => {
  101. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  102. src: `file://${fixtures}/pages/c.html`
  103. });
  104. const types = JSON.parse(message);
  105. expect(types).to.include({
  106. require: 'undefined',
  107. module: 'undefined',
  108. process: 'undefined',
  109. global: 'undefined'
  110. });
  111. });
  112. it('inserts node symbols when set', async () => {
  113. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  114. nodeintegration: 'on',
  115. webpreferences: 'contextIsolation=no',
  116. src: `file://${fixtures}/pages/d.html`
  117. });
  118. const types = JSON.parse(message);
  119. expect(types).to.include({
  120. require: 'function',
  121. module: 'object',
  122. process: 'object'
  123. });
  124. });
  125. it('loads node symbols after POST navigation when set', async function () {
  126. // FIXME Figure out why this is timing out on AppVeyor
  127. if (process.env.APPVEYOR === 'True') {
  128. this.skip();
  129. return;
  130. }
  131. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  132. nodeintegration: 'on',
  133. webpreferences: 'contextIsolation=no',
  134. src: `file://${fixtures}/pages/post.html`
  135. });
  136. const types = JSON.parse(message);
  137. expect(types).to.include({
  138. require: 'function',
  139. module: 'object',
  140. process: 'object'
  141. });
  142. });
  143. it('disables node integration on child windows when it is disabled on the webview', async () => {
  144. const src = url.format({
  145. pathname: `${fixtures}/pages/webview-opener-no-node-integration.html`,
  146. protocol: 'file',
  147. query: {
  148. p: `${fixtures}/pages/window-opener-node.html`
  149. },
  150. slashes: true
  151. });
  152. loadWebView(webview, {
  153. allowpopups: 'on',
  154. webpreferences: 'contextIsolation=no',
  155. src
  156. });
  157. const { message } = await waitForEvent(webview, 'console-message');
  158. expect(JSON.parse(message).isProcessGlobalUndefined).to.be.true();
  159. });
  160. (nativeModulesEnabled ? it : it.skip)('loads native modules when navigation happens', async function () {
  161. await loadWebView(webview, {
  162. nodeintegration: 'on',
  163. webpreferences: 'contextIsolation=no',
  164. src: `file://${fixtures}/pages/native-module.html`
  165. });
  166. webview.reload();
  167. const { message } = await waitForEvent(webview, 'console-message');
  168. expect(message).to.equal('function');
  169. });
  170. });
  171. describe('preload attribute', () => {
  172. it('loads the script before other scripts in window', async () => {
  173. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  174. preload: `${fixtures}/module/preload.js`,
  175. src: `file://${fixtures}/pages/e.html`,
  176. contextIsolation: false
  177. });
  178. expect(message).to.be.a('string');
  179. expect(message).to.be.not.equal('Window script is loaded before preload script');
  180. });
  181. it('preload script can still use "process" and "Buffer" when nodeintegration is off', async () => {
  182. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  183. preload: `${fixtures}/module/preload-node-off.js`,
  184. src: `file://${fixtures}/api/blank.html`
  185. });
  186. const types = JSON.parse(message);
  187. expect(types).to.include({
  188. process: 'object',
  189. Buffer: 'function'
  190. });
  191. });
  192. it('runs in the correct scope when sandboxed', async () => {
  193. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  194. preload: `${fixtures}/module/preload-context.js`,
  195. src: `file://${fixtures}/api/blank.html`,
  196. webpreferences: 'sandbox=yes'
  197. });
  198. const types = JSON.parse(message);
  199. expect(types).to.include({
  200. require: 'function', // arguments passed to it should be availale
  201. electron: 'undefined', // objects from the scope it is called from should not be available
  202. window: 'object', // the window object should be available
  203. localVar: 'undefined' // but local variables should not be exposed to the window
  204. });
  205. });
  206. it('preload script can require modules that still use "process" and "Buffer" when nodeintegration is off', async () => {
  207. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  208. preload: `${fixtures}/module/preload-node-off-wrapper.js`,
  209. src: `file://${fixtures}/api/blank.html`
  210. });
  211. const types = JSON.parse(message);
  212. expect(types).to.include({
  213. process: 'object',
  214. Buffer: 'function'
  215. });
  216. });
  217. it('receives ipc message in preload script', async () => {
  218. await loadWebView(webview, {
  219. preload: `${fixtures}/module/preload-ipc.js`,
  220. src: `file://${fixtures}/pages/e.html`
  221. });
  222. const message = 'boom!';
  223. webview.send('ping', message);
  224. const { channel, args } = await waitForEvent(webview, 'ipc-message');
  225. expect(channel).to.equal('pong');
  226. expect(args).to.deep.equal([message]);
  227. });
  228. it('works without script tag in page', async () => {
  229. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  230. preload: `${fixtures}/module/preload.js`,
  231. src: `file://${fixtures}pages/base-page.html`
  232. });
  233. const types = JSON.parse(message);
  234. expect(types).to.include({
  235. require: 'function',
  236. module: 'object',
  237. process: 'object',
  238. Buffer: 'function'
  239. });
  240. });
  241. it('resolves relative URLs', async () => {
  242. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  243. preload: '../fixtures/module/preload.js',
  244. src: `file://${fixtures}/pages/e.html`
  245. });
  246. const types = JSON.parse(message);
  247. expect(types).to.include({
  248. require: 'function',
  249. module: 'object',
  250. process: 'object',
  251. Buffer: 'function'
  252. });
  253. });
  254. it('ignores empty values', () => {
  255. expect(webview.preload).to.equal('');
  256. for (const emptyValue of ['', null, undefined]) {
  257. webview.preload = emptyValue;
  258. expect(webview.preload).to.equal('');
  259. }
  260. });
  261. });
  262. describe('httpreferrer attribute', () => {
  263. it('sets the referrer url', (done) => {
  264. const referrer = 'http://github.com/';
  265. const server = http.createServer((req, res) => {
  266. try {
  267. expect(req.headers.referer).to.equal(referrer);
  268. done();
  269. } catch (e) {
  270. done(e);
  271. } finally {
  272. res.end();
  273. server.close();
  274. }
  275. }).listen(0, '127.0.0.1', () => {
  276. const port = server.address().port;
  277. loadWebView(webview, {
  278. httpreferrer: referrer,
  279. src: `http://127.0.0.1:${port}`
  280. });
  281. });
  282. });
  283. });
  284. describe('useragent attribute', () => {
  285. it('sets the user agent', async () => {
  286. const referrer = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko';
  287. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  288. src: `file://${fixtures}/pages/useragent.html`,
  289. useragent: referrer
  290. });
  291. expect(message).to.equal(referrer);
  292. });
  293. });
  294. describe('disablewebsecurity attribute', () => {
  295. it('does not disable web security when not set', async () => {
  296. const result = await loadFileInWebView(webview);
  297. expect(result).to.equal('failed');
  298. });
  299. it('disables web security when set', async () => {
  300. const result = await loadFileInWebView(webview, { disablewebsecurity: '' });
  301. expect(result).to.equal('loaded');
  302. });
  303. it('does not break node integration', async () => {
  304. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  305. disablewebsecurity: '',
  306. nodeintegration: 'on',
  307. webpreferences: 'contextIsolation=no',
  308. src: `file://${fixtures}/pages/d.html`
  309. });
  310. const types = JSON.parse(message);
  311. expect(types).to.include({
  312. require: 'function',
  313. module: 'object',
  314. process: 'object'
  315. });
  316. });
  317. it('does not break preload script', async () => {
  318. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  319. disablewebsecurity: '',
  320. preload: `${fixtures}/module/preload.js`,
  321. src: `file://${fixtures}/pages/e.html`
  322. });
  323. const types = JSON.parse(message);
  324. expect(types).to.include({
  325. require: 'function',
  326. module: 'object',
  327. process: 'object',
  328. Buffer: 'function'
  329. });
  330. });
  331. });
  332. describe('partition attribute', () => {
  333. it('inserts no node symbols when not set', async () => {
  334. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  335. partition: 'test1',
  336. src: `file://${fixtures}/pages/c.html`
  337. });
  338. const types = JSON.parse(message);
  339. expect(types).to.include({
  340. require: 'undefined',
  341. module: 'undefined',
  342. process: 'undefined',
  343. global: 'undefined'
  344. });
  345. });
  346. it('inserts node symbols when set', async () => {
  347. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  348. nodeintegration: 'on',
  349. partition: 'test2',
  350. webpreferences: 'contextIsolation=no',
  351. src: `file://${fixtures}/pages/d.html`
  352. });
  353. const types = JSON.parse(message);
  354. expect(types).to.include({
  355. require: 'function',
  356. module: 'object',
  357. process: 'object'
  358. });
  359. });
  360. it('isolates storage for different id', async () => {
  361. window.localStorage.setItem('test', 'one');
  362. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  363. partition: 'test3',
  364. src: `file://${fixtures}/pages/partition/one.html`
  365. });
  366. const parsedMessage = JSON.parse(message);
  367. expect(parsedMessage).to.include({
  368. numberOfEntries: 0,
  369. testValue: null
  370. });
  371. });
  372. it('uses current session storage when no id is provided', async () => {
  373. const testValue = 'one';
  374. window.localStorage.setItem('test', testValue);
  375. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  376. src: `file://${fixtures}/pages/partition/one.html`
  377. });
  378. const parsedMessage = JSON.parse(message);
  379. expect(parsedMessage).to.include({
  380. numberOfEntries: 1,
  381. testValue
  382. });
  383. });
  384. });
  385. describe('allowpopups attribute', () => {
  386. const generateSpecs = (description, webpreferences = '') => {
  387. describe(description, () => {
  388. it('can not open new window when not set', async () => {
  389. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  390. webpreferences,
  391. src: `file://${fixtures}/pages/window-open-hide.html`
  392. });
  393. expect(message).to.equal('null');
  394. });
  395. it('can open new window when set', async () => {
  396. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  397. webpreferences,
  398. allowpopups: 'on',
  399. src: `file://${fixtures}/pages/window-open-hide.html`
  400. });
  401. expect(message).to.equal('window');
  402. });
  403. });
  404. };
  405. generateSpecs('without sandbox');
  406. generateSpecs('with sandbox', 'sandbox=yes');
  407. generateSpecs('with nativeWindowOpen', 'nativeWindowOpen=yes');
  408. });
  409. describe('webpreferences attribute', () => {
  410. it('can enable nodeintegration', async () => {
  411. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  412. src: `file://${fixtures}/pages/d.html`,
  413. webpreferences: 'nodeIntegration,contextIsolation=no'
  414. });
  415. const types = JSON.parse(message);
  416. expect(types).to.include({
  417. require: 'function',
  418. module: 'object',
  419. process: 'object'
  420. });
  421. });
  422. it('can disables web security and enable nodeintegration', async () => {
  423. const result = await loadFileInWebView(webview, { webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' });
  424. expect(result).to.equal('loaded');
  425. const type = await webview.executeJavaScript('typeof require');
  426. expect(type).to.equal('function');
  427. });
  428. });
  429. describe('new-window event', () => {
  430. it('emits when window.open is called', async () => {
  431. loadWebView(webview, {
  432. src: `file://${fixtures}/pages/window-open.html`,
  433. allowpopups: true
  434. });
  435. const { url, frameName } = await waitForEvent(webview, 'new-window');
  436. expect(url).to.equal('http://host/');
  437. expect(frameName).to.equal('host');
  438. });
  439. it('emits when link with target is called', async () => {
  440. loadWebView(webview, {
  441. src: `file://${fixtures}/pages/target-name.html`,
  442. allowpopups: true
  443. });
  444. const { url, frameName } = await waitForEvent(webview, 'new-window');
  445. expect(url).to.equal('http://host/');
  446. expect(frameName).to.equal('target');
  447. });
  448. });
  449. describe('ipc-message event', () => {
  450. it('emits when guest sends an ipc message to browser', async () => {
  451. loadWebView(webview, {
  452. nodeintegration: 'on',
  453. webpreferences: 'contextIsolation=no',
  454. src: `file://${fixtures}/pages/ipc-message.html`
  455. });
  456. const { channel, args } = await waitForEvent(webview, 'ipc-message');
  457. expect(channel).to.equal('channel');
  458. expect(args).to.deep.equal(['arg1', 'arg2']);
  459. });
  460. });
  461. describe('page-title-set event', () => {
  462. it('emits when title is set', async () => {
  463. loadWebView(webview, {
  464. src: `file://${fixtures}/pages/a.html`
  465. });
  466. const { title, explicitSet } = await waitForEvent(webview, 'page-title-set');
  467. expect(title).to.equal('test');
  468. expect(explicitSet).to.be.true();
  469. });
  470. });
  471. describe('page-favicon-updated event', () => {
  472. it('emits when favicon urls are received', async () => {
  473. loadWebView(webview, {
  474. src: `file://${fixtures}/pages/a.html`
  475. });
  476. const { favicons } = await waitForEvent(webview, 'page-favicon-updated');
  477. expect(favicons).to.be.an('array').of.length(2);
  478. if (process.platform === 'win32') {
  479. expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i);
  480. } else {
  481. expect(favicons[0]).to.equal('file:///favicon.png');
  482. }
  483. });
  484. });
  485. describe('will-navigate event', () => {
  486. it('emits when a url that leads to oustide of the page is clicked', async () => {
  487. loadWebView(webview, {
  488. src: `file://${fixtures}/pages/webview-will-navigate.html`
  489. });
  490. const { url } = await waitForEvent(webview, 'will-navigate');
  491. expect(url).to.equal('http://host/');
  492. });
  493. });
  494. describe('did-navigate event', () => {
  495. let p = path.join(fixtures, 'pages', 'webview-will-navigate.html');
  496. p = p.replace(/\\/g, '/');
  497. const pageUrl = url.format({
  498. protocol: 'file',
  499. slashes: true,
  500. pathname: p
  501. });
  502. it('emits when a url that leads to outside of the page is clicked', async () => {
  503. loadWebView(webview, { src: pageUrl });
  504. const { url } = await waitForEvent(webview, 'did-navigate');
  505. expect(url).to.equal(pageUrl);
  506. });
  507. });
  508. describe('did-navigate-in-page event', () => {
  509. it('emits when an anchor link is clicked', async () => {
  510. let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html');
  511. p = p.replace(/\\/g, '/');
  512. const pageUrl = url.format({
  513. protocol: 'file',
  514. slashes: true,
  515. pathname: p
  516. });
  517. loadWebView(webview, { src: pageUrl });
  518. const event = await waitForEvent(webview, 'did-navigate-in-page');
  519. expect(event.url).to.equal(`${pageUrl}#test_content`);
  520. });
  521. it('emits when window.history.replaceState is called', async () => {
  522. loadWebView(webview, {
  523. src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`
  524. });
  525. const { url } = await waitForEvent(webview, 'did-navigate-in-page');
  526. expect(url).to.equal('http://host/');
  527. });
  528. it('emits when window.location.hash is changed', async () => {
  529. let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html');
  530. p = p.replace(/\\/g, '/');
  531. const pageUrl = url.format({
  532. protocol: 'file',
  533. slashes: true,
  534. pathname: p
  535. });
  536. loadWebView(webview, { src: pageUrl });
  537. const event = await waitForEvent(webview, 'did-navigate-in-page');
  538. expect(event.url).to.equal(`${pageUrl}#test`);
  539. });
  540. });
  541. describe('close event', () => {
  542. it('should fire when interior page calls window.close', async () => {
  543. loadWebView(webview, { src: `file://${fixtures}/pages/close.html` });
  544. await waitForEvent(webview, 'close');
  545. });
  546. });
  547. // FIXME(zcbenz): Disabled because of moving to OOPIF webview.
  548. xdescribe('setDevToolsWebContents() API', () => {
  549. it('sets webContents of webview as devtools', async () => {
  550. const webview2 = new WebView();
  551. loadWebView(webview2);
  552. // Setup an event handler for further usage.
  553. const waitForDomReady = waitForEvent(webview2, 'dom-ready');
  554. loadWebView(webview, { src: 'about:blank' });
  555. await waitForEvent(webview, 'dom-ready');
  556. webview.getWebContents().setDevToolsWebContents(webview2.getWebContents());
  557. webview.getWebContents().openDevTools();
  558. await waitForDomReady;
  559. // Its WebContents should be a DevTools.
  560. const devtools = webview2.getWebContents();
  561. expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true();
  562. const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name');
  563. document.body.removeChild(webview2);
  564. expect(name).to.be.equal('InspectorFrontendHostImpl');
  565. });
  566. });
  567. describe('devtools-opened event', () => {
  568. it('should fire when webview.openDevTools() is called', async () => {
  569. loadWebView(webview, {
  570. src: `file://${fixtures}/pages/base-page.html`
  571. });
  572. await waitForEvent(webview, 'dom-ready');
  573. webview.openDevTools();
  574. await waitForEvent(webview, 'devtools-opened');
  575. webview.closeDevTools();
  576. });
  577. });
  578. describe('devtools-closed event', () => {
  579. it('should fire when webview.closeDevTools() is called', async () => {
  580. loadWebView(webview, {
  581. src: `file://${fixtures}/pages/base-page.html`
  582. });
  583. await waitForEvent(webview, 'dom-ready');
  584. webview.openDevTools();
  585. await waitForEvent(webview, 'devtools-opened');
  586. webview.closeDevTools();
  587. await waitForEvent(webview, 'devtools-closed');
  588. });
  589. });
  590. describe('devtools-focused event', () => {
  591. it('should fire when webview.openDevTools() is called', async () => {
  592. loadWebView(webview, {
  593. src: `file://${fixtures}/pages/base-page.html`
  594. });
  595. const waitForDevToolsFocused = waitForEvent(webview, 'devtools-focused');
  596. await waitForEvent(webview, 'dom-ready');
  597. webview.openDevTools();
  598. await waitForDevToolsFocused;
  599. webview.closeDevTools();
  600. });
  601. });
  602. describe('<webview>.reload()', () => {
  603. it('should emit beforeunload handler', async () => {
  604. await loadWebView(webview, {
  605. nodeintegration: 'on',
  606. webpreferences: 'contextIsolation=no',
  607. src: `file://${fixtures}/pages/beforeunload-false.html`
  608. });
  609. // Event handler has to be added before reload.
  610. const waitForOnbeforeunload = waitForEvent(webview, 'ipc-message');
  611. webview.reload();
  612. const { channel } = await waitForOnbeforeunload;
  613. expect(channel).to.equal('onbeforeunload');
  614. });
  615. });
  616. describe('<webview>.goForward()', () => {
  617. it('should work after a replaced history entry', (done) => {
  618. let loadCount = 1;
  619. const listener = (e) => {
  620. if (loadCount === 1) {
  621. expect(e.channel).to.equal('history');
  622. expect(e.args[0]).to.equal(1);
  623. expect(webview.canGoBack()).to.be.false();
  624. expect(webview.canGoForward()).to.be.false();
  625. } else if (loadCount === 2) {
  626. expect(e.channel).to.equal('history');
  627. expect(e.args[0]).to.equal(2);
  628. expect(webview.canGoBack()).to.be.false();
  629. expect(webview.canGoForward()).to.be.true();
  630. webview.removeEventListener('ipc-message', listener);
  631. }
  632. };
  633. const loadListener = () => {
  634. try {
  635. if (loadCount === 1) {
  636. webview.src = `file://${fixtures}/pages/base-page.html`;
  637. } else if (loadCount === 2) {
  638. expect(webview.canGoBack()).to.be.true();
  639. expect(webview.canGoForward()).to.be.false();
  640. webview.goBack();
  641. } else if (loadCount === 3) {
  642. webview.goForward();
  643. } else if (loadCount === 4) {
  644. expect(webview.canGoBack()).to.be.true();
  645. expect(webview.canGoForward()).to.be.false();
  646. webview.removeEventListener('did-finish-load', loadListener);
  647. done();
  648. }
  649. loadCount += 1;
  650. } catch (e) {
  651. done(e);
  652. }
  653. };
  654. webview.addEventListener('ipc-message', listener);
  655. webview.addEventListener('did-finish-load', loadListener);
  656. loadWebView(webview, {
  657. nodeintegration: 'on',
  658. src: `file://${fixtures}/pages/history-replace.html`
  659. });
  660. });
  661. });
  662. // FIXME: https://github.com/electron/electron/issues/19397
  663. xdescribe('<webview>.clearHistory()', () => {
  664. it('should clear the navigation history', async () => {
  665. const message = waitForEvent(webview, 'ipc-message');
  666. await loadWebView(webview, {
  667. nodeintegration: 'on',
  668. src: `file://${fixtures}/pages/history.html`
  669. });
  670. const event = await message;
  671. expect(event.channel).to.equal('history');
  672. expect(event.args[0]).to.equal(2);
  673. expect(webview.canGoBack()).to.be.true();
  674. webview.clearHistory();
  675. expect(webview.canGoBack()).to.be.false();
  676. });
  677. });
  678. describe('basic auth', () => {
  679. const auth = require('basic-auth');
  680. it('should authenticate with correct credentials', (done) => {
  681. const message = 'Authenticated';
  682. const server = http.createServer((req, res) => {
  683. const credentials = auth(req);
  684. if (credentials.name === 'test' && credentials.pass === 'test') {
  685. res.end(message);
  686. } else {
  687. res.end('failed');
  688. }
  689. server.close();
  690. });
  691. server.listen(0, '127.0.0.1', () => {
  692. const port = server.address().port;
  693. webview.addEventListener('ipc-message', (e) => {
  694. try {
  695. expect(e.channel).to.equal(message);
  696. done();
  697. } catch (e) {
  698. done(e);
  699. }
  700. });
  701. loadWebView(webview, {
  702. nodeintegration: 'on',
  703. webpreferences: 'contextIsolation=no',
  704. src: `file://${fixtures}/pages/basic-auth.html?port=${port}`
  705. });
  706. });
  707. });
  708. });
  709. describe('dom-ready event', () => {
  710. it('emits when document is loaded', (done) => {
  711. const server = http.createServer(() => {});
  712. server.listen(0, '127.0.0.1', () => {
  713. const port = server.address().port;
  714. webview.addEventListener('dom-ready', () => {
  715. done();
  716. });
  717. loadWebView(webview, {
  718. src: `file://${fixtures}/pages/dom-ready.html?port=${port}`
  719. });
  720. });
  721. });
  722. it('throws a custom error when an API method is called before the event is emitted', () => {
  723. const expectedErrorMessage =
  724. 'The WebView must be attached to the DOM ' +
  725. 'and the dom-ready event emitted before this method can be called.';
  726. expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
  727. });
  728. });
  729. describe('executeJavaScript', () => {
  730. it('should support user gesture', async () => {
  731. await loadWebView(webview, {
  732. src: `file://${fixtures}/pages/fullscreen.html`
  733. });
  734. // Event handler has to be added before js execution.
  735. const waitForEnterHtmlFullScreen = waitForEvent(webview, 'enter-html-full-screen');
  736. const jsScript = "document.querySelector('video').webkitRequestFullscreen()";
  737. webview.executeJavaScript(jsScript, true);
  738. return waitForEnterHtmlFullScreen;
  739. });
  740. it('can return the result of the executed script', async () => {
  741. await loadWebView(webview, {
  742. src: 'about:blank'
  743. });
  744. const jsScript = "'4'+2";
  745. const expectedResult = '42';
  746. const result = await webview.executeJavaScript(jsScript);
  747. expect(result).to.equal(expectedResult);
  748. });
  749. });
  750. it('supports inserting CSS', async () => {
  751. await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });
  752. await webview.insertCSS('body { background-repeat: round; }');
  753. const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  754. expect(result).to.equal('round');
  755. });
  756. it('supports removing inserted CSS', async () => {
  757. await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });
  758. const key = await webview.insertCSS('body { background-repeat: round; }');
  759. await webview.removeInsertedCSS(key);
  760. const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  761. expect(result).to.equal('repeat');
  762. });
  763. describe('sendInputEvent', () => {
  764. it('can send keyboard event', async () => {
  765. loadWebView(webview, {
  766. nodeintegration: 'on',
  767. webpreferences: 'contextIsolation=no',
  768. src: `file://${fixtures}/pages/onkeyup.html`
  769. });
  770. await waitForEvent(webview, 'dom-ready');
  771. const waitForIpcMessage = waitForEvent(webview, 'ipc-message');
  772. webview.sendInputEvent({
  773. type: 'keyup',
  774. keyCode: 'c',
  775. modifiers: ['shift']
  776. });
  777. const { channel, args } = await waitForIpcMessage;
  778. expect(channel).to.equal('keyup');
  779. expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]);
  780. });
  781. it('can send mouse event', async () => {
  782. loadWebView(webview, {
  783. nodeintegration: 'on',
  784. webpreferences: 'contextIsolation=no',
  785. src: `file://${fixtures}/pages/onmouseup.html`
  786. });
  787. await waitForEvent(webview, 'dom-ready');
  788. const waitForIpcMessage = waitForEvent(webview, 'ipc-message');
  789. webview.sendInputEvent({
  790. type: 'mouseup',
  791. modifiers: ['ctrl'],
  792. x: 10,
  793. y: 20
  794. });
  795. const { channel, args } = await waitForIpcMessage;
  796. expect(channel).to.equal('mouseup');
  797. expect(args).to.deep.equal([10, 20, false, true]);
  798. });
  799. });
  800. describe('media-started-playing media-paused events', () => {
  801. beforeEach(function () {
  802. if (!document.createElement('audio').canPlayType('audio/wav')) {
  803. this.skip();
  804. }
  805. });
  806. it('emits when audio starts and stops playing', async () => {
  807. await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });
  808. // With the new autoplay policy, audio elements must be unmuted
  809. // see https://goo.gl/xX8pDD.
  810. const source = `
  811. const audio = document.createElement("audio")
  812. audio.src = "../assets/tone.wav"
  813. document.body.appendChild(audio);
  814. audio.play()
  815. `;
  816. webview.executeJavaScript(source, true);
  817. await waitForEvent(webview, 'media-started-playing');
  818. webview.executeJavaScript('document.querySelector("audio").pause()', true);
  819. await waitForEvent(webview, 'media-paused');
  820. });
  821. });
  822. describe('found-in-page event', () => {
  823. it('emits when a request is made', async () => {
  824. const didFinishLoad = waitForEvent(webview, 'did-finish-load');
  825. loadWebView(webview, { src: `file://${fixtures}/pages/content.html` });
  826. // TODO(deepak1556): With https://codereview.chromium.org/2836973002
  827. // focus of the webContents is required when triggering the api.
  828. // Remove this workaround after determining the cause for
  829. // incorrect focus.
  830. webview.focus();
  831. await didFinishLoad;
  832. const activeMatchOrdinal = [];
  833. for (;;) {
  834. const foundInPage = waitForEvent(webview, 'found-in-page');
  835. const requestId = webview.findInPage('virtual');
  836. const event = await foundInPage;
  837. expect(event.result.requestId).to.equal(requestId);
  838. expect(event.result.matches).to.equal(3);
  839. activeMatchOrdinal.push(event.result.activeMatchOrdinal);
  840. if (event.result.activeMatchOrdinal === event.result.matches) {
  841. break;
  842. }
  843. }
  844. expect(activeMatchOrdinal).to.deep.equal([1, 2, 3]);
  845. webview.stopFindInPage('clearSelection');
  846. });
  847. });
  848. describe('<webview>.getWebContentsId', () => {
  849. it('can return the WebContents ID', async () => {
  850. const src = 'about:blank';
  851. await loadWebView(webview, { src });
  852. expect(webview.getWebContentsId()).to.be.a('number');
  853. });
  854. });
  855. describe('<webview>.capturePage()', () => {
  856. before(function () {
  857. // TODO(miniak): figure out why this is failing on windows
  858. if (process.platform === 'win32') {
  859. this.skip();
  860. }
  861. });
  862. it('returns a Promise with a NativeImage', async () => {
  863. const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
  864. await loadWebView(webview, { src });
  865. const image = await webview.capturePage();
  866. const imgBuffer = image.toPNG();
  867. // Check the 25th byte in the PNG.
  868. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  869. expect(imgBuffer[25]).to.equal(6);
  870. });
  871. });
  872. ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => {
  873. it('rejects on incorrectly typed parameters', async () => {
  874. const badTypes = {
  875. marginsType: 'terrible',
  876. scaleFactor: 'not-a-number',
  877. landscape: [],
  878. pageRanges: { oops: 'im-not-the-right-key' },
  879. headerFooter: '123',
  880. printSelectionOnly: 1,
  881. printBackground: 2,
  882. pageSize: 'IAmAPageSize'
  883. };
  884. // These will hard crash in Chromium unless we type-check
  885. for (const [key, value] of Object.entries(badTypes)) {
  886. const param = { [key]: value };
  887. const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
  888. await loadWebView(webview, { src });
  889. await expect(webview.printToPDF(param)).to.eventually.be.rejected();
  890. }
  891. });
  892. it('can print to PDF', async () => {
  893. const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
  894. await loadWebView(webview, { src });
  895. const data = await webview.printToPDF({});
  896. expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty();
  897. });
  898. });
  899. describe('will-attach-webview event', () => {
  900. it('does not emit when src is not changed', async () => {
  901. console.log('loadWebView(webview)');
  902. loadWebView(webview);
  903. await delay();
  904. const expectedErrorMessage =
  905. 'The WebView must be attached to the DOM ' +
  906. 'and the dom-ready event emitted before this method can be called.';
  907. expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
  908. });
  909. it('supports changing the web preferences', async () => {
  910. ipcRenderer.send('disable-node-on-next-will-attach-webview');
  911. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  912. nodeintegration: 'yes',
  913. src: `file://${fixtures}/pages/a.html`
  914. });
  915. const types = JSON.parse(message);
  916. expect(types).to.include({
  917. require: 'undefined',
  918. module: 'undefined',
  919. process: 'undefined',
  920. global: 'undefined'
  921. });
  922. });
  923. it('supports preventing a webview from being created', async () => {
  924. ipcRenderer.send('prevent-next-will-attach-webview');
  925. loadWebView(webview, {
  926. src: `file://${fixtures}/pages/c.html`
  927. });
  928. await waitForEvent(webview, 'destroyed');
  929. });
  930. it('supports removing the preload script', async () => {
  931. ipcRenderer.send('disable-preload-on-next-will-attach-webview');
  932. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  933. nodeintegration: 'yes',
  934. preload: path.join(fixtures, 'module', 'preload-set-global.js'),
  935. src: `file://${fixtures}/pages/a.html`
  936. });
  937. expect(message).to.equal('undefined');
  938. });
  939. });
  940. describe('DOM events', () => {
  941. let div;
  942. beforeEach(() => {
  943. div = document.createElement('div');
  944. div.style.width = '100px';
  945. div.style.height = '10px';
  946. div.style.overflow = 'hidden';
  947. webview.style.height = '100%';
  948. webview.style.width = '100%';
  949. });
  950. afterEach(() => {
  951. if (div != null) div.remove();
  952. });
  953. const generateSpecs = (description, sandbox) => {
  954. describe(description, () => {
  955. // TODO(nornagon): disabled during chromium roll 2019-06-11 due to a
  956. // 'ResizeObserver loop limit exceeded' error on Windows
  957. xit('emits resize events', async () => {
  958. const firstResizeSignal = waitForEvent(webview, 'resize');
  959. const domReadySignal = waitForEvent(webview, 'dom-ready');
  960. webview.src = `file://${fixtures}/pages/a.html`;
  961. webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`;
  962. div.appendChild(webview);
  963. document.body.appendChild(div);
  964. const firstResizeEvent = await firstResizeSignal;
  965. expect(firstResizeEvent.target).to.equal(webview);
  966. expect(firstResizeEvent.newWidth).to.equal(100);
  967. expect(firstResizeEvent.newHeight).to.equal(10);
  968. await domReadySignal;
  969. const secondResizeSignal = waitForEvent(webview, 'resize');
  970. const newWidth = 1234;
  971. const newHeight = 789;
  972. div.style.width = `${newWidth}px`;
  973. div.style.height = `${newHeight}px`;
  974. const secondResizeEvent = await secondResizeSignal;
  975. expect(secondResizeEvent.target).to.equal(webview);
  976. expect(secondResizeEvent.newWidth).to.equal(newWidth);
  977. expect(secondResizeEvent.newHeight).to.equal(newHeight);
  978. });
  979. it('emits focus event', async () => {
  980. const domReadySignal = waitForEvent(webview, 'dom-ready');
  981. webview.src = `file://${fixtures}/pages/a.html`;
  982. webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`;
  983. document.body.appendChild(webview);
  984. await domReadySignal;
  985. // If this test fails, check if webview.focus() still works.
  986. const focusSignal = waitForEvent(webview, 'focus');
  987. webview.focus();
  988. await focusSignal;
  989. });
  990. });
  991. };
  992. generateSpecs('without sandbox', false);
  993. generateSpecs('with sandbox', true);
  994. });
  995. });