webview-spec.js 41 KB

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