webview-spec.js 40 KB

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