webview-spec.js 41 KB

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