webview-spec.js 41 KB

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