webview-spec.js 38 KB

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