webview-spec.js 38 KB

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