webview-spec.js 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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. ifit(features.isRemoteModuleEnabled())('can disable the remote module', async () => {
  423. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  424. preload: `${fixtures}/module/preload-disable-remote.js`,
  425. src: `file://${fixtures}/api/blank.html`,
  426. webpreferences: 'enableRemoteModule=no'
  427. });
  428. const typeOfRemote = JSON.parse(message);
  429. expect(typeOfRemote).to.equal('undefined');
  430. });
  431. it('can disables web security and enable nodeintegration', async () => {
  432. const result = await loadFileInWebView(webview, { webpreferences: 'webSecurity=no, nodeIntegration=yes, contextIsolation=no' });
  433. expect(result).to.equal('loaded');
  434. const type = await webview.executeJavaScript('typeof require');
  435. expect(type).to.equal('function');
  436. });
  437. });
  438. describe('new-window event', () => {
  439. it('emits when window.open is called', async () => {
  440. loadWebView(webview, {
  441. src: `file://${fixtures}/pages/window-open.html`
  442. });
  443. const { url, frameName } = await waitForEvent(webview, 'new-window');
  444. expect(url).to.equal('http://host/');
  445. expect(frameName).to.equal('host');
  446. });
  447. it('emits when link with target is called', async () => {
  448. loadWebView(webview, {
  449. src: `file://${fixtures}/pages/target-name.html`
  450. });
  451. const { url, frameName } = await waitForEvent(webview, 'new-window');
  452. expect(url).to.equal('http://host/');
  453. expect(frameName).to.equal('target');
  454. });
  455. });
  456. describe('ipc-message event', () => {
  457. it('emits when guest sends an ipc message to browser', async () => {
  458. loadWebView(webview, {
  459. nodeintegration: 'on',
  460. webpreferences: 'contextIsolation=no',
  461. src: `file://${fixtures}/pages/ipc-message.html`
  462. });
  463. const { channel, args } = await waitForEvent(webview, 'ipc-message');
  464. expect(channel).to.equal('channel');
  465. expect(args).to.deep.equal(['arg1', 'arg2']);
  466. });
  467. });
  468. describe('page-title-set event', () => {
  469. it('emits when title is set', async () => {
  470. loadWebView(webview, {
  471. src: `file://${fixtures}/pages/a.html`
  472. });
  473. const { title, explicitSet } = await waitForEvent(webview, 'page-title-set');
  474. expect(title).to.equal('test');
  475. expect(explicitSet).to.be.true();
  476. });
  477. });
  478. describe('page-favicon-updated event', () => {
  479. it('emits when favicon urls are received', async () => {
  480. loadWebView(webview, {
  481. src: `file://${fixtures}/pages/a.html`
  482. });
  483. const { favicons } = await waitForEvent(webview, 'page-favicon-updated');
  484. expect(favicons).to.be.an('array').of.length(2);
  485. if (process.platform === 'win32') {
  486. expect(favicons[0]).to.match(/^file:\/\/\/[A-Z]:\/favicon.png$/i);
  487. } else {
  488. expect(favicons[0]).to.equal('file:///favicon.png');
  489. }
  490. });
  491. });
  492. describe('will-navigate event', () => {
  493. it('emits when a url that leads to oustide of the page is clicked', async () => {
  494. loadWebView(webview, {
  495. src: `file://${fixtures}/pages/webview-will-navigate.html`
  496. });
  497. const { url } = await waitForEvent(webview, 'will-navigate');
  498. expect(url).to.equal('http://host/');
  499. });
  500. });
  501. describe('did-navigate event', () => {
  502. let p = path.join(fixtures, 'pages', 'webview-will-navigate.html');
  503. p = p.replace(/\\/g, '/');
  504. const pageUrl = url.format({
  505. protocol: 'file',
  506. slashes: true,
  507. pathname: p
  508. });
  509. it('emits when a url that leads to outside of the page is clicked', async () => {
  510. loadWebView(webview, { src: pageUrl });
  511. const { url } = await waitForEvent(webview, 'did-navigate');
  512. expect(url).to.equal(pageUrl);
  513. });
  514. });
  515. describe('did-navigate-in-page event', () => {
  516. it('emits when an anchor link is clicked', async () => {
  517. let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page.html');
  518. p = p.replace(/\\/g, '/');
  519. const pageUrl = url.format({
  520. protocol: 'file',
  521. slashes: true,
  522. pathname: p
  523. });
  524. loadWebView(webview, { src: pageUrl });
  525. const event = await waitForEvent(webview, 'did-navigate-in-page');
  526. expect(event.url).to.equal(`${pageUrl}#test_content`);
  527. });
  528. it('emits when window.history.replaceState is called', async () => {
  529. loadWebView(webview, {
  530. src: `file://${fixtures}/pages/webview-did-navigate-in-page-with-history.html`
  531. });
  532. const { url } = await waitForEvent(webview, 'did-navigate-in-page');
  533. expect(url).to.equal('http://host/');
  534. });
  535. it('emits when window.location.hash is changed', async () => {
  536. let p = path.join(fixtures, 'pages', 'webview-did-navigate-in-page-with-hash.html');
  537. p = p.replace(/\\/g, '/');
  538. const pageUrl = url.format({
  539. protocol: 'file',
  540. slashes: true,
  541. pathname: p
  542. });
  543. loadWebView(webview, { src: pageUrl });
  544. const event = await waitForEvent(webview, 'did-navigate-in-page');
  545. expect(event.url).to.equal(`${pageUrl}#test`);
  546. });
  547. });
  548. describe('close event', () => {
  549. it('should fire when interior page calls window.close', async () => {
  550. loadWebView(webview, { src: `file://${fixtures}/pages/close.html` });
  551. await waitForEvent(webview, 'close');
  552. });
  553. });
  554. // FIXME(zcbenz): Disabled because of moving to OOPIF webview.
  555. xdescribe('setDevToolsWebContents() API', () => {
  556. it('sets webContents of webview as devtools', async () => {
  557. const webview2 = new WebView();
  558. loadWebView(webview2);
  559. // Setup an event handler for further usage.
  560. const waitForDomReady = waitForEvent(webview2, 'dom-ready');
  561. loadWebView(webview, { src: 'about:blank' });
  562. await waitForEvent(webview, 'dom-ready');
  563. webview.getWebContents().setDevToolsWebContents(webview2.getWebContents());
  564. webview.getWebContents().openDevTools();
  565. await waitForDomReady;
  566. // Its WebContents should be a DevTools.
  567. const devtools = webview2.getWebContents();
  568. expect(devtools.getURL().startsWith('devtools://devtools')).to.be.true();
  569. const name = await devtools.executeJavaScript('InspectorFrontendHost.constructor.name');
  570. document.body.removeChild(webview2);
  571. expect(name).to.be.equal('InspectorFrontendHostImpl');
  572. });
  573. });
  574. describe('devtools-opened event', () => {
  575. it('should fire when webview.openDevTools() is called', async () => {
  576. loadWebView(webview, {
  577. src: `file://${fixtures}/pages/base-page.html`
  578. });
  579. await waitForEvent(webview, 'dom-ready');
  580. webview.openDevTools();
  581. await waitForEvent(webview, 'devtools-opened');
  582. webview.closeDevTools();
  583. });
  584. });
  585. describe('devtools-closed event', () => {
  586. it('should fire when webview.closeDevTools() is called', async () => {
  587. loadWebView(webview, {
  588. src: `file://${fixtures}/pages/base-page.html`
  589. });
  590. await waitForEvent(webview, 'dom-ready');
  591. webview.openDevTools();
  592. await waitForEvent(webview, 'devtools-opened');
  593. webview.closeDevTools();
  594. await waitForEvent(webview, 'devtools-closed');
  595. });
  596. });
  597. describe('devtools-focused event', () => {
  598. it('should fire when webview.openDevTools() is called', async () => {
  599. loadWebView(webview, {
  600. src: `file://${fixtures}/pages/base-page.html`
  601. });
  602. const waitForDevToolsFocused = waitForEvent(webview, 'devtools-focused');
  603. await waitForEvent(webview, 'dom-ready');
  604. webview.openDevTools();
  605. await waitForDevToolsFocused;
  606. webview.closeDevTools();
  607. });
  608. });
  609. describe('<webview>.reload()', () => {
  610. it('should emit beforeunload handler', async () => {
  611. await loadWebView(webview, {
  612. nodeintegration: 'on',
  613. webpreferences: 'contextIsolation=no',
  614. src: `file://${fixtures}/pages/beforeunload-false.html`
  615. });
  616. // Event handler has to be added before reload.
  617. const waitForOnbeforeunload = waitForEvent(webview, 'ipc-message');
  618. webview.reload();
  619. const { channel } = await waitForOnbeforeunload;
  620. expect(channel).to.equal('onbeforeunload');
  621. });
  622. });
  623. describe('<webview>.goForward()', () => {
  624. it('should work after a replaced history entry', (done) => {
  625. let loadCount = 1;
  626. const listener = (e) => {
  627. if (loadCount === 1) {
  628. expect(e.channel).to.equal('history');
  629. expect(e.args[0]).to.equal(1);
  630. expect(webview.canGoBack()).to.be.false();
  631. expect(webview.canGoForward()).to.be.false();
  632. } else if (loadCount === 2) {
  633. expect(e.channel).to.equal('history');
  634. expect(e.args[0]).to.equal(2);
  635. expect(webview.canGoBack()).to.be.false();
  636. expect(webview.canGoForward()).to.be.true();
  637. webview.removeEventListener('ipc-message', listener);
  638. }
  639. };
  640. const loadListener = () => {
  641. try {
  642. if (loadCount === 1) {
  643. webview.src = `file://${fixtures}/pages/base-page.html`;
  644. } else if (loadCount === 2) {
  645. expect(webview.canGoBack()).to.be.true();
  646. expect(webview.canGoForward()).to.be.false();
  647. webview.goBack();
  648. } else if (loadCount === 3) {
  649. webview.goForward();
  650. } else if (loadCount === 4) {
  651. expect(webview.canGoBack()).to.be.true();
  652. expect(webview.canGoForward()).to.be.false();
  653. webview.removeEventListener('did-finish-load', loadListener);
  654. done();
  655. }
  656. loadCount += 1;
  657. } catch (e) {
  658. done(e);
  659. }
  660. };
  661. webview.addEventListener('ipc-message', listener);
  662. webview.addEventListener('did-finish-load', loadListener);
  663. loadWebView(webview, {
  664. nodeintegration: 'on',
  665. src: `file://${fixtures}/pages/history-replace.html`
  666. });
  667. });
  668. });
  669. // FIXME: https://github.com/electron/electron/issues/19397
  670. xdescribe('<webview>.clearHistory()', () => {
  671. it('should clear the navigation history', async () => {
  672. const message = waitForEvent(webview, 'ipc-message');
  673. await loadWebView(webview, {
  674. nodeintegration: 'on',
  675. src: `file://${fixtures}/pages/history.html`
  676. });
  677. const event = await message;
  678. expect(event.channel).to.equal('history');
  679. expect(event.args[0]).to.equal(2);
  680. expect(webview.canGoBack()).to.be.true();
  681. webview.clearHistory();
  682. expect(webview.canGoBack()).to.be.false();
  683. });
  684. });
  685. describe('basic auth', () => {
  686. const auth = require('basic-auth');
  687. it('should authenticate with correct credentials', (done) => {
  688. const message = 'Authenticated';
  689. const server = http.createServer((req, res) => {
  690. const credentials = auth(req);
  691. if (credentials.name === 'test' && credentials.pass === 'test') {
  692. res.end(message);
  693. } else {
  694. res.end('failed');
  695. }
  696. server.close();
  697. });
  698. server.listen(0, '127.0.0.1', () => {
  699. const port = server.address().port;
  700. webview.addEventListener('ipc-message', (e) => {
  701. try {
  702. expect(e.channel).to.equal(message);
  703. done();
  704. } catch (e) {
  705. done(e);
  706. }
  707. });
  708. loadWebView(webview, {
  709. nodeintegration: 'on',
  710. webpreferences: 'contextIsolation=no',
  711. src: `file://${fixtures}/pages/basic-auth.html?port=${port}`
  712. });
  713. });
  714. });
  715. });
  716. describe('dom-ready event', () => {
  717. it('emits when document is loaded', (done) => {
  718. const server = http.createServer(() => {});
  719. server.listen(0, '127.0.0.1', () => {
  720. const port = server.address().port;
  721. webview.addEventListener('dom-ready', () => {
  722. done();
  723. });
  724. loadWebView(webview, {
  725. src: `file://${fixtures}/pages/dom-ready.html?port=${port}`
  726. });
  727. });
  728. });
  729. it('throws a custom error when an API method is called before the event is emitted', () => {
  730. const expectedErrorMessage =
  731. 'The WebView must be attached to the DOM ' +
  732. 'and the dom-ready event emitted before this method can be called.';
  733. expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
  734. });
  735. });
  736. describe('executeJavaScript', () => {
  737. it('should support user gesture', async () => {
  738. await loadWebView(webview, {
  739. src: `file://${fixtures}/pages/fullscreen.html`
  740. });
  741. // Event handler has to be added before js execution.
  742. const waitForEnterHtmlFullScreen = waitForEvent(webview, 'enter-html-full-screen');
  743. const jsScript = "document.querySelector('video').webkitRequestFullscreen()";
  744. webview.executeJavaScript(jsScript, true);
  745. return waitForEnterHtmlFullScreen;
  746. });
  747. it('can return the result of the executed script', async () => {
  748. await loadWebView(webview, {
  749. src: 'about:blank'
  750. });
  751. const jsScript = "'4'+2";
  752. const expectedResult = '42';
  753. const result = await webview.executeJavaScript(jsScript);
  754. expect(result).to.equal(expectedResult);
  755. });
  756. });
  757. it('supports inserting CSS', async () => {
  758. await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });
  759. await webview.insertCSS('body { background-repeat: round; }');
  760. const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  761. expect(result).to.equal('round');
  762. });
  763. it('supports removing inserted CSS', async () => {
  764. await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });
  765. const key = await webview.insertCSS('body { background-repeat: round; }');
  766. await webview.removeInsertedCSS(key);
  767. const result = await webview.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")');
  768. expect(result).to.equal('repeat');
  769. });
  770. describe('sendInputEvent', () => {
  771. it('can send keyboard event', async () => {
  772. loadWebView(webview, {
  773. nodeintegration: 'on',
  774. webpreferences: 'contextIsolation=no',
  775. src: `file://${fixtures}/pages/onkeyup.html`
  776. });
  777. await waitForEvent(webview, 'dom-ready');
  778. const waitForIpcMessage = waitForEvent(webview, 'ipc-message');
  779. webview.sendInputEvent({
  780. type: 'keyup',
  781. keyCode: 'c',
  782. modifiers: ['shift']
  783. });
  784. const { channel, args } = await waitForIpcMessage;
  785. expect(channel).to.equal('keyup');
  786. expect(args).to.deep.equal(['C', 'KeyC', 67, true, false]);
  787. });
  788. it('can send mouse event', async () => {
  789. loadWebView(webview, {
  790. nodeintegration: 'on',
  791. webpreferences: 'contextIsolation=no',
  792. src: `file://${fixtures}/pages/onmouseup.html`
  793. });
  794. await waitForEvent(webview, 'dom-ready');
  795. const waitForIpcMessage = waitForEvent(webview, 'ipc-message');
  796. webview.sendInputEvent({
  797. type: 'mouseup',
  798. modifiers: ['ctrl'],
  799. x: 10,
  800. y: 20
  801. });
  802. const { channel, args } = await waitForIpcMessage;
  803. expect(channel).to.equal('mouseup');
  804. expect(args).to.deep.equal([10, 20, false, true]);
  805. });
  806. });
  807. describe('media-started-playing media-paused events', () => {
  808. beforeEach(function () {
  809. if (!document.createElement('audio').canPlayType('audio/wav')) {
  810. this.skip();
  811. }
  812. });
  813. it('emits when audio starts and stops playing', async () => {
  814. await loadWebView(webview, { src: `file://${fixtures}/pages/base-page.html` });
  815. // With the new autoplay policy, audio elements must be unmuted
  816. // see https://goo.gl/xX8pDD.
  817. const source = `
  818. const audio = document.createElement("audio")
  819. audio.src = "../assets/tone.wav"
  820. document.body.appendChild(audio);
  821. audio.play()
  822. `;
  823. webview.executeJavaScript(source, true);
  824. await waitForEvent(webview, 'media-started-playing');
  825. webview.executeJavaScript('document.querySelector("audio").pause()', true);
  826. await waitForEvent(webview, 'media-paused');
  827. });
  828. });
  829. describe('<webview>.getWebContentsId', () => {
  830. it('can return the WebContents ID', async () => {
  831. const src = 'about:blank';
  832. await loadWebView(webview, { src });
  833. expect(webview.getWebContentsId()).to.be.a('number');
  834. });
  835. });
  836. describe('<webview>.capturePage()', () => {
  837. before(function () {
  838. // TODO(miniak): figure out why this is failing on windows
  839. if (process.platform === 'win32') {
  840. this.skip();
  841. }
  842. });
  843. it('returns a Promise with a NativeImage', async () => {
  844. const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
  845. await loadWebView(webview, { src });
  846. const image = await webview.capturePage();
  847. const imgBuffer = image.toPNG();
  848. // Check the 25th byte in the PNG.
  849. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha
  850. expect(imgBuffer[25]).to.equal(6);
  851. });
  852. });
  853. ifdescribe(features.isPrintingEnabled())('<webview>.printToPDF()', () => {
  854. it('rejects on incorrectly typed parameters', async () => {
  855. const badTypes = {
  856. marginsType: 'terrible',
  857. scaleFactor: 'not-a-number',
  858. landscape: [],
  859. pageRanges: { oops: 'im-not-the-right-key' },
  860. headerFooter: '123',
  861. printSelectionOnly: 1,
  862. printBackground: 2,
  863. pageSize: 'IAmAPageSize'
  864. };
  865. // These will hard crash in Chromium unless we type-check
  866. for (const [key, value] of Object.entries(badTypes)) {
  867. const param = { [key]: value };
  868. const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
  869. await loadWebView(webview, { src });
  870. await expect(webview.printToPDF(param)).to.eventually.be.rejected();
  871. }
  872. });
  873. it('can print to PDF', async () => {
  874. const src = 'data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E';
  875. await loadWebView(webview, { src });
  876. const data = await webview.printToPDF({});
  877. expect(data).to.be.an.instanceof(Uint8Array).that.is.not.empty();
  878. });
  879. });
  880. describe('will-attach-webview event', () => {
  881. it('does not emit when src is not changed', async () => {
  882. console.log('loadWebView(webview)');
  883. loadWebView(webview);
  884. await delay();
  885. const expectedErrorMessage =
  886. 'The WebView must be attached to the DOM ' +
  887. 'and the dom-ready event emitted before this method can be called.';
  888. expect(() => { webview.stop(); }).to.throw(expectedErrorMessage);
  889. });
  890. it('supports changing the web preferences', async () => {
  891. ipcRenderer.send('disable-node-on-next-will-attach-webview');
  892. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  893. nodeintegration: 'yes',
  894. src: `file://${fixtures}/pages/a.html`
  895. });
  896. const types = JSON.parse(message);
  897. expect(types).to.include({
  898. require: 'undefined',
  899. module: 'undefined',
  900. process: 'undefined',
  901. global: 'undefined'
  902. });
  903. });
  904. it('supports preventing a webview from being created', async () => {
  905. ipcRenderer.send('prevent-next-will-attach-webview');
  906. loadWebView(webview, {
  907. src: `file://${fixtures}/pages/c.html`
  908. });
  909. await waitForEvent(webview, 'destroyed');
  910. });
  911. it('supports removing the preload script', async () => {
  912. ipcRenderer.send('disable-preload-on-next-will-attach-webview');
  913. const message = await startLoadingWebViewAndWaitForMessage(webview, {
  914. nodeintegration: 'yes',
  915. preload: path.join(fixtures, 'module', 'preload-set-global.js'),
  916. src: `file://${fixtures}/pages/a.html`
  917. });
  918. expect(message).to.equal('undefined');
  919. });
  920. });
  921. describe('DOM events', () => {
  922. let div;
  923. beforeEach(() => {
  924. div = document.createElement('div');
  925. div.style.width = '100px';
  926. div.style.height = '10px';
  927. div.style.overflow = 'hidden';
  928. webview.style.height = '100%';
  929. webview.style.width = '100%';
  930. });
  931. afterEach(() => {
  932. if (div != null) div.remove();
  933. });
  934. const generateSpecs = (description, sandbox) => {
  935. describe(description, () => {
  936. // TODO(nornagon): disabled during chromium roll 2019-06-11 due to a
  937. // 'ResizeObserver loop limit exceeded' error on Windows
  938. xit('emits resize events', async () => {
  939. const firstResizeSignal = waitForEvent(webview, 'resize');
  940. const domReadySignal = waitForEvent(webview, 'dom-ready');
  941. webview.src = `file://${fixtures}/pages/a.html`;
  942. webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`;
  943. div.appendChild(webview);
  944. document.body.appendChild(div);
  945. const firstResizeEvent = await firstResizeSignal;
  946. expect(firstResizeEvent.target).to.equal(webview);
  947. expect(firstResizeEvent.newWidth).to.equal(100);
  948. expect(firstResizeEvent.newHeight).to.equal(10);
  949. await domReadySignal;
  950. const secondResizeSignal = waitForEvent(webview, 'resize');
  951. const newWidth = 1234;
  952. const newHeight = 789;
  953. div.style.width = `${newWidth}px`;
  954. div.style.height = `${newHeight}px`;
  955. const secondResizeEvent = await secondResizeSignal;
  956. expect(secondResizeEvent.target).to.equal(webview);
  957. expect(secondResizeEvent.newWidth).to.equal(newWidth);
  958. expect(secondResizeEvent.newHeight).to.equal(newHeight);
  959. });
  960. it('emits focus event', async () => {
  961. const domReadySignal = waitForEvent(webview, 'dom-ready');
  962. webview.src = `file://${fixtures}/pages/a.html`;
  963. webview.webpreferences = `sandbox=${sandbox ? 'yes' : 'no'}`;
  964. document.body.appendChild(webview);
  965. await domReadySignal;
  966. // If this test fails, check if webview.focus() still works.
  967. const focusSignal = waitForEvent(webview, 'focus');
  968. webview.focus();
  969. await focusSignal;
  970. });
  971. });
  972. };
  973. generateSpecs('without sandbox', false);
  974. generateSpecs('with sandbox', true);
  975. });
  976. });