webview-spec.js 40 KB

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