chromium-spec.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. const { expect } = require('chai');
  2. const fs = require('fs');
  3. const http = require('http');
  4. const path = require('path');
  5. const ws = require('ws');
  6. const url = require('url');
  7. const ChildProcess = require('child_process');
  8. const { ipcRenderer } = require('electron');
  9. const { emittedOnce, waitForEvent } = require('./events-helpers');
  10. const { resolveGetters } = require('./expect-helpers');
  11. const { ifit, ifdescribe, delay } = require('./spec-helpers');
  12. const features = process._linkedBinding('electron_common_features');
  13. /* Most of the APIs here don't use standard callbacks */
  14. /* eslint-disable standard/no-callback-literal */
  15. describe('chromium feature', () => {
  16. const fixtures = path.resolve(__dirname, 'fixtures');
  17. describe('Badging API', () => {
  18. it('does not crash', () => {
  19. expect(() => {
  20. navigator.setAppBadge(42);
  21. }).to.not.throw();
  22. expect(() => {
  23. // setAppBadge with no argument should show dot
  24. navigator.setAppBadge();
  25. }).to.not.throw();
  26. expect(() => {
  27. navigator.clearAppBadge();
  28. }).to.not.throw();
  29. });
  30. });
  31. describe('heap snapshot', () => {
  32. it('does not crash', function () {
  33. process._linkedBinding('electron_common_v8_util').takeHeapSnapshot();
  34. });
  35. });
  36. describe('navigator.webkitGetUserMedia', () => {
  37. it('calls its callbacks', (done) => {
  38. navigator.webkitGetUserMedia({
  39. audio: true,
  40. video: false
  41. }, () => done(),
  42. () => done());
  43. });
  44. });
  45. describe('navigator.language', () => {
  46. it('should not be empty', () => {
  47. expect(navigator.language).to.not.equal('');
  48. });
  49. });
  50. ifdescribe(features.isFakeLocationProviderEnabled())('navigator.geolocation', () => {
  51. it('returns position when permission is granted', async () => {
  52. const position = await new Promise((resolve, reject) => navigator.geolocation.getCurrentPosition(resolve, reject));
  53. expect(position).to.have.a.property('coords');
  54. expect(position).to.have.a.property('timestamp');
  55. });
  56. });
  57. describe('window.open', () => {
  58. it('accepts "nodeIntegration" as feature', async () => {
  59. const message = waitForEvent(window, 'message');
  60. const b = window.open(`file://${fixtures}/pages/window-opener-node.html`, '', 'nodeIntegration=no,show=no');
  61. const event = await message;
  62. b.close();
  63. expect(event.data.isProcessGlobalUndefined).to.be.true();
  64. });
  65. it('inherit options of parent window', async () => {
  66. const message = waitForEvent(window, 'message');
  67. const b = window.open(`file://${fixtures}/pages/window-open-size.html`, '', 'show=no');
  68. const event = await message;
  69. b.close();
  70. const width = outerWidth;
  71. const height = outerHeight;
  72. expect(event.data).to.equal(`size: ${width} ${height}`);
  73. });
  74. // FIXME(zcbenz): This test is making the spec runner hang on exit on Windows.
  75. ifit(process.platform !== 'win32')('disables node integration when it is disabled on the parent window', async () => {
  76. const windowUrl = require('url').format({
  77. pathname: `${fixtures}/pages/window-opener-no-node-integration.html`,
  78. protocol: 'file',
  79. query: {
  80. p: `${fixtures}/pages/window-opener-node.html`
  81. },
  82. slashes: true
  83. });
  84. const message = waitForEvent(window, 'message');
  85. const b = window.open(windowUrl, '', 'nodeIntegration=no,contextIsolation=no,show=no');
  86. const event = await message;
  87. b.close();
  88. expect(event.data.isProcessGlobalUndefined).to.be.true();
  89. });
  90. it('disables the <webview> tag when it is disabled on the parent window', async () => {
  91. const windowUrl = require('url').format({
  92. pathname: `${fixtures}/pages/window-opener-no-webview-tag.html`,
  93. protocol: 'file',
  94. query: {
  95. p: `${fixtures}/pages/window-opener-webview.html`
  96. },
  97. slashes: true
  98. });
  99. const message = waitForEvent(window, 'message');
  100. const b = window.open(windowUrl, '', 'webviewTag=no,contextIsolation=no,nodeIntegration=yes,show=no');
  101. const event = await message;
  102. b.close();
  103. expect(event.data.isWebViewGlobalUndefined).to.be.true();
  104. });
  105. it('does not override child options', async () => {
  106. const size = {
  107. width: 350,
  108. height: 450
  109. };
  110. const message = waitForEvent(window, 'message');
  111. const b = window.open(`file://${fixtures}/pages/window-open-size.html`, '', 'show=no,width=' + size.width + ',height=' + size.height);
  112. const event = await message;
  113. b.close();
  114. expect(event.data).to.equal(`size: ${size.width} ${size.height}`);
  115. });
  116. it('throws an exception when the arguments cannot be converted to strings', () => {
  117. expect(() => {
  118. window.open('', { toString: null });
  119. }).to.throw('Cannot convert object to primitive value');
  120. expect(() => {
  121. window.open('', '', { toString: 3 });
  122. }).to.throw('Cannot convert object to primitive value');
  123. });
  124. it('does not throw an exception when the features include webPreferences', () => {
  125. let b = null;
  126. expect(() => {
  127. b = window.open('', '', 'webPreferences=');
  128. }).to.not.throw();
  129. b.close();
  130. });
  131. });
  132. describe('window.opener', () => {
  133. it('is not null for window opened by window.open', async () => {
  134. const message = waitForEvent(window, 'message');
  135. const b = window.open(`file://${fixtures}/pages/window-opener.html`, '', 'show=no');
  136. const event = await message;
  137. b.close();
  138. expect(event.data).to.equal('object');
  139. });
  140. });
  141. describe('window.opener.postMessage', () => {
  142. it('sets source and origin correctly', async () => {
  143. const message = waitForEvent(window, 'message');
  144. const b = window.open(`file://${fixtures}/pages/window-opener-postMessage.html`, '', 'show=no');
  145. const event = await message;
  146. try {
  147. expect(event.source).to.deep.equal(b);
  148. expect(event.origin).to.equal('file://');
  149. } finally {
  150. b.close();
  151. }
  152. });
  153. it('supports windows opened from a <webview>', async () => {
  154. const webview = new WebView();
  155. const consoleMessage = waitForEvent(webview, 'console-message');
  156. webview.allowpopups = true;
  157. webview.setAttribute('webpreferences', 'contextIsolation=no');
  158. webview.src = url.format({
  159. pathname: `${fixtures}/pages/webview-opener-postMessage.html`,
  160. protocol: 'file',
  161. query: {
  162. p: `${fixtures}/pages/window-opener-postMessage.html`
  163. },
  164. slashes: true
  165. });
  166. document.body.appendChild(webview);
  167. const event = await consoleMessage;
  168. webview.remove();
  169. expect(event.message).to.equal('message');
  170. });
  171. describe('targetOrigin argument', () => {
  172. let serverURL;
  173. let server;
  174. beforeEach((done) => {
  175. server = http.createServer((req, res) => {
  176. res.writeHead(200);
  177. const filePath = path.join(fixtures, 'pages', 'window-opener-targetOrigin.html');
  178. res.end(fs.readFileSync(filePath, 'utf8'));
  179. });
  180. server.listen(0, '127.0.0.1', () => {
  181. serverURL = `http://127.0.0.1:${server.address().port}`;
  182. done();
  183. });
  184. });
  185. afterEach(() => {
  186. server.close();
  187. });
  188. it('delivers messages that match the origin', async () => {
  189. const message = waitForEvent(window, 'message');
  190. const b = window.open(serverURL, '', 'show=no,contextIsolation=no,nodeIntegration=yes');
  191. const event = await message;
  192. b.close();
  193. expect(event.data).to.equal('deliver');
  194. });
  195. });
  196. });
  197. describe('webgl', () => {
  198. before(function () {
  199. if (process.platform === 'win32') {
  200. this.skip();
  201. }
  202. });
  203. it('can be get as context in canvas', () => {
  204. if (process.platform === 'linux') {
  205. // FIXME(alexeykuzmin): Skip the test.
  206. // this.skip()
  207. return;
  208. }
  209. const webgl = document.createElement('canvas').getContext('webgl');
  210. expect(webgl).to.not.be.null();
  211. });
  212. });
  213. describe('web workers', () => {
  214. it('Worker can work', async () => {
  215. const worker = new Worker('../fixtures/workers/worker.js');
  216. const message = 'ping';
  217. const eventPromise = new Promise((resolve) => { worker.onmessage = resolve; });
  218. worker.postMessage(message);
  219. const event = await eventPromise;
  220. worker.terminate();
  221. expect(event.data).to.equal(message);
  222. });
  223. it('Worker has no node integration by default', async () => {
  224. const worker = new Worker('../fixtures/workers/worker_node.js');
  225. const event = await new Promise((resolve) => { worker.onmessage = resolve; });
  226. worker.terminate();
  227. expect(event.data).to.equal('undefined undefined undefined undefined');
  228. });
  229. it('Worker has node integration with nodeIntegrationInWorker', async () => {
  230. const webview = new WebView();
  231. const eventPromise = waitForEvent(webview, 'ipc-message');
  232. webview.src = `file://${fixtures}/pages/worker.html`;
  233. webview.setAttribute('webpreferences', 'nodeIntegration, nodeIntegrationInWorker, contextIsolation=no');
  234. document.body.appendChild(webview);
  235. const event = await eventPromise;
  236. webview.remove();
  237. expect(event.channel).to.equal('object function object function');
  238. });
  239. describe('SharedWorker', () => {
  240. it('can work', async () => {
  241. const worker = new SharedWorker('../fixtures/workers/shared_worker.js');
  242. const message = 'ping';
  243. const eventPromise = new Promise((resolve) => { worker.port.onmessage = resolve; });
  244. worker.port.postMessage(message);
  245. const event = await eventPromise;
  246. expect(event.data).to.equal(message);
  247. });
  248. it('has no node integration by default', async () => {
  249. const worker = new SharedWorker('../fixtures/workers/shared_worker_node.js');
  250. const event = await new Promise((resolve) => { worker.port.onmessage = resolve; });
  251. expect(event.data).to.equal('undefined undefined undefined undefined');
  252. });
  253. it('has node integration with nodeIntegrationInWorker', async () => {
  254. const webview = new WebView();
  255. webview.addEventListener('console-message', (e) => {
  256. console.log(e);
  257. });
  258. const eventPromise = waitForEvent(webview, 'ipc-message');
  259. webview.src = `file://${fixtures}/pages/shared_worker.html`;
  260. webview.setAttribute('webpreferences', 'nodeIntegration, nodeIntegrationInWorker, contextIsolation=no');
  261. document.body.appendChild(webview);
  262. const event = await eventPromise;
  263. webview.remove();
  264. expect(event.channel).to.equal('object function object function');
  265. });
  266. });
  267. });
  268. describe('iframe', () => {
  269. let iframe = null;
  270. beforeEach(() => {
  271. iframe = document.createElement('iframe');
  272. });
  273. afterEach(() => {
  274. document.body.removeChild(iframe);
  275. });
  276. it('does not have node integration', async () => {
  277. iframe.src = `file://${fixtures}/pages/set-global.html`;
  278. document.body.appendChild(iframe);
  279. await waitForEvent(iframe, 'load');
  280. expect(iframe.contentWindow.test).to.equal('undefined undefined undefined');
  281. });
  282. });
  283. describe('storage', () => {
  284. describe('DOM storage quota increase', () => {
  285. ['localStorage', 'sessionStorage'].forEach((storageName) => {
  286. const storage = window[storageName];
  287. it(`allows saving at least 40MiB in ${storageName}`, async () => {
  288. // Although JavaScript strings use UTF-16, the underlying
  289. // storage provider may encode strings differently, muddling the
  290. // translation between character and byte counts. However,
  291. // a string of 40 * 2^20 characters will require at least 40MiB
  292. // and presumably no more than 80MiB, a size guaranteed to
  293. // to exceed the original 10MiB quota yet stay within the
  294. // new 100MiB quota.
  295. // Note that both the key name and value affect the total size.
  296. const testKeyName = '_electronDOMStorageQuotaIncreasedTest';
  297. const length = 40 * Math.pow(2, 20) - testKeyName.length;
  298. storage.setItem(testKeyName, 'X'.repeat(length));
  299. // Wait at least one turn of the event loop to help avoid false positives
  300. // Although not entirely necessary, the previous version of this test case
  301. // failed to detect a real problem (perhaps related to DOM storage data caching)
  302. // wherein calling `getItem` immediately after `setItem` would appear to work
  303. // but then later (e.g. next tick) it would not.
  304. await delay(1);
  305. try {
  306. expect(storage.getItem(testKeyName)).to.have.lengthOf(length);
  307. } finally {
  308. storage.removeItem(testKeyName);
  309. }
  310. });
  311. it(`throws when attempting to use more than 128MiB in ${storageName}`, () => {
  312. expect(() => {
  313. const testKeyName = '_electronDOMStorageQuotaStillEnforcedTest';
  314. const length = 128 * Math.pow(2, 20) - testKeyName.length;
  315. try {
  316. storage.setItem(testKeyName, 'X'.repeat(length));
  317. } finally {
  318. storage.removeItem(testKeyName);
  319. }
  320. }).to.throw();
  321. });
  322. });
  323. });
  324. it('requesting persistent quota works', async () => {
  325. const grantedBytes = await new Promise(resolve => {
  326. navigator.webkitPersistentStorage.requestQuota(1024 * 1024, resolve);
  327. });
  328. expect(grantedBytes).to.equal(1048576);
  329. });
  330. });
  331. describe('websockets', () => {
  332. let wss = null;
  333. let server = null;
  334. const WebSocketServer = ws.Server;
  335. afterEach(() => {
  336. wss.close();
  337. server.close();
  338. });
  339. it('has user agent', (done) => {
  340. server = http.createServer();
  341. server.listen(0, '127.0.0.1', () => {
  342. const port = server.address().port;
  343. wss = new WebSocketServer({ server: server });
  344. wss.on('error', done);
  345. wss.on('connection', (ws, upgradeReq) => {
  346. if (upgradeReq.headers['user-agent']) {
  347. done();
  348. } else {
  349. done('user agent is empty');
  350. }
  351. });
  352. const socket = new WebSocket(`ws://127.0.0.1:${port}`);
  353. });
  354. });
  355. });
  356. describe('Promise', () => {
  357. it('resolves correctly in Node.js calls', (done) => {
  358. class XElement extends HTMLElement {}
  359. customElements.define('x-element', XElement);
  360. setImmediate(() => {
  361. let called = false;
  362. Promise.resolve().then(() => {
  363. done(called ? undefined : new Error('wrong sequence'));
  364. });
  365. document.createElement('x-element');
  366. called = true;
  367. });
  368. });
  369. it('resolves correctly in Electron calls', (done) => {
  370. class YElement extends HTMLElement {}
  371. customElements.define('y-element', YElement);
  372. ipcRenderer.invoke('ping').then(() => {
  373. let called = false;
  374. Promise.resolve().then(() => {
  375. done(called ? undefined : new Error('wrong sequence'));
  376. });
  377. document.createElement('y-element');
  378. called = true;
  379. });
  380. });
  381. });
  382. describe('fetch', () => {
  383. it('does not crash', (done) => {
  384. const server = http.createServer((req, res) => {
  385. res.end('test');
  386. server.close();
  387. });
  388. server.listen(0, '127.0.0.1', () => {
  389. const port = server.address().port;
  390. fetch(`http://127.0.0.1:${port}`).then((res) => res.body.getReader())
  391. .then((reader) => {
  392. reader.read().then((r) => {
  393. reader.cancel();
  394. done();
  395. });
  396. }).catch((e) => done(e));
  397. });
  398. });
  399. });
  400. describe('window.alert(message, title)', () => {
  401. it('throws an exception when the arguments cannot be converted to strings', () => {
  402. expect(() => {
  403. window.alert({ toString: null });
  404. }).to.throw('Cannot convert object to primitive value');
  405. });
  406. });
  407. describe('window.confirm(message, title)', () => {
  408. it('throws an exception when the arguments cannot be converted to strings', () => {
  409. expect(() => {
  410. window.confirm({ toString: null }, 'title');
  411. }).to.throw('Cannot convert object to primitive value');
  412. });
  413. });
  414. describe('window.history', () => {
  415. describe('window.history.go(offset)', () => {
  416. it('throws an exception when the argument cannot be converted to a string', () => {
  417. expect(() => {
  418. window.history.go({ toString: null });
  419. }).to.throw('Cannot convert object to primitive value');
  420. });
  421. });
  422. });
  423. // TODO(nornagon): this is broken on CI, it triggers:
  424. // [FATAL:speech_synthesis.mojom-shared.h(237)] The outgoing message will
  425. // trigger VALIDATION_ERROR_UNEXPECTED_NULL_POINTER at the receiving side
  426. // (null text in SpeechSynthesisUtterance struct).
  427. describe.skip('SpeechSynthesis', () => {
  428. before(function () {
  429. if (!features.isTtsEnabled()) {
  430. this.skip();
  431. }
  432. });
  433. it('should emit lifecycle events', async () => {
  434. const sentence = `long sentence which will take at least a few seconds to
  435. utter so that it's possible to pause and resume before the end`;
  436. const utter = new SpeechSynthesisUtterance(sentence);
  437. // Create a dummy utterance so that speech synthesis state
  438. // is initialized for later calls.
  439. speechSynthesis.speak(new SpeechSynthesisUtterance());
  440. speechSynthesis.cancel();
  441. speechSynthesis.speak(utter);
  442. // paused state after speak()
  443. expect(speechSynthesis.paused).to.be.false();
  444. await new Promise((resolve) => { utter.onstart = resolve; });
  445. // paused state after start event
  446. expect(speechSynthesis.paused).to.be.false();
  447. speechSynthesis.pause();
  448. // paused state changes async, right before the pause event
  449. expect(speechSynthesis.paused).to.be.false();
  450. await new Promise((resolve) => { utter.onpause = resolve; });
  451. expect(speechSynthesis.paused).to.be.true();
  452. speechSynthesis.resume();
  453. await new Promise((resolve) => { utter.onresume = resolve; });
  454. // paused state after resume event
  455. expect(speechSynthesis.paused).to.be.false();
  456. await new Promise((resolve) => { utter.onend = resolve; });
  457. });
  458. });
  459. });
  460. describe('console functions', () => {
  461. it('should exist', () => {
  462. expect(console.log, 'log').to.be.a('function');
  463. expect(console.error, 'error').to.be.a('function');
  464. expect(console.warn, 'warn').to.be.a('function');
  465. expect(console.info, 'info').to.be.a('function');
  466. expect(console.debug, 'debug').to.be.a('function');
  467. expect(console.trace, 'trace').to.be.a('function');
  468. expect(console.time, 'time').to.be.a('function');
  469. expect(console.timeEnd, 'timeEnd').to.be.a('function');
  470. });
  471. });