status
stringclasses
1 value
repo_name
stringclasses
31 values
repo_url
stringclasses
31 values
issue_id
int64
1
104k
title
stringlengths
4
369
body
stringlengths
0
254k
issue_url
stringlengths
37
56
pull_url
stringlengths
37
54
before_fix_sha
stringlengths
40
40
after_fix_sha
stringlengths
40
40
report_datetime
timestamp[us, tz=UTC]
language
stringclasses
5 values
commit_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
4
188
file_content
stringlengths
0
5.12M
closed
electron/electron
https://github.com/electron/electron
22,201
Add 'focus' & 'blur' events to BrowserView/WebContents
### Preflight Checklist * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description When working with BrowserViews, there's no way to listen to focus changes on either BrowserView itself or its WebContents. ### Proposed Solution On BrowserWindow, there are `focus` and `blur` events. The same events need to be emitted on BrowserView/WebContents. i.e. : ``` browserView.on('focus', () => { // view is focused, do stuff }); ``` or ``` browserView.webContents.on('focus', () => { // contents are focused, do stuff }); ``` ### Alternatives Considered I can't think of a good way of working around this lack of functionality
https://github.com/electron/electron/issues/22201
https://github.com/electron/electron/pull/25873
e34d7f5d6f7c34332a11010ca786e2e1271b2629
aeee9cfb7876a770fed9a1dc9669c2beeacf9ed9
2020-02-14T21:24:32Z
c++
2022-02-01T10:28:57Z
spec-main/api-web-contents-spec.ts
import { expect } from 'chai'; import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; import { clipboard } from 'electron/common'; import { emittedOnce } from './events-helpers'; import { closeAllWindows } from './window-helpers'; import { ifdescribe, ifit, delay, defer } from './spec-helpers'; const pdfjs = require('pdfjs-dist'); const fixturesPath = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixturesPath = path.resolve(__dirname, 'fixtures'); const features = process._linkedBinding('electron_common_features'); describe('webContents module', () => { describe('getAllWebContents() API', () => { afterEach(closeAllWindows); it('returns an array of web contents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'webview-zoom-factor.html')); await emittedOnce(w.webContents, 'did-attach-webview'); w.webContents.openDevTools(); await emittedOnce(w.webContents, 'devtools-opened'); const all = webContents.getAllWebContents().sort((a, b) => { return a.id - b.id; }); expect(all).to.have.length(3); expect(all[0].getType()).to.equal('window'); expect(all[all.length - 2].getType()).to.equal('webview'); expect(all[all.length - 1].getType()).to.equal('remote'); }); }); describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined(); }); }); describe('fromDevToolsTargetId()', () => { it('returns WebContents for attached DevTools target', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); try { await w.webContents.debugger.attach('1.3'); const { targetInfo } = await w.webContents.debugger.sendCommand('Target.getTargetInfo'); expect(webContents.fromDevToolsTargetId(targetInfo.targetId)).to.equal(w.webContents); } finally { await w.webContents.debugger.detach(); } }); it('returns undefined for an unknown id', () => { expect(webContents.fromDevToolsTargetId('nope')).to.be.undefined(); }); }); describe('will-prevent-unload event', function () { afterEach(closeAllWindows); it('does not emit if beforeunload returns undefined in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('does not emit if beforeunload returns undefined in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); view.webContents.once('will-prevent-unload', () => { expect.fail('should not have fired'); }); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits if beforeunload returns false in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'will-prevent-unload'); }); it('emits if beforeunload returns false in a BrowserView', async () => { const w = new BrowserWindow({ show: false }); const view = new BrowserView(); w.setBrowserView(view); view.setBounds(w.getBounds()); await view.webContents.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(view.webContents, 'will-prevent-unload'); }); it('supports calling preventDefault on will-prevent-unload events in a BrowserWindow', async () => { const w = new BrowserWindow({ show: false }); w.webContents.once('will-prevent-unload', event => event.preventDefault()); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); }); describe('webContents.send(channel, args...)', () => { afterEach(closeAllWindows); it('throws an error when the channel is missing', () => { const w = new BrowserWindow({ show: false }); expect(() => { (w.webContents.send as any)(); }).to.throw('Missing required channel argument'); expect(() => { w.webContents.send(null as any); }).to.throw('Missing required channel argument'); }); it('does not block node async APIs when sent before document is ready', (done) => { // Please reference https://github.com/electron/electron/issues/19368 if // this test fails. ipcMain.once('async-node-api-done', () => { done(); }); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, sandbox: false, contextIsolation: false } }); w.loadFile(path.join(fixturesPath, 'pages', 'send-after-node.html')); setTimeout(() => { w.webContents.send('test'); }, 50); }); }); ifdescribe(features.isPrintingEnabled())('webContents.print()', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('throws when invalid settings are passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print(true); }).to.throw('webContents.print(): Invalid print settings specified.'); }); it('throws when an invalid callback is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({}, true); }).to.throw('webContents.print(): Invalid optional callback provided.'); }); ifit(process.platform !== 'linux')('throws when an invalid deviceName is passed', () => { expect(() => { w.webContents.print({ deviceName: 'i-am-a-nonexistent-printer' }, () => {}); }).to.throw('webContents.print(): Invalid deviceName provided.'); }); it('throws when an invalid pageSize is passed', () => { expect(() => { // @ts-ignore this line is intentionally incorrect w.webContents.print({ pageSize: 'i-am-a-bad-pagesize' }, () => {}); }).to.throw('Unsupported pageSize: i-am-a-bad-pagesize'); }); it('throws when an invalid custom pageSize is passed', () => { expect(() => { w.webContents.print({ pageSize: { width: 100, height: 200 } }); }).to.throw('height and width properties must be minimum 352 microns.'); }); it('does not crash with custom margins', () => { expect(() => { w.webContents.print({ silent: true, margins: { marginType: 'custom', top: 1, bottom: 1, left: 1, right: 1 } }); }).to.not.throw(); }); }); describe('webContents.executeJavaScript', () => { describe('in about:blank', () => { const expected = 'hello, world!'; const expectedErrorMsg = 'woops!'; const code = `(() => "${expected}")()`; const asyncCode = `(() => new Promise(r => setTimeout(() => r("${expected}"), 500)))()`; const badAsyncCode = `(() => new Promise((r, e) => setTimeout(() => e("${expectedErrorMsg}"), 500)))()`; const errorTypes = new Set([ Error, ReferenceError, EvalError, RangeError, SyntaxError, TypeError, URIError ]); let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: false } }); await w.loadURL('about:blank'); }); after(closeAllWindows); it('resolves the returned promise with the result', async () => { const result = await w.webContents.executeJavaScript(code); expect(result).to.equal(expected); }); it('resolves the returned promise with the result if the code returns an asyncronous promise', async () => { const result = await w.webContents.executeJavaScript(asyncCode); expect(result).to.equal(expected); }); it('rejects the returned promise if an async error is thrown', async () => { await expect(w.webContents.executeJavaScript(badAsyncCode)).to.eventually.be.rejectedWith(expectedErrorMsg); }); it('rejects the returned promise with an error if an Error.prototype is thrown', async () => { for (const error of errorTypes) { await expect(w.webContents.executeJavaScript(`Promise.reject(new ${error.name}("Wamp-wamp"))`)) .to.eventually.be.rejectedWith(error); } }); }); describe('on a real page', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('works after page load and during subframe load', async () => { await w.loadURL(serverUrl); // initiate a sub-frame load, then try and execute script during it await w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/slow' document.body.appendChild(iframe) null // don't return the iframe `); await w.webContents.executeJavaScript('console.log(\'hello\')'); }); it('executes after page load', async () => { const executeJavaScript = w.webContents.executeJavaScript('(() => "test")()'); w.loadURL(serverUrl); const result = await executeJavaScript; expect(result).to.equal('test'); }); }); }); describe('webContents.executeJavaScriptInIsolatedWorld', () => { let w: BrowserWindow; before(async () => { w = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true } }); await w.loadURL('about:blank'); }); it('resolves the returned promise with the result', async () => { await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X = 123' }]); const isolatedResult = await w.webContents.executeJavaScriptInIsolatedWorld(999, [{ code: 'window.X' }]); const mainWorldResult = await w.webContents.executeJavaScript('window.X'); expect(isolatedResult).to.equal(123); expect(mainWorldResult).to.equal(undefined); }); }); describe('loadURL() promise API', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false }); }); afterEach(closeAllWindows); it('resolves when done loading', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('resolves when done loading a file URL', async () => { await expect(w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'))).to.eventually.be.fulfilled(); }); it('rejects when failing to load a file URL', async () => { await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FILE_NOT_FOUND'); }); // Temporarily disable on WOA until // https://github.com/electron/electron/issues/20008 is resolved const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('rejects when loading fails due to DNS not resolved', async () => { await expect(w.loadURL('https://err.name.not.resolved')).to.eventually.be.rejected() .and.have.property('code', 'ERR_NAME_NOT_RESOLVED'); }); it('rejects when navigation is cancelled due to a bad scheme', async () => { await expect(w.loadURL('bad-scheme://foo')).to.eventually.be.rejected() .and.have.property('code', 'ERR_FAILED'); }); it('sets appropriate error information on rejection', async () => { let err: any; try { await w.loadURL('file:non-existent'); } catch (e) { err = e; } expect(err).not.to.be.null(); expect(err.code).to.eql('ERR_FILE_NOT_FOUND'); expect(err.errno).to.eql(-6); expect(err.url).to.eql(process.platform === 'win32' ? 'file://non-existent/' : 'file:///non-existent'); }); it('rejects if the load is aborted', async () => { const s = http.createServer(() => { /* never complete the request */ }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = expect(w.loadURL(`http://127.0.0.1:${port}`)).to.eventually.be.rejectedWith(Error, /ERR_ABORTED/); // load a different file before the first load completes, causing the // first load to be aborted. await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); await p; s.close(); }); it("doesn't reject when a subframe fails to load", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="http://err.name.not.resolved"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.end(); await main; s.close(); }); it("doesn't resolve when a subframe loads", async () => { let resp = null as unknown as http.ServerResponse; const s = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('<iframe src="about:blank"></iframe>'); resp = res; // don't end the response yet }); await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve)); const { port } = s.address() as AddressInfo; const p = new Promise<void>(resolve => { w.webContents.on('did-frame-finish-load', (event, isMainFrame) => { if (!isMainFrame) { resolve(); } }); }); const main = w.loadURL(`http://127.0.0.1:${port}`); await p; resp.destroy(); // cause the main request to fail await expect(main).to.eventually.be.rejected() .and.have.property('errno', -355); // ERR_INCOMPLETE_CHUNKED_ENCODING s.close(); }); }); describe('getFocusedWebContents() API', () => { afterEach(closeAllWindows); const testFn = (process.platform === 'win32' && process.arch === 'arm64' ? it.skip : it); testFn('returns the focused web contents', async () => { const w = new BrowserWindow({ show: true }); await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html')); expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); const devToolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await devToolsOpened; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.devToolsWebContents!.id); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(webContents.getFocusedWebContents().id).to.equal(w.webContents.id); }); it('does not crash when called on a detached dev tools window', async () => { const w = new BrowserWindow({ show: true }); w.webContents.openDevTools({ mode: 'detach' }); w.webContents.inspectElement(100, 100); // For some reason we have to wait for two focused events...? await emittedOnce(w.webContents, 'devtools-focused'); expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); // Work around https://github.com/electron/electron/issues/19985 await delay(); const devToolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devToolsClosed; expect(() => { webContents.getFocusedWebContents(); }).to.not.throw(); }); }); describe('setDevToolsWebContents() API', () => { afterEach(closeAllWindows); it('sets arbitrary webContents as devtools', async () => { const w = new BrowserWindow({ show: false }); const devtools = new BrowserWindow({ show: false }); const promise = emittedOnce(devtools.webContents, 'dom-ready'); w.webContents.setDevToolsWebContents(devtools.webContents); w.webContents.openDevTools(); await promise; expect(devtools.webContents.getURL().startsWith('devtools://devtools')).to.be.true(); const result = await devtools.webContents.executeJavaScript('InspectorFrontendHost.constructor.name'); expect(result).to.equal('InspectorFrontendHostImpl'); devtools.destroy(); }); }); describe('isFocused() API', () => { it('returns false when the window is hidden', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(w.isVisible()).to.be.false(); expect(w.webContents.isFocused()).to.be.false(); }); }); describe('isCurrentlyAudible() API', () => { afterEach(closeAllWindows); it('returns whether audio is playing', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript(` window.context = new AudioContext // Start in suspended state, because of the // new web audio api policy. context.suspend() window.oscillator = context.createOscillator() oscillator.connect(context.destination) oscillator.start() `); let p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('context.resume()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.true(); p = emittedOnce(w.webContents, '-audio-state-changed'); w.webContents.executeJavaScript('oscillator.stop()'); await p; expect(w.webContents.isCurrentlyAudible()).to.be.false(); }); }); describe('openDevTools() API', () => { afterEach(closeAllWindows); it('can show window with activation', async () => { const w = new BrowserWindow({ show: false }); const focused = emittedOnce(w, 'focus'); w.show(); await focused; expect(w.isFocused()).to.be.true(); const blurred = emittedOnce(w, 'blur'); w.webContents.openDevTools({ mode: 'detach', activate: true }); await Promise.all([ emittedOnce(w.webContents, 'devtools-opened'), emittedOnce(w.webContents, 'devtools-focused') ]); await blurred; expect(w.isFocused()).to.be.false(); }); it('can show window without activation', async () => { const w = new BrowserWindow({ show: false }); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools({ mode: 'detach', activate: false }); await devtoolsOpened; expect(w.webContents.isDevToolsOpened()).to.be.true(); }); }); describe('before-input-event event', () => { afterEach(closeAllWindows); it('can prevent document keyboard events', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); const keyDown = new Promise(resolve => { ipcMain.once('keydown', (event, key) => resolve(key)); }); w.webContents.once('before-input-event', (event, input) => { if (input.key === 'a') event.preventDefault(); }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'a' }); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'b' }); expect(await keyDown).to.equal('b'); }); it('has the correct properties', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testBeforeInput = async (opts: any) => { const modifiers = []; if (opts.shift) modifiers.push('shift'); if (opts.control) modifiers.push('control'); if (opts.alt) modifiers.push('alt'); if (opts.meta) modifiers.push('meta'); if (opts.isAutoRepeat) modifiers.push('isAutoRepeat'); const p = emittedOnce(w.webContents, 'before-input-event'); w.webContents.sendInputEvent({ type: opts.type, keyCode: opts.keyCode, modifiers: modifiers as any }); const [, input] = await p; expect(input.type).to.equal(opts.type); expect(input.key).to.equal(opts.key); expect(input.code).to.equal(opts.code); expect(input.isAutoRepeat).to.equal(opts.isAutoRepeat); expect(input.shift).to.equal(opts.shift); expect(input.control).to.equal(opts.control); expect(input.alt).to.equal(opts.alt); expect(input.meta).to.equal(opts.meta); }; await testBeforeInput({ type: 'keyDown', key: 'A', code: 'KeyA', keyCode: 'a', shift: true, control: true, alt: true, meta: true, isAutoRepeat: true }); await testBeforeInput({ type: 'keyUp', key: '.', code: 'Period', keyCode: '.', shift: false, control: true, alt: true, meta: false, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: '!', code: 'Digit1', keyCode: '1', shift: true, control: false, alt: false, meta: true, isAutoRepeat: false }); await testBeforeInput({ type: 'keyUp', key: 'Tab', code: 'Tab', keyCode: 'Tab', shift: false, control: true, alt: false, meta: false, isAutoRepeat: true }); }); }); // On Mac, zooming isn't done with the mouse wheel. ifdescribe(process.platform !== 'darwin')('zoom-changed', () => { afterEach(closeAllWindows); it('is emitted with the correct zoom-in info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: 1, wheelTicksX: 0, wheelTicksY: 1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('in'); }; await testZoomChanged(); }); it('is emitted with the correct zoom-out info', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const testZoomChanged = async () => { w.webContents.sendInputEvent({ type: 'mouseWheel', x: 300, y: 300, deltaX: 0, deltaY: -1, wheelTicksX: 0, wheelTicksY: -1, modifiers: ['control', 'meta'] }); const [, zoomDirection] = await emittedOnce(w.webContents, 'zoom-changed'); expect(zoomDirection).to.equal('out'); }; await testZoomChanged(); }); }); describe('sendInputEvent(event)', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); }); afterEach(closeAllWindows); it('can send keydown events', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send keydown events with modifiers', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); it('can send keydown events with special keys', async () => { const keydown = emittedOnce(ipcMain, 'keydown'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Tab', modifiers: ['alt'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keydown; expect(key).to.equal('Tab'); expect(code).to.equal('Tab'); expect(keyCode).to.equal(9); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.true(); }); it('can send char events', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'A' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'A' }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('a'); expect(code).to.equal('KeyA'); expect(keyCode).to.equal(65); expect(shiftKey).to.be.false(); expect(ctrlKey).to.be.false(); expect(altKey).to.be.false(); }); it('can send char events with modifiers', async () => { const keypress = emittedOnce(ipcMain, 'keypress'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Z' }); w.webContents.sendInputEvent({ type: 'char', keyCode: 'Z', modifiers: ['shift', 'ctrl'] }); const [, key, code, keyCode, shiftKey, ctrlKey, altKey] = await keypress; expect(key).to.equal('Z'); expect(code).to.equal('KeyZ'); expect(keyCode).to.equal(90); expect(shiftKey).to.be.true(); expect(ctrlKey).to.be.true(); expect(altKey).to.be.false(); }); }); describe('insertCSS', () => { afterEach(closeAllWindows); it('supports inserting CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); await w.webContents.insertCSS('body { background-repeat: round; }'); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('round'); }); it('supports removing inserted CSS', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); const key = await w.webContents.insertCSS('body { background-repeat: round; }'); await w.webContents.removeInsertedCSS(key); const result = await w.webContents.executeJavaScript('window.getComputedStyle(document.body).getPropertyValue("background-repeat")'); expect(result).to.equal('repeat'); }); }); describe('inspectElement()', () => { afterEach(closeAllWindows); it('supports inspecting an element in the devtools', (done) => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.once('devtools-opened', () => { done(); }); w.webContents.inspectElement(10, 10); }); }); describe('startDrag({file, icon})', () => { it('throws errors for a missing file or a missing/empty icon', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.startDrag({ icon: path.join(fixturesPath, 'assets', 'logo.png') } as any); }).to.throw('Must specify either \'file\' or \'files\' option'); expect(() => { w.webContents.startDrag({ file: __filename } as any); }).to.throw('\'icon\' parameter is required'); expect(() => { w.webContents.startDrag({ file: __filename, icon: path.join(mainFixturesPath, 'blank.png') }); }).to.throw(/Failed to load image from path (.+)/); }); }); describe('focus()', () => { describe('when the web contents is hidden', () => { afterEach(closeAllWindows); it('does not blur the focused window', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.show(); await w.loadURL('about:blank'); w.focus(); const child = new BrowserWindow({ show: false }); child.loadURL('about:blank'); child.webContents.focus(); const currentFocused = w.isFocused(); const childFocused = child.isFocused(); child.close(); expect(currentFocused).to.be.true(); expect(childFocused).to.be.false(); }); }); }); describe('getOSProcessId()', () => { afterEach(closeAllWindows); it('returns a valid procress id', async () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getOSProcessId()).to.equal(0); await w.loadURL('about:blank'); expect(w.webContents.getOSProcessId()).to.be.above(0); }); }); describe('getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns a valid stream id', () => { const w = new BrowserWindow({ show: false }); expect(w.webContents.getMediaSourceId(w.webContents)).to.be.a('string').that.is.not.empty(); }); }); describe('userAgent APIs', () => { it('can set the user agent (functions)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.getUserAgent(); w.webContents.setUserAgent('my-user-agent'); expect(w.webContents.getUserAgent()).to.equal('my-user-agent'); w.webContents.setUserAgent(userAgent); expect(w.webContents.getUserAgent()).to.equal(userAgent); }); it('can set the user agent (properties)', () => { const w = new BrowserWindow({ show: false }); const userAgent = w.webContents.userAgent; w.webContents.userAgent = 'my-user-agent'; expect(w.webContents.userAgent).to.equal('my-user-agent'); w.webContents.userAgent = userAgent; expect(w.webContents.userAgent).to.equal(userAgent); }); }); describe('audioMuted APIs', () => { it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.setAudioMuted(true); expect(w.webContents.isAudioMuted()).to.be.true(); w.webContents.setAudioMuted(false); expect(w.webContents.isAudioMuted()).to.be.false(); }); it('can set the audio mute level (functions)', () => { const w = new BrowserWindow({ show: false }); w.webContents.audioMuted = true; expect(w.webContents.audioMuted).to.be.true(); w.webContents.audioMuted = false; expect(w.webContents.audioMuted).to.be.false(); }); }); describe('zoom api', () => { const hostZoomMap: Record<string, number> = { host1: 0.3, host2: 0.7, host3: 0.2 }; before(() => { const protocol = session.defaultSession.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { const response = `<script> const {ipcRenderer} = require('electron') ipcRenderer.send('set-zoom', window.location.hostname) ipcRenderer.on(window.location.hostname + '-zoom-set', () => { ipcRenderer.send(window.location.hostname + '-zoom-level') }) </script>`; callback({ data: response, mimeType: 'text/html' }); }); }); after(() => { const protocol = session.defaultSession.protocol; protocol.unregisterProtocol(standardScheme); }); afterEach(closeAllWindows); it('throws on an invalid zoomFactor', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); expect(() => { w.webContents.setZoomFactor(0.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); expect(() => { w.webContents.setZoomFactor(-2.0); }).to.throw(/'zoomFactor' must be a double greater than 0.0/); }); it('can set the correct zoom level (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.getZoomLevel(); expect(zoomLevel).to.eql(0.0); w.webContents.setZoomLevel(0.5); const newZoomLevel = w.webContents.getZoomLevel(); expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.setZoomLevel(0); } }); it('can set the correct zoom level (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.eql(0.0); w.webContents.zoomLevel = 0.5; const newZoomLevel = w.webContents.zoomLevel; expect(newZoomLevel).to.eql(0.5); } finally { w.webContents.zoomLevel = 0; } }); it('can set the correct zoom factor (functions)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.getZoomFactor(); expect(zoomFactor).to.eql(1.0); w.webContents.setZoomFactor(0.5); const newZoomFactor = w.webContents.getZoomFactor(); expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.setZoomFactor(1.0); } }); it('can set the correct zoom factor (properties)', async () => { const w = new BrowserWindow({ show: false }); try { await w.loadURL('about:blank'); const zoomFactor = w.webContents.zoomFactor; expect(zoomFactor).to.eql(1.0); w.webContents.zoomFactor = 0.5; const newZoomFactor = w.webContents.zoomFactor; expect(newZoomFactor).to.eql(0.5); } finally { w.webContents.zoomFactor = 1.0; } }); it('can persist zoom level across navigation', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let finalNavigation = false; ipcMain.on('set-zoom', (e, host) => { const zoomLevel = hostZoomMap[host]; if (!finalNavigation) w.webContents.zoomLevel = zoomLevel; e.sender.send(`${host}-zoom-set`); }); ipcMain.on('host1-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host1; expect(zoomLevel).to.equal(expectedZoomLevel); if (finalNavigation) { done(); } else { w.loadURL(`${standardScheme}://host2`); } } catch (e) { done(e); } }); ipcMain.once('host2-zoom-level', (e) => { try { const zoomLevel = e.sender.getZoomLevel(); const expectedZoomLevel = hostZoomMap.host2; expect(zoomLevel).to.equal(expectedZoomLevel); finalNavigation = true; w.webContents.goBack(); } catch (e) { done(e); } }); w.loadURL(`${standardScheme}://host1`); }); it('can propagate zoom level across same session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false }); defer(() => { w2.setClosable(true); w2.close(); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel1).to.equal(zoomLevel2); }); it('cannot propagate zoom level across different session', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); const w2 = new BrowserWindow({ show: false, webPreferences: { partition: 'temp' } }); const protocol = w2.webContents.session.protocol; protocol.registerStringProtocol(standardScheme, (request, callback) => { callback('hello'); }); defer(() => { w2.setClosable(true); w2.close(); protocol.unregisterProtocol(standardScheme); }); await w.loadURL(`${standardScheme}://host3`); w.webContents.zoomLevel = hostZoomMap.host3; await w2.loadURL(`${standardScheme}://host3`); const zoomLevel1 = w.webContents.zoomLevel; expect(zoomLevel1).to.equal(hostZoomMap.host3); const zoomLevel2 = w2.webContents.zoomLevel; expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); it('can persist when it contains iframe', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { setTimeout(() => { res.end(); }, 200); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { try { const zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(2.0); w.webContents.zoomLevel = 0; done(); } catch (e) { done(e); } finally { server.close(); } } }); w.webContents.on('dom-ready', () => { w.webContents.zoomLevel = 2.0; }); w.loadURL(`data:text/html,${content}`); }); }); it('cannot propagate when used with webframe', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const w2 = new BrowserWindow({ show: false }); const temporaryZoomSet = emittedOnce(ipcMain, 'temporary-zoom-set'); w.loadFile(path.join(fixturesPath, 'pages', 'webframe-zoom.html')); await temporaryZoomSet; const finalZoomLevel = w.webContents.getZoomLevel(); await w2.loadFile(path.join(fixturesPath, 'pages', 'c.html')); const zoomLevel1 = w.webContents.zoomLevel; const zoomLevel2 = w2.webContents.zoomLevel; w2.setClosable(true); w2.close(); expect(zoomLevel1).to.equal(finalZoomLevel); expect(zoomLevel2).to.equal(0); expect(zoomLevel1).to.not.equal(zoomLevel2); }); describe('with unique domains', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { setTimeout(() => res.end('hey'), 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('cannot persist zoom level after navigation with webFrame', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const source = ` const {ipcRenderer, webFrame} = require('electron') webFrame.setZoomLevel(0.6) ipcRenderer.send('zoom-level-set', webFrame.getZoomLevel()) `; const zoomLevelPromise = emittedOnce(ipcMain, 'zoom-level-set'); await w.loadURL(serverUrl); await w.webContents.executeJavaScript(source); let [, zoomLevel] = await zoomLevelPromise; expect(zoomLevel).to.equal(0.6); const loadPromise = emittedOnce(w.webContents, 'did-finish-load'); await w.loadURL(crossSiteUrl); await loadPromise; zoomLevel = w.webContents.zoomLevel; expect(zoomLevel).to.equal(0); }); }); }); describe('webrtc ip policy api', () => { afterEach(closeAllWindows); it('can set and get webrtc ip policies', () => { const w = new BrowserWindow({ show: false }); const policies = [ 'default', 'default_public_interface_only', 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ]; policies.forEach((policy) => { w.webContents.setWebRTCIPHandlingPolicy(policy as any); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); }); }); }); describe('render view deleted events', () => { let server: http.Server; let serverUrl: string; let crossSiteUrl: string; before((done) => { server = http.createServer((req, res) => { const respond = () => { if (req.url === '/redirect-cross-site') { res.setHeader('Location', `${crossSiteUrl}/redirected`); res.statusCode = 302; res.end(); } else if (req.url === '/redirected') { res.end('<html><script>window.localStorage</script></html>'); } else if (req.url === '/first-window-open') { res.end(`<html><script>window.open('${serverUrl}/second-window-open', 'first child');</script></html>`); } else if (req.url === '/second-window-open') { res.end('<html><script>window.open(\'wrong://url\', \'second child\');</script></html>'); } else { res.end(); } }; setTimeout(respond, 0); }); server.listen(0, '127.0.0.1', () => { serverUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; crossSiteUrl = `http://localhost:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); afterEach(closeAllWindows); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; w.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); w.webContents.on('did-finish-load', () => { w.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('current-render-view-deleted was emitted'); }); it('does not emit current-render-view-deleted when speculative RVHs are deleted', async () => { const parentWindow = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; let childWindow: BrowserWindow | null = null; const destroyed = emittedOnce(parentWindow.webContents, 'destroyed'); const renderViewDeletedHandler = () => { currentRenderViewDeletedEmitted = true; }; const childWindowCreated = new Promise<void>((resolve) => { app.once('browser-window-created', (event, window) => { childWindow = window; window.webContents.on('current-render-view-deleted' as any, renderViewDeletedHandler); resolve(); }); }); parentWindow.loadURL(`${serverUrl}/first-window-open`); await childWindowCreated; childWindow!.webContents.removeListener('current-render-view-deleted' as any, renderViewDeletedHandler); parentWindow.close(); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.false('child window was destroyed'); }); it('emits current-render-view-deleted if the current RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let currentRenderViewDeletedEmitted = false; w.webContents.on('current-render-view-deleted' as any, () => { currentRenderViewDeletedEmitted = true; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; expect(currentRenderViewDeletedEmitted).to.be.true('current-render-view-deleted wasn\'t emitted'); }); it('emits render-view-deleted if any RVHs are deleted', async () => { const w = new BrowserWindow({ show: false }); let rvhDeletedCount = 0; w.webContents.on('render-view-deleted' as any, () => { rvhDeletedCount++; }); w.webContents.on('did-finish-load', () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.loadURL(`${serverUrl}/redirect-cross-site`); await destroyed; const expectedRenderViewDeletedEventCount = 1; expect(rvhDeletedCount).to.equal(expectedRenderViewDeletedEventCount, 'render-view-deleted wasn\'t emitted the expected nr. of times'); }); }); describe('setIgnoreMenuShortcuts(ignore)', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.setIgnoreMenuShortcuts(true); w.webContents.setIgnoreMenuShortcuts(false); }).to.not.throw(); }); }); const crashPrefs = [ { nodeIntegration: true }, { sandbox: true } ]; const nicePrefs = (o: any) => { let s = ''; for (const key of Object.keys(o)) { s += `${key}=${o[key]}, `; } return `(${s.slice(0, s.length - 2)})`; }; for (const prefs of crashPrefs) { describe(`crash with webPreferences ${nicePrefs(prefs)}`, () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); await w.loadURL('about:blank'); }); afterEach(closeAllWindows); it('isCrashed() is false by default', () => { expect(w.webContents.isCrashed()).to.equal(false); }); it('forcefullyCrashRenderer() crashes the process with reason=killed||crashed', async () => { expect(w.webContents.isCrashed()).to.equal(false); const crashEvent = emittedOnce(w.webContents, 'render-process-gone'); w.webContents.forcefullyCrashRenderer(); const [, details] = await crashEvent; expect(details.reason === 'killed' || details.reason === 'crashed').to.equal(true, 'reason should be killed || crashed'); expect(w.webContents.isCrashed()).to.equal(true); }); it('a crashed process is recoverable with reload()', async () => { expect(w.webContents.isCrashed()).to.equal(false); w.webContents.forcefullyCrashRenderer(); w.webContents.reload(); expect(w.webContents.isCrashed()).to.equal(false); }); }); } // Destroying webContents in its event listener is going to crash when // Electron is built in Debug mode. describe('destroy()', () => { let server: http.Server; let serverUrl: string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/200': response.end(); break; default: done('unsupported endpoint'); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', url: '/200' }, { name: 'dom-ready', url: '/200' }, { name: 'did-stop-loading', url: '/200' }, { name: 'did-finish-load', url: '/200' }, // FIXME: Multiple Emit calls inside an observer assume that object // will be alive till end of the observer. Synchronous `destroy` api // violates this contract and crashes. { name: 'did-frame-finish-load', url: '/200' }, { name: 'did-fail-load', url: '/net-error' } ]; for (const e of events) { it(`should not crash when invoked synchronously inside ${e.name} handler`, async function () { // This test is flaky on Windows CI and we don't know why, but the // purpose of this test is to make sure Electron does not crash so it // is fine to retry this test for a few times. this.retries(3); const contents = (webContents as any).create() as WebContents; const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => (contents as any).destroy()); const destroyed = emittedOnce(contents, 'destroyed'); contents.loadURL(serverUrl + e.url); await destroyed; }); } }); describe('did-change-theme-color event', () => { afterEach(closeAllWindows); it('is triggered with correct theme color', (done) => { const w = new BrowserWindow({ show: true }); let count = 0; w.webContents.on('did-change-theme-color', (e, color) => { try { if (count === 0) { count += 1; expect(color).to.equal('#FFEEDD'); w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); } else if (count === 1) { expect(color).to.be.null(); done(); } } catch (e) { done(e); } }); w.loadFile(path.join(fixturesPath, 'pages', 'theme-color.html')); }); }); describe('console-message event', () => { afterEach(closeAllWindows); it('is triggered with correct log message', (done) => { const w = new BrowserWindow({ show: true }); w.webContents.on('console-message', (e, level, message) => { // Don't just assert as Chromium might emit other logs that we should ignore. if (message === 'a') { done(); } }); w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); }); }); describe('ipc-message event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends an asynchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); w.webContents.executeJavaScript(` require('electron').ipcRenderer.send('message', 'Hello World!') `); const [, channel, message] = await emittedOnce(w.webContents, 'ipc-message'); expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); }); }); describe('ipc-message-sync event', () => { afterEach(closeAllWindows); it('emits when the renderer process sends a synchronous message', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true, contextIsolation: false } }); await w.webContents.loadURL('about:blank'); const promise: Promise<[string, string]> = new Promise(resolve => { w.webContents.once('ipc-message-sync', (event, channel, arg) => { event.returnValue = 'foobar' as any; resolve([channel, arg]); }); }); const result = await w.webContents.executeJavaScript(` require('electron').ipcRenderer.sendSync('message', 'Hello World!') `); const [channel, message] = await promise; expect(channel).to.equal('message'); expect(message).to.equal('Hello World!'); expect(result).to.equal('foobar'); }); }); describe('referrer', () => { afterEach(closeAllWindows); it('propagates referrer information to new target=_blank windows', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } finally { server.close(); } } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.once('new-window', (event, newUrl, frameName, disposition, options, features, referrer) => { expect(referrer.url).to.equal(url); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); }); w.webContents.executeJavaScript('a.click()'); }); w.loadURL(url); }); }); // TODO(jeremy): window.open() in a real browser passes the referrer, but // our hacked-up window.open() shim doesn't. It should. xit('propagates referrer information to windows opened with window.open', (done) => { const w = new BrowserWindow({ show: false }); const server = http.createServer((req, res) => { if (req.url === '/should_have_referrer') { try { expect(req.headers.referer).to.equal(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`); return done(); } catch (e) { return done(e); } } res.end(''); }); server.listen(0, '127.0.0.1', () => { const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; w.webContents.once('did-finish-load', () => { w.webContents.once('new-window', (event, newUrl, frameName, disposition, options, features, referrer) => { expect(referrer.url).to.equal(url); expect(referrer.policy).to.equal('no-referrer-when-downgrade'); }); w.webContents.executeJavaScript('window.open(location.href + "should_have_referrer")'); }); w.loadURL(url); }); }); }); describe('webframe messages in sandboxed contents', () => { afterEach(closeAllWindows); it('responds to executeJavaScript', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const result = await w.webContents.executeJavaScript('37 + 5'); expect(result).to.equal(42); }); }); describe('preload-error event', () => { afterEach(closeAllWindows); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('is triggered when unhandled exception is thrown', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-exception.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('Hello World!'); }); it('is triggered on syntax errors', async () => { const preload = path.join(fixturesPath, 'module', 'preload-error-syntax.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.equal('foobar is not defined'); }); it('is triggered when preload script loading fails', async () => { const preload = path.join(fixturesPath, 'module', 'preload-invalid.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload } }); const promise = emittedOnce(w.webContents, 'preload-error'); w.loadURL('about:blank'); const [, preloadPath, error] = await promise; expect(preloadPath).to.equal(preload); expect(error.message).to.contain('preload-invalid.js'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('takeHeapSnapshot()', () => { afterEach(closeAllWindows); it('works with sandboxed renderers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const filePath = path.join(app.getPath('temp'), 'test.heapsnapshot'); const cleanup = () => { try { fs.unlinkSync(filePath); } catch (e) { // ignore error } }; try { await w.webContents.takeHeapSnapshot(filePath); const stats = fs.statSync(filePath); expect(stats.size).not.to.be.equal(0); } finally { cleanup(); } }); it('fails with invalid file path', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const promise = w.webContents.takeHeapSnapshot(''); return expect(promise).to.be.eventually.rejectedWith(Error, 'takeHeapSnapshot failed'); }); }); describe('setBackgroundThrottling()', () => { afterEach(closeAllWindows); it('does not crash when allowing', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(true); }); it('does not crash when called via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(true); }); it('does not crash when disallowing', () => { const w = new BrowserWindow({ show: false, webPreferences: { backgroundThrottling: true } }); w.webContents.setBackgroundThrottling(false); }); }); describe('getBackgroundThrottling()', () => { afterEach(closeAllWindows); it('works via getter', () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); expect(w.webContents.getBackgroundThrottling()).to.equal(false); w.webContents.setBackgroundThrottling(true); expect(w.webContents.getBackgroundThrottling()).to.equal(true); }); it('works via property', () => { const w = new BrowserWindow({ show: false }); w.webContents.backgroundThrottling = false; expect(w.webContents.backgroundThrottling).to.equal(false); w.webContents.backgroundThrottling = true; expect(w.webContents.backgroundThrottling).to.equal(true); }); it('works via BrowserWindow', () => { const w = new BrowserWindow({ show: false }); (w as any).setBackgroundThrottling(false); expect((w as any).getBackgroundThrottling()).to.equal(false); (w as any).setBackgroundThrottling(true); expect((w as any).getBackgroundThrottling()).to.equal(true); }); }); ifdescribe(features.isPrintingEnabled())('getPrinters()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = w.webContents.getPrinters(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('getPrintersAsync()', () => { afterEach(closeAllWindows); it('can get printer list', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('about:blank'); const printers = await w.webContents.getPrintersAsync(); expect(printers).to.be.an('array'); }); }); ifdescribe(features.isPrintingEnabled())('printToPDF()', () => { let w: BrowserWindow; beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadURL('data:text/html,<h1>Hello, World!</h1>'); }); afterEach(closeAllWindows); it('rejects on incorrectly typed parameters', async () => { const badTypes = { marginsType: 'terrible', scaleFactor: 'not-a-number', landscape: [], pageRanges: { oops: 'im-not-the-right-key' }, headerFooter: '123', printSelectionOnly: 1, printBackground: 2, pageSize: 'IAmAPageSize' }; // These will hard crash in Chromium unless we type-check for (const [key, value] of Object.entries(badTypes)) { const param = { [key]: value }; await expect(w.webContents.printToPDF(param)).to.eventually.be.rejected(); } }); it('can print to PDF', async () => { const data = await w.webContents.printToPDF({}); expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); }); it('does not crash when called multiple times in parallel', async () => { const promises = []; for (let i = 0; i < 3; i++) { promises.push(w.webContents.printToPDF({})); } const results = await Promise.all(promises); for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); it('does not crash when called multiple times in sequence', async () => { const results = []; for (let i = 0; i < 3; i++) { const result = await w.webContents.printToPDF({}); results.push(result); } for (const data of results) { expect(data).to.be.an.instanceof(Buffer).that.is.not.empty(); } }); // TODO(codebytere): Re-enable after Chromium fixes upstream v8_scriptormodule_legacy_lifetime crash. xdescribe('using a large document', () => { beforeEach(async () => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'print-to-pdf.html')); }); afterEach(closeAllWindows); it('respects custom settings', async () => { const data = await w.webContents.printToPDF({ pageRanges: { from: 0, to: 2 }, landscape: true }); const doc = await pdfjs.getDocument(data).promise; // Check that correct # of pages are rendered. expect(doc.numPages).to.equal(3); // Check that PDF is generated in landscape mode. const firstPage = await doc.getPage(1); const { width, height } = firstPage.getViewport({ scale: 100 }); expect(width).to.be.greaterThan(height); }); }); }); describe('PictureInPicture video', () => { afterEach(closeAllWindows); it('works as expected', async function () { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); await w.loadFile(path.join(fixturesPath, 'api', 'picture-in-picture.html')); if (!await w.webContents.executeJavaScript('document.createElement(\'video\').canPlayType(\'video/webm; codecs="vp8.0"\')')) { this.skip(); } const result = await w.webContents.executeJavaScript( `runTest(${features.isPictureInPictureEnabled()})`, true); expect(result).to.be.true(); }); }); describe('devtools window', () => { let hasRobotJS = false; try { // We have other tests that check if native modules work, if we fail to require // robotjs let's skip this test to avoid false negatives require('robotjs'); hasRobotJS = true; } catch (err) { /* no-op */ } afterEach(closeAllWindows); // NB. on macOS, this requires that you grant your terminal the ability to // control your computer. Open System Preferences > Security & Privacy > // Privacy > Accessibility and grant your terminal the permission to control // your computer. ifit(hasRobotJS)('can receive and handle menu events', async () => { const w = new BrowserWindow({ show: true, webPreferences: { nodeIntegration: true } }); w.loadFile(path.join(fixturesPath, 'pages', 'key-events.html')); // Ensure the devtools are loaded w.webContents.closeDevTools(); const opened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.openDevTools(); await opened; await emittedOnce(w.webContents.devToolsWebContents!, 'did-finish-load'); w.webContents.devToolsWebContents!.focus(); // Focus an input field await w.webContents.devToolsWebContents!.executeJavaScript(` const input = document.createElement('input') document.body.innerHTML = '' document.body.appendChild(input) input.focus() `); // Write something to the clipboard clipboard.writeText('test value'); const pasted = w.webContents.devToolsWebContents!.executeJavaScript(`new Promise(resolve => { document.querySelector('input').addEventListener('paste', (e) => { resolve(e.target.value) }) })`); // Fake a paste request using robotjs to emulate a REAL keyboard paste event require('robotjs').keyTap('v', process.platform === 'darwin' ? ['command'] : ['control']); const val = await pasted; // Once we're done expect the paste to have been successful expect(val).to.equal('test value', 'value should eventually become the pasted value'); }); }); describe('Shared Workers', () => { afterEach(closeAllWindows); it('can get multiple shared workers', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); expect(sharedWorkers).to.have.lengthOf(2); expect(sharedWorkers[0].url).to.contain('shared-worker'); expect(sharedWorkers[1].url).to.contain('shared-worker'); }); it('can inspect a specific shared worker', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); const ready = emittedOnce(ipcMain, 'ready'); w.loadFile(path.join(fixturesPath, 'api', 'shared-worker', 'shared-worker.html')); await ready; const sharedWorkers = w.webContents.getAllSharedWorkers(); const devtoolsOpened = emittedOnce(w.webContents, 'devtools-opened'); w.webContents.inspectSharedWorkerById(sharedWorkers[0].id); await devtoolsOpened; const devtoolsClosed = emittedOnce(w.webContents, 'devtools-closed'); w.webContents.closeDevTools(); await devtoolsClosed; }); }); describe('login event', () => { afterEach(closeAllWindows); let server: http.Server; let serverUrl: string; let serverPort: number; let proxyServer: http.Server; let proxyServerPort: number; before((done) => { server = http.createServer((request, response) => { if (request.url === '/no-auth') { return response.end('ok'); } if (request.headers.authorization) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers.authorization); } response .writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }) .end('401'); }).listen(0, '127.0.0.1', () => { serverPort = (server.address() as AddressInfo).port; serverUrl = `http://127.0.0.1:${serverPort}`; done(); }); }); before((done) => { proxyServer = http.createServer((request, response) => { if (request.headers['proxy-authorization']) { response.writeHead(200, { 'Content-type': 'text/plain' }); return response.end(request.headers['proxy-authorization']); } response .writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }) .end(); }).listen(0, '127.0.0.1', () => { proxyServerPort = (proxyServer.address() as AddressInfo).port; done(); }); }); afterEach(async () => { await session.defaultSession.clearAuthCache(); }); after(() => { server.close(); proxyServer.close(); }); it('is emitted when navigating', async () => { const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(serverUrl + '/'); expect(eventAuthInfo.isProxy).to.be.false(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(serverPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('is emitted when a proxy requests authorization', async () => { const customSession = session.fromPartition(`${Math.random()}`); await customSession.setProxy({ proxyRules: `127.0.0.1:${proxyServerPort}`, proxyBypassRules: '<-loopback>' }); const [user, pass] = ['user', 'pass']; const w = new BrowserWindow({ show: false, webPreferences: { session: customSession } }); let eventRequest: any; let eventAuthInfo: any; w.webContents.on('login', (event, request, authInfo, cb) => { eventRequest = request; eventAuthInfo = authInfo; event.preventDefault(); cb(user, pass); }); await w.loadURL(`${serverUrl}/no-auth`); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal(`Basic ${Buffer.from(`${user}:${pass}`).toString('base64')}`); expect(eventRequest.url).to.equal(`${serverUrl}/no-auth`); expect(eventAuthInfo.isProxy).to.be.true(); expect(eventAuthInfo.scheme).to.equal('basic'); expect(eventAuthInfo.host).to.equal('127.0.0.1'); expect(eventAuthInfo.port).to.equal(proxyServerPort); expect(eventAuthInfo.realm).to.equal('Foo'); }); it('cancels authentication when callback is called with no arguments', async () => { const w = new BrowserWindow({ show: false }); w.webContents.on('login', (event, request, authInfo, cb) => { event.preventDefault(); cb(); }); await w.loadURL(serverUrl); const body = await w.webContents.executeJavaScript('document.documentElement.textContent'); expect(body).to.equal('401'); }); }); describe('page-title-updated event', () => { afterEach(closeAllWindows); it('is emitted with a full title for pages with no navigation', async () => { const bw = new BrowserWindow({ show: false }); await bw.loadURL('about:blank'); bw.webContents.executeJavaScript('child = window.open("", "", "show=no"); null'); const [, child] = await emittedOnce(app, 'web-contents-created'); bw.webContents.executeJavaScript('child.document.title = "new title"'); const [, title] = await emittedOnce(child, 'page-title-updated'); expect(title).to.equal('new title'); }); }); describe('crashed event', () => { it('does not crash main process when destroying WebContents in it', (done) => { const contents = (webContents as any).create({ nodeIntegration: true }); contents.once('crashed', () => { contents.destroy(); done(); }); contents.loadURL('about:blank').then(() => contents.forcefullyCrashRenderer()); }); }); describe('context-menu event', () => { afterEach(closeAllWindows); it('emits when right-clicked in page', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html')); const promise = emittedOnce(w.webContents, 'context-menu'); // Simulate right-click to create context-menu event. const opts = { x: 0, y: 0, button: 'right' as any }; w.webContents.sendInputEvent({ ...opts, type: 'mouseDown' }); w.webContents.sendInputEvent({ ...opts, type: 'mouseUp' }); const [, params] = await promise; expect(params.pageURL).to.equal(w.webContents.getURL()); expect(params.frame).to.be.an('object'); expect(params.x).to.be.a('number'); expect(params.y).to.be.a('number'); }); }); it('emits a cancelable event before creating a child webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); w.webContents.on('-will-add-new-contents' as any, (event: any, url: any) => { expect(url).to.equal('about:blank'); event.preventDefault(); }); let wasCalled = false; w.webContents.on('new-window' as any, () => { wasCalled = true; }); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('window.open(\'about:blank\')'); await new Promise((resolve) => { process.nextTick(resolve); }); expect(wasCalled).to.equal(false); await closeAllWindows(); }); });
closed
electron/electron
https://github.com/electron/electron
32,684
[Bug]: Cancelling print causes electron to crash
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.9 ### What operating system are you using? Windows ### Operating System Version Windows 10 19042.985 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No crash should happen, print gets cancelled ### Actual Behavior Calling window.print() and then clicking on the cancel button crashes electron ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32684
https://github.com/electron/electron/pull/32632
b346f909e74dc3a82df2ba269029dc3dbd365add
56c6d25e98d6c0caef124dc81113f264efccc8ef
2022-01-31T16:43:16Z
c++
2022-02-01T19:00:09Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 0de0532d64897c91ce0f72d165976e12e1dec03e..13167ca3f9c0d4895fecd40ab1e2d397c6e85a0b 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -88,6 +88,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -96,6 +97,7 @@ PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { web_contents ? web_contents->GetBrowserContext() : nullptr; return context ? Profile::FromBrowserContext(context)->GetPrefs() : nullptr; } +#endif #endif // defined(OS_WIN) @@ -355,8 +357,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -446,8 +450,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } @@ -504,6 +510,20 @@ void PrintJob::OnPageDone(PrintedPage* page) { } #endif // defined(OS_WIN) +void PrintJob::OnUserInitCancelled() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + // Make sure a `Cancel()` is broadcast. + auto details = base::MakeRefCounted<JobEventDetails>(JobEventDetails::USER_INIT_CANCELED, + 0, nullptr); + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<PrintJob>(this), + content::Details<JobEventDetails>(details.get())); + + for (auto& observer : observers_) { + observer.OnUserInitCancelled(); + } +} + void PrintJob::OnFailed() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); diff --git a/chrome/browser/printing/print_job.h b/chrome/browser/printing/print_job.h index e19f62354edb8acad722c6680296b7d2f55f51fe..b5539171655d78634ee89faf3516d23ce5718353 100644 --- a/chrome/browser/printing/print_job.h +++ b/chrome/browser/printing/print_job.h @@ -53,6 +53,7 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob> { public: virtual void OnDocDone(int job_id, PrintedDocument* document) {} virtual void OnJobDone() {} + virtual void OnUserInitCancelled() {} virtual void OnFailed() {} }; @@ -100,6 +101,9 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob> { // Called when the document is done printing. virtual void OnDocDone(int job_id, PrintedDocument* document); + // Called if the user cancels the print job. + virtual void OnUserInitCancelled(); + // Called if the document fails to print. virtual void OnFailed(); @@ -257,6 +261,9 @@ class JobEventDetails : public base::RefCountedThreadSafe<JobEventDetails> { public: // Event type. enum Type { + // Print... dialog box has been closed with CANCEL button. + USER_INIT_CANCELED, + // A new document started printing. NEW_DOC, diff --git a/chrome/browser/printing/print_job_worker.cc b/chrome/browser/printing/print_job_worker.cc index d8f67ab5116483eb2eeb4cc09f19bbcbccb74b37..b4ab0984765c9711ddacf32f7147108cdfbc5096 100644 --- a/chrome/browser/printing/print_job_worker.cc +++ b/chrome/browser/printing/print_job_worker.cc @@ -20,13 +20,13 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job.h" -#include "chrome/grit/generated_resources.h" #include "components/crash/core/common/crash_keys.h" #include "components/device_event_log/device_event_log.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" +#include "electron/grit/electron_resources.h" #include "printing/backend/print_backend.h" #include "printing/buildflags/buildflags.h" #include "printing/mojom/print.mojom.h" @@ -125,6 +125,10 @@ void FailedNotificationCallback(PrintJob* print_job) { print_job->OnFailed(); } +void UserInitCancelledNotificationCallback(PrintJob* print_job) { + print_job->OnUserInitCancelled(); +} + #if defined(OS_WIN) void PageNotificationCallback(PrintJob* print_job, PrintedPage* page) { print_job->OnPageDone(page); @@ -245,16 +249,21 @@ void PrintJobWorker::UpdatePrintSettings(base::Value new_settings, #endif // defined(OS_LINUX) && defined(USE_CUPS) } - mojom::ResultCode result; { #if defined(OS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode get_default_result = printing_context_->UseDefaultSettings(); + if (get_default_result == mojom::ResultCode::kSuccess) { + mojom::ResultCode update_result = + printing_context_->UpdatePrintSettings(std::move(new_settings)); + GetSettingsDone(std::move(callback), update_result); + } } - GetSettingsDone(std::move(callback), result); } #if defined(OS_CHROMEOS) @@ -270,6 +279,12 @@ void PrintJobWorker::UpdatePrintSettingsFromPOD( void PrintJobWorker::GetSettingsDone(SettingsCallback callback, mojom::ResultCode result) { + if (result == mojom::ResultCode::kCanceled) { + print_job_->PostTask( + FROM_HERE, + base::BindOnce(&UserInitCancelledNotificationCallback, + base::RetainedRef(print_job_.get()))); + } std::move(callback).Run(printing_context_->TakeAndResetSettings(), result); } diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index c9f1502da55d89de0eede73a7d39047c090594d0..1320afa83016ea72e5dbc23b1ed63cf91d439102 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -29,10 +29,10 @@ #include "chrome/browser/printing/print_view_manager_common.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/simple_message_box.h" -#include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "chrome/common/pref_names.h" +#if 0 #include "chrome/grit/generated_resources.h" +#endif #include "components/prefs/pref_service.h" #include "components/printing/browser/print_composite_client.h" #include "components/printing/browser/print_manager_utils.h" @@ -47,6 +47,7 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" +#include "electron/grit/electron_resources.h" #include "mojo/public/cpp/system/buffer.h" #include "printing/buildflags/buildflags.h" #include "printing/metafile_skia.h" @@ -110,6 +111,8 @@ crosapi::mojom::PrintJobPtr PrintJobToMojom(int job_id, #endif void ShowWarningMessageBox(const std::u16string& message) { + LOG(ERROR) << "Invalid printer settings " << message; +#if 0 // Runs always on the UI thread. static bool is_dialog_shown = false; if (is_dialog_shown) @@ -118,6 +121,7 @@ void ShowWarningMessageBox(const std::u16string& message) { base::AutoReset<bool> auto_reset(&is_dialog_shown, true); chrome::ShowWarningMessageBox(nullptr, std::u16string(), message); +#endif } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -217,7 +221,9 @@ void UpdatePrintSettingsReplyOnIO( DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(printer_query); mojom::PrintPagesParamsPtr params = CreateEmptyPrintPagesParamsPtr(); - if (printer_query->last_status() == mojom::ResultCode::kSuccess) { + // We call update without first printing from defaults, + // so the last printer status will still be defaulted to PrintingContext::FAILED + if (printer_query) { RenderParamsFromPrintSettings(printer_query->settings(), params->params.get()); params->params->document_cookie = printer_query->cookie(); @@ -319,12 +325,14 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); printing_enabled_.Init( prefs::kPrintingEnabled, profile->GetPrefs(), base::BindRepeating(&PrintViewManagerBase::UpdatePrintingEnabled, weak_ptr_factory_.GetWeakPtr())); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -332,7 +340,10 @@ PrintViewManagerBase::~PrintViewManagerBase() { DisconnectFromCurrentPrintJob(); } -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value settings, + CompletionCallback callback) { auto weak_this = weak_ptr_factory_.GetWeakPtr(); DisconnectFromCurrentPrintJob(); if (!weak_this) @@ -347,7 +358,13 @@ bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { // go in `ReleasePrintJob()`. SetPrintingRFH(rfh); - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + callback_ = std::move(callback); + + if (!callback_.is_null()) { + print_job_->AddObserver(*this); + } + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); for (auto& observer : GetObservers()) observer.OnPrintNow(rfh); @@ -506,9 +523,9 @@ void PrintViewManagerBase::ScriptedPrintReply( void PrintViewManagerBase::UpdatePrintingEnabled() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // The Unretained() is safe because ForEachFrame() is synchronous. - web_contents()->ForEachFrame(base::BindRepeating( - &PrintViewManagerBase::SendPrintingEnabled, base::Unretained(this), - printing_enabled_.GetValue())); + web_contents()->ForEachFrame( + base::BindRepeating(&PrintViewManagerBase::SendPrintingEnabled, + base::Unretained(this), true)); } void PrintViewManagerBase::NavigationStopped() { @@ -622,12 +639,13 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), mojom::PrintParams::New()); return; } - +#endif content::RenderFrameHost* render_frame_host = GetCurrentTargetFrame(); auto callback_wrapper = base::BindOnce(&PrintViewManagerBase::GetDefaultPrintSettingsReply, @@ -645,18 +663,20 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } - +#endif if (!job_settings.FindIntKey(kSettingPrinterType)) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } +#if 0 content::BrowserContext* context = web_contents() ? web_contents()->GetBrowserContext() : nullptr; PrefService* prefs = @@ -666,6 +686,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.SetIntKey(kSettingRasterizePdfDpi, value); } +#endif auto callback_wrapper = base::BindOnce(&PrintViewManagerBase::UpdatePrintSettingsReply, @@ -714,7 +735,6 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie) { PrintManager::PrintingFailed(cookie); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) - ShowPrintErrorDialog(); #endif ReleasePrinterQuery(); @@ -729,6 +749,11 @@ void PrintViewManagerBase::RemoveObserver(Observer& observer) { } void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + std::string cb_str = "Invalid printer settings"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ShowWarningMessageBox, l10n_util::GetStringUTF16( @@ -739,8 +764,10 @@ void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 // Printing is always enabled. if (new_state == content::RenderFrameHost::LifecycleState::kActive) SendPrintingEnabled(printing_enabled_.GetValue(), render_frame_host); +#endif } void PrintViewManagerBase::DidStartLoading() { @@ -808,6 +835,11 @@ void PrintViewManagerBase::OnJobDone() { ReleasePrintJob(); } +void PrintViewManagerBase::OnUserInitCancelled() { + printing_cancelled_ = true; + ReleasePrintJob(); +} + void PrintViewManagerBase::OnFailed() { TerminatePrintJob(true); } @@ -869,7 +901,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current |print_job_|. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -891,8 +926,6 @@ bool PrintViewManagerBase::CreateNewPrintJob( : PrintJob::Source::PRINT_PREVIEW, /*source_id=*/""); #endif - print_job_->AddObserver(*this); - printing_succeeded_ = false; return true; } @@ -944,14 +977,21 @@ void PrintViewManagerBase::ReleasePrintJob() { content::RenderFrameHost* rfh = printing_rfh_; printing_rfh_ = nullptr; + if (!callback_.is_null()) { + print_job_->RemoveObserver(*this); + + std::string cb_str = ""; + if (!printing_succeeded_) + cb_str = printing_cancelled_ ? "cancelled" : "failed"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + if (!print_job_) return; if (rfh) GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_); - print_job_->RemoveObserver(*this); - // Don't close the worker thread. print_job_ = nullptr; } @@ -989,7 +1029,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 5771a3ebd76145c6cf8a2ccc33abc886802ed59f..1562d6331a9cafd530db42c436e878bac427566d 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -37,6 +37,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -58,7 +60,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value settings, + CompletionCallback callback); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Prints the document in |print_data| with settings specified in @@ -143,6 +148,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // PrintJob::Observer overrides: void OnDocDone(int job_id, PrintedDocument* document) override; void OnJobDone() override; + void OnUserInitCancelled() override; void OnFailed() override; base::ObserverList<Observer>& GetObservers() { return observers_; } @@ -252,9 +258,15 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. bool printing_succeeded_ = false; + // Indication of whether the print job was manually cancelled + bool printing_cancelled_ = false; + // Set while running an inner message loop inside RenderAllMissingPagesNow(). // This means we are _blocking_ until all the necessary pages have been // rendered or the print settings are being loaded. diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index 51ebcb4ae399018d3fd8566656596a7ef1f148af..5f2b807fc364131f4c3e6a1646ec522ddc826d9c 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -274,7 +274,7 @@ interface PrintPreviewUI { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings); // Tells the RenderFrame to switch the CSS to print media type, render every // requested page using the print preview document's frame/node, and then diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 650b5550f982fa5c5c522efaa9b8e305b7edc5e7..260b5521dccadf07eba2c67fa3d9c3da80b49104 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -39,6 +39,7 @@ #include "printing/metafile_skia.h" #include "printing/mojom/print.mojom.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" @@ -1226,7 +1227,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::DictionaryValue() /* new_settings */); if (!weak_this) return; @@ -1257,7 +1259,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1272,7 +1274,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1303,7 +1305,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::DictionaryValue()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1350,6 +1353,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); if (print_preview_context_.IsForArc()) { @@ -1886,7 +1891,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::DictionaryValue() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -1901,7 +1907,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -1909,7 +1917,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, base::Value::AsDictionaryValue(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -1928,8 +1936,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2177,36 +2192,51 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { - mojom::PrintPagesParams settings; - settings.params = mojom::PrintParams::New(); - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + const base::DictionaryValue& new_settings) { + mojom::PrintPagesParamsPtr settings; + + if (new_settings.DictEmpty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + bool canceled = false; + int cookie = + print_pages_params_ ? print_pages_params_->params->document_cookie : 0; + GetPrintManagerHost()->UpdatePrintSettings(cookie, new_settings.Clone(), &settings, &canceled); + if (canceled) + return false; + } // Check if the printer returned any settings, if the settings is empty, we // can safely assume there are no printer drivers configured. So we safely // terminate. bool result = true; - if (!PrintMsg_Print_Params_IsValid(*settings.params)) + if (!PrintMsg_Print_Params_IsValid(*settings->params)) result = false; // Reset to default values. ignore_css_margins_ = false; - settings.pages.clear(); + settings->pages.clear(); - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return result; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + const base::DictionaryValue& settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingNodeOrPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, settings)) { notify_browser_of_print_failure_ = false; GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; @@ -2579,18 +2609,7 @@ void PrintRenderFrameHelper::RequestPrintPreview(PrintPreviewRequestType type) { } bool PrintRenderFrameHelper::CheckForCancel() { - const mojom::PrintParams& print_params = *print_pages_params_->params; - bool cancel = false; - - if (!GetPrintManagerHost()->CheckForCancel(print_params.preview_ui_id, - print_params.preview_request_id, - &cancel)) { - cancel = true; - } - - if (cancel) - notify_browser_of_print_failure_ = false; - return cancel; + return false; } bool PrintRenderFrameHelper::PreviewPageRendered( diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 90236920457c931c86426049c6cbc30b592b597f..353178863eba37b9112e784ffa4b3519076e91b9 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -256,7 +256,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value settings) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintForSystemDialog() override; void SetPrintPreviewUI( @@ -323,7 +323,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -332,12 +334,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + const base::DictionaryValue& settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + const base::DictionaryValue& settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/printing/printing_context.cc b/printing/printing_context.cc index f8f0f4bdfbb8db883f883f62f9d6e4b987d7b113..c2505f5e0049dc7ee8783056538ca4c2d0968744 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -120,7 +120,6 @@ mojom::ResultCode PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 7d937e7e3f19df351d410185fc4dc3b7c8937f2e..e87170e6957733f06bcc296bcca3fc331557ed46 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -175,6 +175,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { std::unique_ptr<PrintSettings> TakeAndResetSettings(); + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -185,9 +188,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING)
closed
electron/electron
https://github.com/electron/electron
32,684
[Bug]: Cancelling print causes electron to crash
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.9 ### What operating system are you using? Windows ### Operating System Version Windows 10 19042.985 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior No crash should happen, print gets cancelled ### Actual Behavior Calling window.print() and then clicking on the cancel button crashes electron ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32684
https://github.com/electron/electron/pull/32632
b346f909e74dc3a82df2ba269029dc3dbd365add
56c6d25e98d6c0caef124dc81113f264efccc8ef
2022-01-31T16:43:16Z
c++
2022-02-01T19:00:09Z
patches/chromium/printing.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Fri, 7 Jun 2019 13:59:37 -0700 Subject: printing.patch Add changeset that was previously applied to sources in chromium_src. The majority of changes originally come from these PRs: * https://github.com/electron/electron/pull/1835 * https://github.com/electron/electron/pull/8596 This patch also fixes callback for manual user cancellation and success. diff --git a/chrome/browser/printing/print_job.cc b/chrome/browser/printing/print_job.cc index 0de0532d64897c91ce0f72d165976e12e1dec03e..13167ca3f9c0d4895fecd40ab1e2d397c6e85a0b 100644 --- a/chrome/browser/printing/print_job.cc +++ b/chrome/browser/printing/print_job.cc @@ -88,6 +88,7 @@ bool PrintWithReducedRasterization(PrefService* prefs) { return base::FeatureList::IsEnabled(features::kPrintWithReducedRasterization); } +#if 0 PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { // TODO(thestig): Figure out why crbug.com/1083911 occurred, which is likely // because `web_contents` was null. As a result, this section has many more @@ -96,6 +97,7 @@ PrefService* GetPrefsForWebContents(content::WebContents* web_contents) { web_contents ? web_contents->GetBrowserContext() : nullptr; return context ? Profile::FromBrowserContext(context)->GetPrefs() : nullptr; } +#endif #endif // defined(OS_WIN) @@ -355,8 +357,10 @@ void PrintJob::StartPdfToEmfConversion( const PrintSettings& settings = document()->settings(); +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - bool print_with_reduced_rasterization = PrintWithReducedRasterization(prefs); +#endif + bool print_with_reduced_rasterization = PrintWithReducedRasterization(nullptr); using RenderMode = PdfRenderSettings::Mode; RenderMode mode = print_with_reduced_rasterization @@ -446,8 +450,10 @@ void PrintJob::StartPdfToPostScriptConversion( if (ps_level2) { mode = PdfRenderSettings::Mode::POSTSCRIPT_LEVEL2; } else { +#if 0 PrefService* prefs = GetPrefsForWebContents(worker_->GetWebContents()); - mode = PrintWithPostScriptType42Fonts(prefs) +#endif + mode = PrintWithPostScriptType42Fonts(nullptr) ? PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3_WITH_TYPE42_FONTS : PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3; } @@ -504,6 +510,20 @@ void PrintJob::OnPageDone(PrintedPage* page) { } #endif // defined(OS_WIN) +void PrintJob::OnUserInitCancelled() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + // Make sure a `Cancel()` is broadcast. + auto details = base::MakeRefCounted<JobEventDetails>(JobEventDetails::USER_INIT_CANCELED, + 0, nullptr); + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_PRINT_JOB_EVENT, content::Source<PrintJob>(this), + content::Details<JobEventDetails>(details.get())); + + for (auto& observer : observers_) { + observer.OnUserInitCancelled(); + } +} + void PrintJob::OnFailed() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); diff --git a/chrome/browser/printing/print_job.h b/chrome/browser/printing/print_job.h index e19f62354edb8acad722c6680296b7d2f55f51fe..b5539171655d78634ee89faf3516d23ce5718353 100644 --- a/chrome/browser/printing/print_job.h +++ b/chrome/browser/printing/print_job.h @@ -53,6 +53,7 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob> { public: virtual void OnDocDone(int job_id, PrintedDocument* document) {} virtual void OnJobDone() {} + virtual void OnUserInitCancelled() {} virtual void OnFailed() {} }; @@ -100,6 +101,9 @@ class PrintJob : public base::RefCountedThreadSafe<PrintJob> { // Called when the document is done printing. virtual void OnDocDone(int job_id, PrintedDocument* document); + // Called if the user cancels the print job. + virtual void OnUserInitCancelled(); + // Called if the document fails to print. virtual void OnFailed(); @@ -257,6 +261,9 @@ class JobEventDetails : public base::RefCountedThreadSafe<JobEventDetails> { public: // Event type. enum Type { + // Print... dialog box has been closed with CANCEL button. + USER_INIT_CANCELED, + // A new document started printing. NEW_DOC, diff --git a/chrome/browser/printing/print_job_worker.cc b/chrome/browser/printing/print_job_worker.cc index d8f67ab5116483eb2eeb4cc09f19bbcbccb74b37..b4ab0984765c9711ddacf32f7147108cdfbc5096 100644 --- a/chrome/browser/printing/print_job_worker.cc +++ b/chrome/browser/printing/print_job_worker.cc @@ -20,13 +20,13 @@ #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/printing/print_job.h" -#include "chrome/grit/generated_resources.h" #include "components/crash/core/common/crash_keys.h" #include "components/device_event_log/device_event_log.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" +#include "electron/grit/electron_resources.h" #include "printing/backend/print_backend.h" #include "printing/buildflags/buildflags.h" #include "printing/mojom/print.mojom.h" @@ -125,6 +125,10 @@ void FailedNotificationCallback(PrintJob* print_job) { print_job->OnFailed(); } +void UserInitCancelledNotificationCallback(PrintJob* print_job) { + print_job->OnUserInitCancelled(); +} + #if defined(OS_WIN) void PageNotificationCallback(PrintJob* print_job, PrintedPage* page) { print_job->OnPageDone(page); @@ -245,16 +249,21 @@ void PrintJobWorker::UpdatePrintSettings(base::Value new_settings, #endif // defined(OS_LINUX) && defined(USE_CUPS) } - mojom::ResultCode result; { #if defined(OS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ScopedAllowBlocking allow_blocking; #endif - result = printing_context_->UpdatePrintSettings(std::move(new_settings)); + // Reset settings from previous print job + printing_context_->ResetSettings(); + mojom::ResultCode get_default_result = printing_context_->UseDefaultSettings(); + if (get_default_result == mojom::ResultCode::kSuccess) { + mojom::ResultCode update_result = + printing_context_->UpdatePrintSettings(std::move(new_settings)); + GetSettingsDone(std::move(callback), update_result); + } } - GetSettingsDone(std::move(callback), result); } #if defined(OS_CHROMEOS) @@ -270,6 +279,12 @@ void PrintJobWorker::UpdatePrintSettingsFromPOD( void PrintJobWorker::GetSettingsDone(SettingsCallback callback, mojom::ResultCode result) { + if (result == mojom::ResultCode::kCanceled) { + print_job_->PostTask( + FROM_HERE, + base::BindOnce(&UserInitCancelledNotificationCallback, + base::RetainedRef(print_job_.get()))); + } std::move(callback).Run(printing_context_->TakeAndResetSettings(), result); } diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc index c9f1502da55d89de0eede73a7d39047c090594d0..1320afa83016ea72e5dbc23b1ed63cf91d439102 100644 --- a/chrome/browser/printing/print_view_manager_base.cc +++ b/chrome/browser/printing/print_view_manager_base.cc @@ -29,10 +29,10 @@ #include "chrome/browser/printing/print_view_manager_common.h" #include "chrome/browser/printing/printer_query.h" #include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/simple_message_box.h" -#include "chrome/browser/ui/webui/print_preview/printer_handler.h" #include "chrome/common/pref_names.h" +#if 0 #include "chrome/grit/generated_resources.h" +#endif #include "components/prefs/pref_service.h" #include "components/printing/browser/print_composite_client.h" #include "components/printing/browser/print_manager_utils.h" @@ -47,6 +47,7 @@ #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" +#include "electron/grit/electron_resources.h" #include "mojo/public/cpp/system/buffer.h" #include "printing/buildflags/buildflags.h" #include "printing/metafile_skia.h" @@ -110,6 +111,8 @@ crosapi::mojom::PrintJobPtr PrintJobToMojom(int job_id, #endif void ShowWarningMessageBox(const std::u16string& message) { + LOG(ERROR) << "Invalid printer settings " << message; +#if 0 // Runs always on the UI thread. static bool is_dialog_shown = false; if (is_dialog_shown) @@ -118,6 +121,7 @@ void ShowWarningMessageBox(const std::u16string& message) { base::AutoReset<bool> auto_reset(&is_dialog_shown, true); chrome::ShowWarningMessageBox(nullptr, std::u16string(), message); +#endif } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) @@ -217,7 +221,9 @@ void UpdatePrintSettingsReplyOnIO( DCHECK_CURRENTLY_ON(content::BrowserThread::IO); DCHECK(printer_query); mojom::PrintPagesParamsPtr params = CreateEmptyPrintPagesParamsPtr(); - if (printer_query->last_status() == mojom::ResultCode::kSuccess) { + // We call update without first printing from defaults, + // so the last printer status will still be defaulted to PrintingContext::FAILED + if (printer_query) { RenderParamsFromPrintSettings(printer_query->settings(), params->params.get()); params->params->document_cookie = printer_query->cookie(); @@ -319,12 +325,14 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) : PrintManager(web_contents), queue_(g_browser_process->print_job_manager()->queue()) { DCHECK(queue_); +#if 0 // Printing is always enabled. Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); printing_enabled_.Init( prefs::kPrintingEnabled, profile->GetPrefs(), base::BindRepeating(&PrintViewManagerBase::UpdatePrintingEnabled, weak_ptr_factory_.GetWeakPtr())); +#endif } PrintViewManagerBase::~PrintViewManagerBase() { @@ -332,7 +340,10 @@ PrintViewManagerBase::~PrintViewManagerBase() { DisconnectFromCurrentPrintJob(); } -bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { +bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value settings, + CompletionCallback callback) { auto weak_this = weak_ptr_factory_.GetWeakPtr(); DisconnectFromCurrentPrintJob(); if (!weak_this) @@ -347,7 +358,13 @@ bool PrintViewManagerBase::PrintNow(content::RenderFrameHost* rfh) { // go in `ReleasePrintJob()`. SetPrintingRFH(rfh); - GetPrintRenderFrame(rfh)->PrintRequestedPages(); + callback_ = std::move(callback); + + if (!callback_.is_null()) { + print_job_->AddObserver(*this); + } + + GetPrintRenderFrame(rfh)->PrintRequestedPages(silent, std::move(settings)); for (auto& observer : GetObservers()) observer.OnPrintNow(rfh); @@ -506,9 +523,9 @@ void PrintViewManagerBase::ScriptedPrintReply( void PrintViewManagerBase::UpdatePrintingEnabled() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // The Unretained() is safe because ForEachFrame() is synchronous. - web_contents()->ForEachFrame(base::BindRepeating( - &PrintViewManagerBase::SendPrintingEnabled, base::Unretained(this), - printing_enabled_.GetValue())); + web_contents()->ForEachFrame( + base::BindRepeating(&PrintViewManagerBase::SendPrintingEnabled, + base::Unretained(this), true)); } void PrintViewManagerBase::NavigationStopped() { @@ -622,12 +639,13 @@ void PrintViewManagerBase::DidPrintDocument( void PrintViewManagerBase::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { GetDefaultPrintSettingsReply(std::move(callback), mojom::PrintParams::New()); return; } - +#endif content::RenderFrameHost* render_frame_host = GetCurrentTargetFrame(); auto callback_wrapper = base::BindOnce(&PrintViewManagerBase::GetDefaultPrintSettingsReply, @@ -645,18 +663,20 @@ void PrintViewManagerBase::UpdatePrintSettings( base::Value job_settings, UpdatePrintSettingsCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); +#if 0 // Printing is always enabled. if (!printing_enabled_.GetValue()) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } - +#endif if (!job_settings.FindIntKey(kSettingPrinterType)) { UpdatePrintSettingsReply(std::move(callback), CreateEmptyPrintPagesParamsPtr(), false); return; } +#if 0 content::BrowserContext* context = web_contents() ? web_contents()->GetBrowserContext() : nullptr; PrefService* prefs = @@ -666,6 +686,7 @@ void PrintViewManagerBase::UpdatePrintSettings( if (value > 0) job_settings.SetIntKey(kSettingRasterizePdfDpi, value); } +#endif auto callback_wrapper = base::BindOnce(&PrintViewManagerBase::UpdatePrintSettingsReply, @@ -714,7 +735,6 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie) { PrintManager::PrintingFailed(cookie); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) - ShowPrintErrorDialog(); #endif ReleasePrinterQuery(); @@ -729,6 +749,11 @@ void PrintViewManagerBase::RemoveObserver(Observer& observer) { } void PrintViewManagerBase::ShowInvalidPrinterSettingsError() { + if (!callback_.is_null()) { + std::string cb_str = "Invalid printer settings"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ShowWarningMessageBox, l10n_util::GetStringUTF16( @@ -739,8 +764,10 @@ void PrintViewManagerBase::RenderFrameHostStateChanged( content::RenderFrameHost* render_frame_host, content::RenderFrameHost::LifecycleState /*old_state*/, content::RenderFrameHost::LifecycleState new_state) { +#if 0 // Printing is always enabled. if (new_state == content::RenderFrameHost::LifecycleState::kActive) SendPrintingEnabled(printing_enabled_.GetValue(), render_frame_host); +#endif } void PrintViewManagerBase::DidStartLoading() { @@ -808,6 +835,11 @@ void PrintViewManagerBase::OnJobDone() { ReleasePrintJob(); } +void PrintViewManagerBase::OnUserInitCancelled() { + printing_cancelled_ = true; + ReleasePrintJob(); +} + void PrintViewManagerBase::OnFailed() { TerminatePrintJob(true); } @@ -869,7 +901,10 @@ bool PrintViewManagerBase::CreateNewPrintJob( // Disconnect the current |print_job_|. auto weak_this = weak_ptr_factory_.GetWeakPtr(); - DisconnectFromCurrentPrintJob(); + if (callback_.is_null()) { + // Disconnect the current |print_job_| only when calling window.print() + DisconnectFromCurrentPrintJob(); + } if (!weak_this) return false; @@ -891,8 +926,6 @@ bool PrintViewManagerBase::CreateNewPrintJob( : PrintJob::Source::PRINT_PREVIEW, /*source_id=*/""); #endif - print_job_->AddObserver(*this); - printing_succeeded_ = false; return true; } @@ -944,14 +977,21 @@ void PrintViewManagerBase::ReleasePrintJob() { content::RenderFrameHost* rfh = printing_rfh_; printing_rfh_ = nullptr; + if (!callback_.is_null()) { + print_job_->RemoveObserver(*this); + + std::string cb_str = ""; + if (!printing_succeeded_) + cb_str = printing_cancelled_ ? "cancelled" : "failed"; + std::move(callback_).Run(printing_succeeded_, cb_str); + } + if (!print_job_) return; if (rfh) GetPrintRenderFrame(rfh)->PrintingDone(printing_succeeded_); - print_job_->RemoveObserver(*this); - // Don't close the worker thread. print_job_ = nullptr; } @@ -989,7 +1029,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() { } bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) { - if (print_job_) + if (print_job_ && print_job_->document()) return true; if (!cookie) { diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h index 5771a3ebd76145c6cf8a2ccc33abc886802ed59f..1562d6331a9cafd530db42c436e878bac427566d 100644 --- a/chrome/browser/printing/print_view_manager_base.h +++ b/chrome/browser/printing/print_view_manager_base.h @@ -37,6 +37,8 @@ namespace printing { class PrintQueriesQueue; class PrinterQuery; +using CompletionCallback = base::OnceCallback<void(bool, const std::string&)>; + // Base class for managing the print commands for a WebContents. class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { public: @@ -58,7 +60,10 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // Prints the current document immediately. Since the rendering is // asynchronous, the actual printing will not be completed on the return of // this function. Returns false if printing is impossible at the moment. - virtual bool PrintNow(content::RenderFrameHost* rfh); + virtual bool PrintNow(content::RenderFrameHost* rfh, + bool silent, + base::Value settings, + CompletionCallback callback); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Prints the document in |print_data| with settings specified in @@ -143,6 +148,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // PrintJob::Observer overrides: void OnDocDone(int job_id, PrintedDocument* document) override; void OnJobDone() override; + void OnUserInitCancelled() override; void OnFailed() override; base::ObserverList<Observer>& GetObservers() { return observers_; } @@ -252,9 +258,15 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer { // The current RFH that is printing with a system printing dialog. raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr; + // Respond with success of the print job. + CompletionCallback callback_; + // Indication of success of the print job. bool printing_succeeded_ = false; + // Indication of whether the print job was manually cancelled + bool printing_cancelled_ = false; + // Set while running an inner message loop inside RenderAllMissingPagesNow(). // This means we are _blocking_ until all the necessary pages have been // rendered or the print settings are being loaded. diff --git a/components/printing/common/print.mojom b/components/printing/common/print.mojom index 51ebcb4ae399018d3fd8566656596a7ef1f148af..5f2b807fc364131f4c3e6a1646ec522ddc826d9c 100644 --- a/components/printing/common/print.mojom +++ b/components/printing/common/print.mojom @@ -274,7 +274,7 @@ interface PrintPreviewUI { interface PrintRenderFrame { // Tells the RenderFrame to switch the CSS to print media type, render every // requested page, and then switch back the CSS to display media type. - PrintRequestedPages(); + PrintRequestedPages(bool silent, mojo_base.mojom.DictionaryValue settings); // Tells the RenderFrame to switch the CSS to print media type, render every // requested page using the print preview document's frame/node, and then diff --git a/components/printing/renderer/print_render_frame_helper.cc b/components/printing/renderer/print_render_frame_helper.cc index 650b5550f982fa5c5c522efaa9b8e305b7edc5e7..260b5521dccadf07eba2c67fa3d9c3da80b49104 100644 --- a/components/printing/renderer/print_render_frame_helper.cc +++ b/components/printing/renderer/print_render_frame_helper.cc @@ -39,6 +39,7 @@ #include "printing/metafile_skia.h" #include "printing/mojom/print.mojom.h" #include "printing/print_job_constants.h" +#include "printing/print_settings.h" #include "printing/units.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" @@ -1226,7 +1227,8 @@ void PrintRenderFrameHelper::ScriptedPrint(bool user_initiated) { if (!weak_this) return; - Print(web_frame, blink::WebNode(), PrintRequestType::kScripted); + Print(web_frame, blink::WebNode(), PrintRequestType::kScripted, + false /* silent */, base::DictionaryValue() /* new_settings */); if (!weak_this) return; @@ -1257,7 +1259,7 @@ void PrintRenderFrameHelper::BindPrintRenderFrameReceiver( receivers_.Add(this, std::move(receiver)); } -void PrintRenderFrameHelper::PrintRequestedPages() { +void PrintRenderFrameHelper::PrintRequestedPages(bool silent, base::Value settings) { ScopedIPC scoped_ipc(weak_ptr_factory_.GetWeakPtr()); if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; @@ -1272,7 +1274,7 @@ void PrintRenderFrameHelper::PrintRequestedPages() { // plugin node and print that instead. auto plugin = delegate_->GetPdfElement(frame); - Print(frame, plugin, PrintRequestType::kRegular); + Print(frame, plugin, PrintRequestType::kRegular, silent, std::move(settings)); if (!render_frame_gone_) frame->DispatchAfterPrintEvent(); @@ -1303,7 +1305,8 @@ void PrintRenderFrameHelper::PrintForSystemDialog() { } Print(frame, print_preview_context_.source_node(), - PrintRequestType::kRegular); + PrintRequestType::kRegular, false, + base::DictionaryValue()); if (!render_frame_gone_) print_preview_context_.DispatchAfterPrintEvent(); // WARNING: |this| may be gone at this point. Do not do any more work here and @@ -1350,6 +1353,8 @@ void PrintRenderFrameHelper::PrintPreview(base::Value settings) { if (ipc_nesting_level_ > kAllowedIpcDepthForPrint) return; + blink::WebLocalFrame* frame = render_frame()->GetWebFrame(); + print_preview_context_.InitWithFrame(frame); print_preview_context_.OnPrintPreview(); if (print_preview_context_.IsForArc()) { @@ -1886,7 +1891,8 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { return; Print(duplicate_node.GetDocument().GetFrame(), duplicate_node, - PrintRequestType::kRegular); + PrintRequestType::kRegular, false /* silent */, + base::DictionaryValue() /* new_settings */); // Check if |this| is still valid. if (!weak_this) return; @@ -1901,7 +1907,9 @@ void PrintRenderFrameHelper::PrintNode(const blink::WebNode& node) { void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type) { + PrintRequestType print_request_type, + bool silent, + base::Value settings) { // If still not finished with earlier print request simply ignore. if (prep_frame_view_) return; @@ -1909,7 +1917,7 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, FrameReference frame_ref(frame); uint32_t expected_page_count = 0; - if (!CalculateNumberOfPages(frame, node, &expected_page_count)) { + if (!CalculateNumberOfPages(frame, node, &expected_page_count, base::Value::AsDictionaryValue(settings))) { DidFinishPrinting(FAIL_PRINT_INIT); return; // Failed to init print page settings. } @@ -1928,8 +1936,15 @@ void PrintRenderFrameHelper::Print(blink::WebLocalFrame* frame, print_pages_params_->params->print_scaling_option; auto self = weak_ptr_factory_.GetWeakPtr(); - mojom::PrintPagesParamsPtr print_settings = GetPrintSettingsFromUser( + mojom::PrintPagesParamsPtr print_settings; + + if (silent) { + print_settings = mojom::PrintPagesParams::New(); + print_settings->params = print_pages_params_->params->Clone(); + } else { + print_settings = GetPrintSettingsFromUser( frame_ref.GetFrame(), node, expected_page_count, print_request_type); + } // Check if |this| is still valid. if (!self) return; @@ -2177,36 +2192,51 @@ void PrintRenderFrameHelper::IPCProcessed() { } } -bool PrintRenderFrameHelper::InitPrintSettings(bool fit_to_paper_size) { - mojom::PrintPagesParams settings; - settings.params = mojom::PrintParams::New(); - GetPrintManagerHost()->GetDefaultPrintSettings(&settings.params); +bool PrintRenderFrameHelper::InitPrintSettings( + bool fit_to_paper_size, + const base::DictionaryValue& new_settings) { + mojom::PrintPagesParamsPtr settings; + + if (new_settings.DictEmpty()) { + settings = mojom::PrintPagesParams::New(); + settings->params = mojom::PrintParams::New(); + GetPrintManagerHost()->GetDefaultPrintSettings(&settings->params); + } else { + bool canceled = false; + int cookie = + print_pages_params_ ? print_pages_params_->params->document_cookie : 0; + GetPrintManagerHost()->UpdatePrintSettings(cookie, new_settings.Clone(), &settings, &canceled); + if (canceled) + return false; + } // Check if the printer returned any settings, if the settings is empty, we // can safely assume there are no printer drivers configured. So we safely // terminate. bool result = true; - if (!PrintMsg_Print_Params_IsValid(*settings.params)) + if (!PrintMsg_Print_Params_IsValid(*settings->params)) result = false; // Reset to default values. ignore_css_margins_ = false; - settings.pages.clear(); + settings->pages.clear(); - settings.params->print_scaling_option = + settings->params->print_scaling_option = fit_to_paper_size ? mojom::PrintScalingOption::kFitToPrintableArea : mojom::PrintScalingOption::kSourceSize; - SetPrintPagesParams(settings); + SetPrintPagesParams(*settings); return result; } -bool PrintRenderFrameHelper::CalculateNumberOfPages(blink::WebLocalFrame* frame, - const blink::WebNode& node, - uint32_t* number_of_pages) { +bool PrintRenderFrameHelper::CalculateNumberOfPages( + blink::WebLocalFrame* frame, + const blink::WebNode& node, + uint32_t* number_of_pages, + const base::DictionaryValue& settings) { DCHECK(frame); bool fit_to_paper_size = !IsPrintingNodeOrPdfFrame(frame, node); - if (!InitPrintSettings(fit_to_paper_size)) { + if (!InitPrintSettings(fit_to_paper_size, settings)) { notify_browser_of_print_failure_ = false; GetPrintManagerHost()->ShowInvalidPrinterSettingsError(); return false; @@ -2579,18 +2609,7 @@ void PrintRenderFrameHelper::RequestPrintPreview(PrintPreviewRequestType type) { } bool PrintRenderFrameHelper::CheckForCancel() { - const mojom::PrintParams& print_params = *print_pages_params_->params; - bool cancel = false; - - if (!GetPrintManagerHost()->CheckForCancel(print_params.preview_ui_id, - print_params.preview_request_id, - &cancel)) { - cancel = true; - } - - if (cancel) - notify_browser_of_print_failure_ = false; - return cancel; + return false; } bool PrintRenderFrameHelper::PreviewPageRendered( diff --git a/components/printing/renderer/print_render_frame_helper.h b/components/printing/renderer/print_render_frame_helper.h index 90236920457c931c86426049c6cbc30b592b597f..353178863eba37b9112e784ffa4b3519076e91b9 100644 --- a/components/printing/renderer/print_render_frame_helper.h +++ b/components/printing/renderer/print_render_frame_helper.h @@ -256,7 +256,7 @@ class PrintRenderFrameHelper mojo::PendingAssociatedReceiver<mojom::PrintRenderFrame> receiver); // printing::mojom::PrintRenderFrame: - void PrintRequestedPages() override; + void PrintRequestedPages(bool silent, base::Value settings) override; #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintForSystemDialog() override; void SetPrintPreviewUI( @@ -323,7 +323,9 @@ class PrintRenderFrameHelper // WARNING: |this| may be gone after this method returns. void Print(blink::WebLocalFrame* frame, const blink::WebNode& node, - PrintRequestType print_request_type); + PrintRequestType print_request_type, + bool silent, + base::Value settings); // Notification when printing is done - signal tear-down/free resources. void DidFinishPrinting(PrintingResult result); @@ -332,12 +334,14 @@ class PrintRenderFrameHelper // Initialize print page settings with default settings. // Used only for native printing workflow. - bool InitPrintSettings(bool fit_to_paper_size); + bool InitPrintSettings(bool fit_to_paper_size, + const base::DictionaryValue& settings); // Calculate number of pages in source document. bool CalculateNumberOfPages(blink::WebLocalFrame* frame, const blink::WebNode& node, - uint32_t* number_of_pages); + uint32_t* number_of_pages, + const base::DictionaryValue& settings); #if BUILDFLAG(ENABLE_PRINT_PREVIEW) // Set options for print preset from source PDF document. diff --git a/printing/printing_context.cc b/printing/printing_context.cc index f8f0f4bdfbb8db883f883f62f9d6e4b987d7b113..c2505f5e0049dc7ee8783056538ca4c2d0968744 100644 --- a/printing/printing_context.cc +++ b/printing/printing_context.cc @@ -120,7 +120,6 @@ mojom::ResultCode PrintingContext::UsePdfSettings() { mojom::ResultCode PrintingContext::UpdatePrintSettings( base::Value job_settings) { - ResetSettings(); { std::unique_ptr<PrintSettings> settings = PrintSettingsFromJobSettings(job_settings); diff --git a/printing/printing_context.h b/printing/printing_context.h index 7d937e7e3f19df351d410185fc4dc3b7c8937f2e..e87170e6957733f06bcc296bcca3fc331557ed46 100644 --- a/printing/printing_context.h +++ b/printing/printing_context.h @@ -175,6 +175,9 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { std::unique_ptr<PrintSettings> TakeAndResetSettings(); + // Reinitializes the settings for object reuse. + void ResetSettings(); + int job_id() const { return job_id_; } protected: @@ -185,9 +188,6 @@ class COMPONENT_EXPORT(PRINTING) PrintingContext { static std::unique_ptr<PrintingContext> CreateImpl(Delegate* delegate, bool skip_system_calls); - // Reinitializes the settings for object reuse. - void ResetSettings(); - // Determine if system calls should be skipped by this instance. bool skip_system_calls() const { #if BUILDFLAG(ENABLE_OOP_PRINTING)
closed
electron/electron
https://github.com/electron/electron
32,360
[Bug]: Windows Control Overlay button hover effect not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 14.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Actual Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Testcase Gist URL _No response_ ### Additional Information I am creating this issue based on https://github.com/electron/electron/issues/30764 and the information I have gathered while trying to triage it. Though this not a breaking bug, it does create a visual inconsistency for users, as a window control button would typically change color when hovered over. For this reason, I think it should still be addressed at some point. Consolidating all current information and future questions/comments here should help in finding a solution. [Here](https://bugs.chromium.org/p/chromium/issues/detail?id=1218921) is a link to the bug that led to the original fix implemented in Chromium And [here](https://bugs.chromium.org/p/chromium/issues/detail?id=1271293#c1) is the link to the follow-up bug report created noting issues with the implemented fix. This was then labeled as `WontFix` The chromium fix artificially creates the correct tooltips and allows for the button color to change on hover. However, this results in a response to the `WM_NCHITTEST` [message](https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-nchittest) that does not correspond with the function of the button. For example, `HTMAXIMIZE` is not returned, thus Snap Layout on Windows 11 does not work. If someone else wants to take a look at this, the relevant Electron files can be found in [this PR](https://github.com/electron/electron/pull/29600) adding WCO to Electron. For this bug in particular, I believe the related files are: `shell/browser/ui/views/win_caption_button.cc`, `shell/browser/ui/views/win_caption_button_container.cc`, and `shell/browser/ui/views/win_frame_view.cc` but changes to other files may provide a solution as well.
https://github.com/electron/electron/issues/32360
https://github.com/electron/electron/pull/32672
8b6202b6a8847ddd28768fe09b0e014259a6b8e7
9a5a45e804d83ea06f458d2ff9020aec87ffc17d
2022-01-06T00:01:50Z
c++
2022-02-02T15:06:36Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" #if BUILDFLAG(ENABLE_WIN_DARK_MODE_WINDOW_UI) #include "shell/browser/win/dark_mode.h" #endif namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { #if BUILDFLAG(ENABLE_WIN_DARK_MODE_WINDOW_UI) if (message == WM_NCCREATE) { HWND const hwnd = GetAcceleratedWidget(); auto const theme_source = ui::NativeTheme::GetInstanceForNativeUi()->theme_source(); win::SetDarkModeForWindow(hwnd, theme_source); } #endif return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { // Tell Chromium to use system default behavior when rendering inactive // titlebar, otherwise it would render inactive titlebar as active under // some cases. // See also https://github.com/electron/electron/issues/24647. return false; } bool ElectronDesktopWindowTreeHostWin::HasNativeFrame() const { // Since we never use chromium's titlebar implementation, we can just say // that we use a native titlebar. This will disable the repaint locking when // DWM composition is disabled. // See also https://github.com/electron/electron/issues/1821. return !ui::win::IsAeroGlassEnabled(); } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by deafult extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current moniotr. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); insets->Set(thickness, thickness, thickness, thickness); return true; } return false; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,360
[Bug]: Windows Control Overlay button hover effect not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 14.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Actual Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Testcase Gist URL _No response_ ### Additional Information I am creating this issue based on https://github.com/electron/electron/issues/30764 and the information I have gathered while trying to triage it. Though this not a breaking bug, it does create a visual inconsistency for users, as a window control button would typically change color when hovered over. For this reason, I think it should still be addressed at some point. Consolidating all current information and future questions/comments here should help in finding a solution. [Here](https://bugs.chromium.org/p/chromium/issues/detail?id=1218921) is a link to the bug that led to the original fix implemented in Chromium And [here](https://bugs.chromium.org/p/chromium/issues/detail?id=1271293#c1) is the link to the follow-up bug report created noting issues with the implemented fix. This was then labeled as `WontFix` The chromium fix artificially creates the correct tooltips and allows for the button color to change on hover. However, this results in a response to the `WM_NCHITTEST` [message](https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-nchittest) that does not correspond with the function of the button. For example, `HTMAXIMIZE` is not returned, thus Snap Layout on Windows 11 does not work. If someone else wants to take a look at this, the relevant Electron files can be found in [this PR](https://github.com/electron/electron/pull/29600) adding WCO to Electron. For this bug in particular, I believe the related files are: `shell/browser/ui/views/win_caption_button.cc`, `shell/browser/ui/views/win_caption_button_container.cc`, and `shell/browser/ui/views/win_frame_view.cc` but changes to other files may provide a solution as well.
https://github.com/electron/electron/issues/32360
https://github.com/electron/electron/pull/32672
8b6202b6a8847ddd28768fe09b0e014259a6b8e7
9a5a45e804d83ea06f458d2ff9020aec87ffc17d
2022-01-06T00:01:50Z
c++
2022-02-02T15:06:36Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #include <windows.h> #include "shell/browser/native_window_views.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" namespace electron { class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin { public: ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura); ~ElectronDesktopWindowTreeHostWin() override; // disable copy ElectronDesktopWindowTreeHostWin(const ElectronDesktopWindowTreeHostWin&) = delete; ElectronDesktopWindowTreeHostWin& operator=( const ElectronDesktopWindowTreeHostWin&) = delete; protected: bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; bool ShouldPaintAsActive() const override; bool HasNativeFrame() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override; private: NativeWindowViews* native_window_view_; // weak ref }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_
closed
electron/electron
https://github.com/electron/electron
32,360
[Bug]: Windows Control Overlay button hover effect not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 14.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Actual Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Testcase Gist URL _No response_ ### Additional Information I am creating this issue based on https://github.com/electron/electron/issues/30764 and the information I have gathered while trying to triage it. Though this not a breaking bug, it does create a visual inconsistency for users, as a window control button would typically change color when hovered over. For this reason, I think it should still be addressed at some point. Consolidating all current information and future questions/comments here should help in finding a solution. [Here](https://bugs.chromium.org/p/chromium/issues/detail?id=1218921) is a link to the bug that led to the original fix implemented in Chromium And [here](https://bugs.chromium.org/p/chromium/issues/detail?id=1271293#c1) is the link to the follow-up bug report created noting issues with the implemented fix. This was then labeled as `WontFix` The chromium fix artificially creates the correct tooltips and allows for the button color to change on hover. However, this results in a response to the `WM_NCHITTEST` [message](https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-nchittest) that does not correspond with the function of the button. For example, `HTMAXIMIZE` is not returned, thus Snap Layout on Windows 11 does not work. If someone else wants to take a look at this, the relevant Electron files can be found in [this PR](https://github.com/electron/electron/pull/29600) adding WCO to Electron. For this bug in particular, I believe the related files are: `shell/browser/ui/views/win_caption_button.cc`, `shell/browser/ui/views/win_caption_button_container.cc`, and `shell/browser/ui/views/win_frame_view.cc` but changes to other files may provide a solution as well.
https://github.com/electron/electron/issues/32360
https://github.com/electron/electron/pull/32672
8b6202b6a8847ddd28768fe09b0e014259a6b8e7
9a5a45e804d83ea06f458d2ff9020aec87ffc17d
2022-01-06T00:01:50Z
c++
2022-02-02T15:06:36Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" #if BUILDFLAG(ENABLE_WIN_DARK_MODE_WINDOW_UI) #include "shell/browser/win/dark_mode.h" #endif namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { #if BUILDFLAG(ENABLE_WIN_DARK_MODE_WINDOW_UI) if (message == WM_NCCREATE) { HWND const hwnd = GetAcceleratedWidget(); auto const theme_source = ui::NativeTheme::GetInstanceForNativeUi()->theme_source(); win::SetDarkModeForWindow(hwnd, theme_source); } #endif return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { // Tell Chromium to use system default behavior when rendering inactive // titlebar, otherwise it would render inactive titlebar as active under // some cases. // See also https://github.com/electron/electron/issues/24647. return false; } bool ElectronDesktopWindowTreeHostWin::HasNativeFrame() const { // Since we never use chromium's titlebar implementation, we can just say // that we use a native titlebar. This will disable the repaint locking when // DWM composition is disabled. // See also https://github.com/electron/electron/issues/1821. return !ui::win::IsAeroGlassEnabled(); } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by deafult extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current moniotr. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); insets->Set(thickness, thickness, thickness, thickness); return true; } return false; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,360
[Bug]: Windows Control Overlay button hover effect not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 14.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 11 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Actual Behavior See https://github.com/electron/electron/issues/30764 for specific behavior ### Testcase Gist URL _No response_ ### Additional Information I am creating this issue based on https://github.com/electron/electron/issues/30764 and the information I have gathered while trying to triage it. Though this not a breaking bug, it does create a visual inconsistency for users, as a window control button would typically change color when hovered over. For this reason, I think it should still be addressed at some point. Consolidating all current information and future questions/comments here should help in finding a solution. [Here](https://bugs.chromium.org/p/chromium/issues/detail?id=1218921) is a link to the bug that led to the original fix implemented in Chromium And [here](https://bugs.chromium.org/p/chromium/issues/detail?id=1271293#c1) is the link to the follow-up bug report created noting issues with the implemented fix. This was then labeled as `WontFix` The chromium fix artificially creates the correct tooltips and allows for the button color to change on hover. However, this results in a response to the `WM_NCHITTEST` [message](https://docs.microsoft.com/en-us/windows/win32/inputdev/wm-nchittest) that does not correspond with the function of the button. For example, `HTMAXIMIZE` is not returned, thus Snap Layout on Windows 11 does not work. If someone else wants to take a look at this, the relevant Electron files can be found in [this PR](https://github.com/electron/electron/pull/29600) adding WCO to Electron. For this bug in particular, I believe the related files are: `shell/browser/ui/views/win_caption_button.cc`, `shell/browser/ui/views/win_caption_button_container.cc`, and `shell/browser/ui/views/win_frame_view.cc` but changes to other files may provide a solution as well.
https://github.com/electron/electron/issues/32360
https://github.com/electron/electron/pull/32672
8b6202b6a8847ddd28768fe09b0e014259a6b8e7
9a5a45e804d83ea06f458d2ff9020aec87ffc17d
2022-01-06T00:01:50Z
c++
2022-02-02T15:06:36Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #include <windows.h> #include "shell/browser/native_window_views.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" namespace electron { class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin { public: ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura); ~ElectronDesktopWindowTreeHostWin() override; // disable copy ElectronDesktopWindowTreeHostWin(const ElectronDesktopWindowTreeHostWin&) = delete; ElectronDesktopWindowTreeHostWin& operator=( const ElectronDesktopWindowTreeHostWin&) = delete; protected: bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; bool ShouldPaintAsActive() const override; bool HasNativeFrame() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override; private: NativeWindowViews* native_window_view_; // weak ref }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_
closed
electron/electron
https://github.com/electron/electron
32,455
Update deprecated QuickLook Thumbnailing methods
Nearly all methods we use in `nativeImage.createThumbnailFromPath()` are deprecated on macOS as of 10.15 and scheduled for imminent removal - we should update our usage of those methods to the newer `QuickLookThumbnailing` framework accordingly. See [here](https://developer.apple.com/documentation/quicklook/previews_or_thumbnail_images_for_macos_10_14_or_earlier?language=objc) for deprecation information and [here](https://developer.apple.com/documentation/quicklookthumbnailing?language=objc) for the updated framework we should use.
https://github.com/electron/electron/issues/32455
https://github.com/electron/electron/pull/32456
c3d11e2ea2d9751a457c72805b7688a38ceac30a
4c39eb32b0d2be479b9a0856186c6dfeccae6b96
2022-01-13T13:46:22Z
c++
2022-02-02T22:01:05Z
BUILD.gn
import("//build/config/locales.gni") import("//build/config/ui.gni") import("//build/config/win/manifest.gni") import("//components/os_crypt/features.gni") import("//components/spellcheck/spellcheck_build_features.gni") import("//content/public/app/mac_helpers.gni") import("//extensions/buildflags/buildflags.gni") import("//pdf/features.gni") import("//ppapi/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//testing/test.gni") import("//third_party/ffmpeg/ffmpeg_options.gni") import("//tools/generate_library_loader/generate_library_loader.gni") import("//tools/grit/grit_rule.gni") import("//tools/grit/repack.gni") import("//tools/v8_context_snapshot/v8_context_snapshot.gni") import("//v8/gni/snapshot_toolchain.gni") import("build/asar.gni") import("build/extract_symbols.gni") import("build/npm.gni") import("build/templated_file.gni") import("build/tsc.gni") import("build/webpack/webpack.gni") import("buildflags/buildflags.gni") import("electron_paks.gni") import("filenames.auto.gni") import("filenames.gni") import("filenames.hunspell.gni") import("filenames.libcxx.gni") import("filenames.libcxxabi.gni") if (is_mac) { import("//build/config/mac/rules.gni") import("//third_party/icu/config.gni") import("//ui/gl/features.gni") import("//v8/gni/v8.gni") import("build/rules.gni") assert( mac_deployment_target == "10.11.0", "Chromium has updated the mac_deployment_target, please update this assert, update the supported versions documentation (docs/tutorial/support.md) and flag this as a breaking change") } if (is_linux) { import("//build/config/linux/pkg_config.gni") pkg_config("gio_unix") { packages = [ "gio-unix-2.0" ] } pkg_config("libnotify_config") { packages = [ "glib-2.0", "gdk-pixbuf-2.0", ] } } declare_args() { use_prebuilt_v8_context_snapshot = false } branding = read_file("shell/app/BRANDING.json", "json") electron_project_name = branding.project_name electron_product_name = branding.product_name electron_mac_bundle_id = branding.mac_bundle_id if (is_mas_build) { assert(is_mac, "It doesn't make sense to build a MAS build on a non-mac platform") } if (enable_pdf_viewer) { assert(enable_pdf, "PDF viewer support requires enable_pdf=true") assert(enable_electron_extensions, "PDF viewer support requires enable_electron_extensions=true") } if (enable_electron_extensions) { assert(enable_extensions, "Chrome extension support requires enable_extensions=true") } config("branding") { defines = [ "ELECTRON_PRODUCT_NAME=\"$electron_product_name\"", "ELECTRON_PROJECT_NAME=\"$electron_project_name\"", ] } config("electron_lib_config") { include_dirs = [ "." ] } # We geneate the definitions twice here, once in //electron/electron.d.ts # and once in $target_gen_dir # The one in $target_gen_dir is used for the actual TSC build later one # and the one in //electron/electron.d.ts is used by your IDE (vscode) # for typescript prompting npm_action("build_electron_definitions") { script = "gn-typescript-definitions" args = [ rebase_path("$target_gen_dir/tsc/typings/electron.d.ts") ] inputs = auto_filenames.api_docs + [ "yarn.lock" ] outputs = [ "$target_gen_dir/tsc/typings/electron.d.ts" ] } webpack_build("electron_asar_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.asar_bundle_deps config_file = "//electron/build/webpack/webpack.config.asar.js" out_file = "$target_gen_dir/js2c/asar_bundle.js" } webpack_build("electron_browser_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.browser_bundle_deps config_file = "//electron/build/webpack/webpack.config.browser.js" out_file = "$target_gen_dir/js2c/browser_init.js" } webpack_build("electron_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.renderer_bundle_deps config_file = "//electron/build/webpack/webpack.config.renderer.js" out_file = "$target_gen_dir/js2c/renderer_init.js" } webpack_build("electron_worker_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.worker_bundle_deps config_file = "//electron/build/webpack/webpack.config.worker.js" out_file = "$target_gen_dir/js2c/worker_init.js" } webpack_build("electron_sandboxed_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.sandbox_bundle_deps config_file = "//electron/build/webpack/webpack.config.sandboxed_renderer.js" out_file = "$target_gen_dir/js2c/sandbox_bundle.js" } webpack_build("electron_isolated_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.isolated_bundle_deps config_file = "//electron/build/webpack/webpack.config.isolated_renderer.js" out_file = "$target_gen_dir/js2c/isolated_bundle.js" } action("electron_js2c") { deps = [ ":electron_asar_bundle", ":electron_browser_bundle", ":electron_isolated_renderer_bundle", ":electron_renderer_bundle", ":electron_sandboxed_renderer_bundle", ":electron_worker_bundle", ] sources = [ "$target_gen_dir/js2c/asar_bundle.js", "$target_gen_dir/js2c/browser_init.js", "$target_gen_dir/js2c/isolated_bundle.js", "$target_gen_dir/js2c/renderer_init.js", "$target_gen_dir/js2c/sandbox_bundle.js", "$target_gen_dir/js2c/worker_init.js", ] inputs = sources + [ "//third_party/electron_node/tools/js2c.py" ] outputs = [ "$root_gen_dir/electron_natives.cc" ] script = "build/js2c.py" args = [ rebase_path("//third_party/electron_node") ] + rebase_path(outputs, root_build_dir) + rebase_path(sources, root_build_dir) } action("generate_config_gypi") { outputs = [ "$root_gen_dir/config.gypi" ] script = "script/generate-config-gypi.py" args = rebase_path(outputs) + [ target_cpu ] } target_gen_default_app_js = "$target_gen_dir/js/default_app" typescript_build("default_app_js") { deps = [ ":build_electron_definitions" ] sources = filenames.default_app_ts_sources output_gen_dir = target_gen_default_app_js output_dir_name = "default_app" tsconfig = "tsconfig.default_app.json" } copy("default_app_static") { sources = filenames.default_app_static_sources outputs = [ "$target_gen_default_app_js/{{source}}" ] } copy("default_app_octicon_deps") { sources = filenames.default_app_octicon_sources outputs = [ "$target_gen_default_app_js/electron/default_app/octicon/{{source_file_part}}" ] } asar("default_app_asar") { deps = [ ":default_app_js", ":default_app_octicon_deps", ":default_app_static", ] root = "$target_gen_default_app_js/electron/default_app" sources = get_target_outputs(":default_app_js") + get_target_outputs(":default_app_static") + get_target_outputs(":default_app_octicon_deps") outputs = [ "$root_out_dir/resources/default_app.asar" ] } grit("resources") { source = "electron_resources.grd" outputs = [ "grit/electron_resources.h", "electron_resources.pak", ] # Mojo manifest overlays are generated. grit_flags = [ "-E", "target_gen_dir=" + rebase_path(target_gen_dir, root_build_dir), ] deps = [ ":copy_shell_devtools_discovery_page" ] output_dir = "$target_gen_dir" } copy("copy_shell_devtools_discovery_page") { sources = [ "//content/shell/resources/shell_devtools_discovery_page.html" ] outputs = [ "$target_gen_dir/shell_devtools_discovery_page.html" ] } if (is_linux) { generate_library_loader("libnotify_loader") { name = "LibNotifyLoader" output_h = "libnotify_loader.h" output_cc = "libnotify_loader.cc" header = "<libnotify/notify.h>" config = ":libnotify_config" functions = [ "notify_is_initted", "notify_init", "notify_get_server_caps", "notify_get_server_info", "notify_notification_new", "notify_notification_add_action", "notify_notification_set_image_from_pixbuf", "notify_notification_set_timeout", "notify_notification_set_urgency", "notify_notification_set_hint_string", "notify_notification_show", "notify_notification_close", ] } } npm_action("electron_version_args") { script = "generate-version-json" outputs = [ "$target_gen_dir/electron_version.args" ] args = rebase_path(outputs) inputs = [ "ELECTRON_VERSION", "script/generate-version-json.js", ] } templated_file("electron_version_header") { deps = [ ":electron_version_args" ] template = "build/templates/electron_version.tmpl" output = "$target_gen_dir/electron_version.h" args_files = get_target_outputs(":electron_version_args") } action("electron_fuses") { script = "build/fuses/build.py" inputs = [ "build/fuses/fuses.json5" ] outputs = [ "$target_gen_dir/fuses.h", "$target_gen_dir/fuses.cc", ] args = rebase_path(outputs) } action("electron_generate_node_defines") { script = "build/generate_node_defines.py" inputs = [ "//third_party/electron_node/src/tracing/trace_event_common.h", "//third_party/electron_node/src/tracing/trace_event.h", "//third_party/electron_node/src/util.h", ] outputs = [ "$target_gen_dir/push_and_undef_node_defines.h", "$target_gen_dir/pop_node_defines.h", ] args = [ rebase_path(target_gen_dir) ] + rebase_path(inputs) } source_set("electron_lib") { configs += [ "//v8:external_startup_data" ] configs += [ "//third_party/electron_node:node_internals" ] public_configs = [ ":branding", ":electron_lib_config", ] deps = [ ":electron_fuses", ":electron_generate_node_defines", ":electron_js2c", ":electron_version_header", ":resources", "buildflags", "chromium_src:chrome", "chromium_src:chrome_spellchecker", "shell/common/api:mojo", "//base:base_static", "//base/allocator:buildflags", "//chrome/app:command_ids", "//chrome/app/resources:platform_locale_settings", "//components/autofill/core/common:features", "//components/certificate_transparency", "//components/language/core/browser", "//components/net_log", "//components/network_hints/browser", "//components/network_hints/common:mojo_bindings", "//components/network_hints/renderer", "//components/network_session_configurator/common", "//components/os_crypt", "//components/pref_registry", "//components/prefs", "//components/security_state/content", "//components/upload_list", "//components/user_prefs", "//components/viz/host", "//components/viz/service", "//content/public/browser", "//content/public/child", "//content/public/gpu", "//content/public/renderer", "//content/public/utility", "//device/bluetooth", "//device/bluetooth/public/cpp", "//gin", "//media/capture/mojom:video_capture", "//media/mojo/mojom", "//net:extras", "//net:net_resources", "//ppapi/host", "//ppapi/proxy", "//ppapi/shared_impl", "//printing/buildflags", "//services/device/public/cpp/geolocation", "//services/device/public/cpp/hid", "//services/device/public/mojom", "//services/proxy_resolver:lib", "//services/video_capture/public/mojom:constants", "//services/viz/privileged/mojom/compositing", "//skia", "//third_party/blink/public:blink", "//third_party/blink/public:blink_devtools_inspector_resources", "//third_party/blink/public/platform/media", "//third_party/boringssl", "//third_party/electron_node:node_lib", "//third_party/inspector_protocol:crdtp", "//third_party/leveldatabase", "//third_party/libyuv", "//third_party/webrtc_overrides:webrtc_component", "//third_party/widevine/cdm:headers", "//third_party/zlib/google:zip", "//ui/base/idle", "//ui/events:dom_keycode_converter", "//ui/gl", "//ui/native_theme", "//ui/shell_dialogs", "//ui/views", "//v8", "//v8:v8_libplatform", ] public_deps = [ "//base", "//base:i18n", "//content/public/app", ] include_dirs = [ ".", "$target_gen_dir", # TODO(nornagon): replace usage of SchemeRegistry by an actually exported # API of blink, then remove this from the include_dirs. "//third_party/blink/renderer", ] defines = [ "V8_DEPRECATION_WARNINGS" ] libs = [] if (is_linux) { defines += [ "GDK_DISABLE_DEPRECATION_WARNINGS" ] } if (!is_mas_build) { deps += [ "//components/crash/core/app", "//components/crash/core/browser", ] } sources = filenames.lib_sources if (is_win) { sources += filenames.lib_sources_win } if (is_mac) { sources += filenames.lib_sources_mac } if (is_posix) { sources += filenames.lib_sources_posix } if (is_linux) { sources += filenames.lib_sources_linux } if (!is_mac) { sources += filenames.lib_sources_views } if (is_component_build) { defines += [ "NODE_SHARED_MODE" ] } if (enable_fake_location_provider) { sources += [ "shell/browser/fake_location_provider.cc", "shell/browser/fake_location_provider.h", ] } if (is_linux) { deps += [ "//build/config/linux/gtk:gtkprint", "//components/crash/content/browser", ] } if (is_mac) { deps += [ "//components/remote_cocoa/app_shim", "//components/remote_cocoa/browser", "//content/common:mac_helpers", "//ui/accelerated_widget_mac", ] if (!is_mas_build) { deps += [ "//third_party/crashpad/crashpad/client" ] } frameworks = [ "AVFoundation.framework", "Carbon.framework", "LocalAuthentication.framework", "QuartzCore.framework", "Quartz.framework", "Security.framework", "SecurityInterface.framework", "ServiceManagement.framework", "StoreKit.framework", ] sources += [ "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", ] if (is_mas_build) { sources += [ "shell/browser/api/electron_api_app_mas.mm" ] sources -= [ "shell/browser/auto_updater_mac.mm" ] defines += [ "MAS_BUILD" ] sources -= [ "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", ] } else { frameworks += [ "Squirrel.framework", "ReactiveObjC.framework", "Mantle.framework", ] deps += [ "//third_party/squirrel.mac:reactiveobjc_framework+link", "//third_party/squirrel.mac:squirrel_framework+link", ] # ReactiveObjC which is used by Squirrel requires using __weak. cflags_objcc = [ "-fobjc-weak" ] } } if (is_linux) { libs = [ "xshmfence" ] deps += [ ":libnotify_loader", "//build/config/linux/gtk", "//dbus", "//device/bluetooth", "//ui/base/ime/linux", "//ui/events/devices/x11", "//ui/events/platform/x11", "//ui/gtk", "//ui/views/controls/webview", "//ui/wm", ] if (ozone_platform_x11) { sources += filenames.lib_sources_linux_x11 public_deps += [ "//ui/base/x", "//ui/platform_window/x11", ] } configs += [ ":gio_unix" ] defines += [ # Disable warnings for g_settings_list_schemas. "GLIB_DISABLE_DEPRECATION_WARNINGS", "USE_X11=1", ] sources += [ "shell/browser/certificate_manager_model.cc", "shell/browser/certificate_manager_model.h", "shell/browser/ui/gtk/app_indicator_icon.cc", "shell/browser/ui/gtk/app_indicator_icon.h", "shell/browser/ui/gtk/app_indicator_icon_menu.cc", "shell/browser/ui/gtk/app_indicator_icon_menu.h", "shell/browser/ui/gtk/gtk_status_icon.cc", "shell/browser/ui/gtk/gtk_status_icon.h", "shell/browser/ui/gtk/menu_util.cc", "shell/browser/ui/gtk/menu_util.h", "shell/browser/ui/gtk/status_icon.cc", "shell/browser/ui/gtk/status_icon.h", "shell/browser/ui/gtk_util.cc", "shell/browser/ui/gtk_util.h", ] } if (is_win) { libs += [ "dwmapi.lib" ] deps += [ "//components/crash/core/app:crash_export_thunks", "//ui/native_theme:native_theme_browser", "//ui/views/controls/webview", "//ui/wm", "//ui/wm/public", ] public_deps += [ "//sandbox/win:sandbox", "//third_party/crashpad/crashpad/handler", ] } if (enable_plugins) { deps += [ "chromium_src:plugins" ] sources += [ "shell/renderer/pepper_helper.cc", "shell/renderer/pepper_helper.h", ] } if (enable_run_as_node) { sources += [ "shell/app/node_main.cc", "shell/app/node_main.h", ] } if (enable_osr) { sources += [ "shell/browser/osr/osr_host_display_client.cc", "shell/browser/osr/osr_host_display_client.h", "shell/browser/osr/osr_render_widget_host_view.cc", "shell/browser/osr/osr_render_widget_host_view.h", "shell/browser/osr/osr_video_consumer.cc", "shell/browser/osr/osr_video_consumer.h", "shell/browser/osr/osr_view_proxy.cc", "shell/browser/osr/osr_view_proxy.h", "shell/browser/osr/osr_web_contents_view.cc", "shell/browser/osr/osr_web_contents_view.h", ] if (is_mac) { sources += [ "shell/browser/osr/osr_host_display_client_mac.mm", "shell/browser/osr/osr_web_contents_view_mac.mm", ] } deps += [ "//components/viz/service", "//services/viz/public/mojom", "//ui/compositor", ] } if (enable_desktop_capturer) { sources += [ "shell/browser/api/electron_api_desktop_capturer.cc", "shell/browser/api/electron_api_desktop_capturer.h", ] } if (enable_views_api) { sources += [ "shell/browser/api/views/electron_api_image_view.cc", "shell/browser/api/views/electron_api_image_view.h", ] } if (enable_basic_printing) { sources += [ "shell/browser/printing/print_preview_message_handler.cc", "shell/browser/printing/print_preview_message_handler.h", "shell/browser/printing/print_view_manager_electron.cc", "shell/browser/printing/print_view_manager_electron.h", "shell/renderer/printing/print_render_frame_helper_delegate.cc", "shell/renderer/printing/print_render_frame_helper_delegate.h", ] deps += [ "//chrome/services/printing/public/mojom", "//components/printing/common:mojo_interfaces", ] if (is_mac) { deps += [ "//chrome/services/mac_notifications/public/mojom" ] } } if (enable_electron_extensions) { sources += filenames.lib_sources_extensions deps += [ "shell/browser/extensions/api:api_registration", "shell/common/extensions/api", "shell/common/extensions/api:extensions_features", "//chrome/browser/resources:component_extension_resources", "//components/update_client:update_client", "//components/zoom", "//extensions/browser", "//extensions/browser:core_api_provider", "//extensions/browser/updater", "//extensions/common", "//extensions/common:core_api_provider", "//extensions/renderer", ] } if (enable_pdf) { # Printing depends on some //pdf code, so it needs to be built even if the # pdf viewer isn't enabled. deps += [ "//pdf", "//pdf:features", ] } if (enable_pdf_viewer) { deps += [ "//chrome/browser/resources/pdf:resources", "//components/pdf/browser", "//components/pdf/renderer", "//pdf:pdf_ppapi", ] sources += [ "shell/browser/electron_pdf_web_contents_helper_client.cc", "shell/browser/electron_pdf_web_contents_helper_client.h", ] } sources += get_target_outputs(":electron_fuses") if (is_win && enable_win_dark_mode_window_ui) { sources += [ "shell/browser/win/dark_mode.cc", "shell/browser/win/dark_mode.h", ] libs += [ "uxtheme.lib" ] } if (allow_runtime_configurable_key_storage) { defines += [ "ALLOW_RUNTIME_CONFIGURABLE_KEY_STORAGE" ] } } electron_paks("packed_resources") { if (is_mac) { output_dir = "$root_gen_dir/electron_repack" copy_data_to_bundle = true } else { output_dir = root_out_dir } } if (is_mac) { electron_framework_name = "$electron_product_name Framework" electron_helper_name = "$electron_product_name Helper" electron_login_helper_name = "$electron_product_name Login Helper" electron_framework_version = "A" electron_version = read_file("ELECTRON_VERSION", "trim string") mac_xib_bundle_data("electron_xibs") { sources = [ "shell/common/resources/mac/MainMenu.xib" ] } action("fake_v8_context_snapshot_generator") { script = "build/fake_v8_context_snapshot_generator.py" args = [ rebase_path("$root_out_dir/$v8_context_snapshot_filename"), rebase_path("$root_out_dir/fake/$v8_context_snapshot_filename"), ] outputs = [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] } bundle_data("electron_framework_resources") { public_deps = [ ":packed_resources" ] sources = [] if (icu_use_data_file) { sources += [ "$root_out_dir/icudtl.dat" ] public_deps += [ "//third_party/icu:icudata" ] } if (v8_use_external_startup_data) { public_deps += [ "//v8" ] if (use_v8_context_snapshot) { if (use_prebuilt_v8_context_snapshot) { sources += [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] public_deps += [ ":fake_v8_context_snapshot_generator" ] } else { sources += [ "$root_out_dir/$v8_context_snapshot_filename" ] public_deps += [ "//tools/v8_context_snapshot" ] } } else { sources += [ "$root_out_dir/snapshot_blob.bin" ] } } outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } if (!is_component_build && is_component_ffmpeg) { bundle_data("electron_framework_libraries") { sources = [] public_deps = [] sources += [ "$root_out_dir/libffmpeg.dylib" ] public_deps += [ "//third_party/ffmpeg:ffmpeg" ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] } } else { group("electron_framework_libraries") { } } if (use_egl) { # Add the ANGLE .dylibs in the Libraries directory of the Framework. bundle_data("electron_angle_binaries") { sources = [ "$root_out_dir/egl_intermediates/libEGL.dylib", "$root_out_dir/egl_intermediates/libGLESv2.dylib", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:angle_library_copy" ] } # Add the SwiftShader .dylibs in the Libraries directory of the Framework. bundle_data("electron_swiftshader_binaries") { sources = [ "$root_out_dir/egl_intermediates/libswiftshader_libEGL.dylib", "$root_out_dir/egl_intermediates/libswiftshader_libGLESv2.dylib", "$root_out_dir/vk_intermediates/libvk_swiftshader.dylib", "$root_out_dir/vk_intermediates/vk_swiftshader_icd.json", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:swiftshader_egl_library_copy", "//ui/gl:swiftshader_vk_library_copy", ] } } group("electron_angle_library") { if (use_egl) { deps = [ ":electron_angle_binaries" ] } } group("electron_swiftshader_library") { if (use_egl) { deps = [ ":electron_swiftshader_binaries" ] } } bundle_data("electron_crashpad_helper") { sources = [ "$root_out_dir/chrome_crashpad_handler" ] outputs = [ "{{bundle_contents_dir}}/Helpers/{{source_file_part}}" ] public_deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] if (is_asan) { # crashpad_handler requires the ASan runtime at its @executable_path. sources += [ "$root_out_dir/libclang_rt.asan_osx_dynamic.dylib" ] public_deps += [ "//build/config/sanitizers:copy_asan_runtime" ] } } mac_framework_bundle("electron_framework") { output_name = electron_framework_name framework_version = electron_framework_version framework_contents = [ "Resources", "Libraries", ] if (!is_mas_build) { framework_contents += [ "Helpers" ] } public_deps = [ ":electron_framework_libraries", ":electron_lib", ] deps = [ ":electron_angle_library", ":electron_framework_libraries", ":electron_framework_resources", ":electron_swiftshader_library", ":electron_xibs", ] if (!is_mas_build) { deps += [ ":electron_crashpad_helper" ] } info_plist = "shell/common/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.framework", "ELECTRON_VERSION=$electron_version", ] include_dirs = [ "." ] sources = filenames.framework_sources frameworks = [] if (enable_osr) { frameworks += [ "IOSurface.framework" ] } ldflags = [ "-Wl,-install_name,@rpath/$output_name.framework/$output_name", "-rpath", "@loader_path/Libraries", # Required for exporting all symbols of libuv. "-Wl,-force_load,obj/third_party/electron_node/deps/uv/libuv.a", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } template("electron_helper_app") { mac_app_bundle(target_name) { assert(defined(invoker.helper_name_suffix)) output_name = electron_helper_name + invoker.helper_name_suffix deps = [ ":electron_framework+link" ] if (!is_mas_build) { deps += [ "//sandbox/mac:seatbelt" ] } defines = [ "HELPER_EXECUTABLE" ] sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", "shell/common/electron_constants.cc", ] include_dirs = [ "." ] info_plist = "shell/renderer/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.helper" ] ldflags = [ "-rpath", "@executable_path/../../..", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] electron_helper_app("electron_helper_app_${_helper_target}") { helper_name_suffix = _helper_suffix } } template("stripped_framework") { action(target_name) { assert(defined(invoker.framework)) script = "//electron/build/strip_framework.py" forward_variables_from(invoker, [ "deps" ]) inputs = [ "$root_out_dir/" + invoker.framework ] outputs = [ "$target_out_dir/stripped_frameworks/" + invoker.framework ] args = rebase_path(inputs) + rebase_path(outputs) } } stripped_framework("stripped_mantle_framework") { framework = "Mantle.framework" deps = [ "//third_party/squirrel.mac:mantle_framework" ] } stripped_framework("stripped_reactiveobjc_framework") { framework = "ReactiveObjC.framework" deps = [ "//third_party/squirrel.mac:reactiveobjc_framework" ] } stripped_framework("stripped_squirrel_framework") { framework = "Squirrel.framework" deps = [ "//third_party/squirrel.mac:squirrel_framework" ] } bundle_data("electron_app_framework_bundle_data") { sources = [ "$root_out_dir/$electron_framework_name.framework" ] if (!is_mas_build) { sources += get_target_outputs(":stripped_mantle_framework") + get_target_outputs(":stripped_reactiveobjc_framework") + get_target_outputs(":stripped_squirrel_framework") } outputs = [ "{{bundle_contents_dir}}/Frameworks/{{source_file_part}}" ] public_deps = [ ":electron_framework+link", ":stripped_mantle_framework", ":stripped_reactiveobjc_framework", ":stripped_squirrel_framework", ] foreach(helper_params, content_mac_helpers) { sources += [ "$root_out_dir/${electron_helper_name}${helper_params[2]}.app" ] public_deps += [ ":electron_helper_app_${helper_params[0]}" ] } } mac_app_bundle("electron_login_helper") { output_name = electron_login_helper_name sources = filenames.login_helper_sources include_dirs = [ "." ] frameworks = [ "AppKit.framework" ] info_plist = "shell/app/resources/mac/loginhelper-Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.loginhelper" ] } bundle_data("electron_login_helper_app") { public_deps = [ ":electron_login_helper" ] sources = [ "$root_out_dir/$electron_login_helper_name.app" ] outputs = [ "{{bundle_contents_dir}}/Library/LoginItems/{{source_file_part}}" ] } action("electron_app_lproj_dirs") { outputs = [] foreach(locale, locales_as_mac_outputs) { outputs += [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] } script = "build/mac/make_locale_dirs.py" args = rebase_path(outputs) } foreach(locale, locales_as_mac_outputs) { bundle_data("electron_app_strings_${locale}_bundle_data") { sources = [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] outputs = [ "{{bundle_resources_dir}}/$locale.lproj" ] public_deps = [ ":electron_app_lproj_dirs" ] } } group("electron_app_strings_bundle_data") { public_deps = [] foreach(locale, locales_as_mac_outputs) { public_deps += [ ":electron_app_strings_${locale}_bundle_data" ] } } bundle_data("electron_app_resources") { public_deps = [ ":default_app_asar", ":electron_app_strings_bundle_data", ] sources = [ "$root_out_dir/resources/default_app.asar", "shell/browser/resources/mac/electron.icns", ] outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } asar_hashed_info_plist("electron_app_plist") { keys = [ "DEFAULT_APP_ASAR_HEADER_SHA" ] hash_targets = [ ":default_app_asar_header_hash" ] plist_file = "shell/browser/resources/mac/Info.plist" } mac_app_bundle("electron_app") { output_name = electron_product_name sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", "shell/common/electron_constants.cc", ] include_dirs = [ "." ] deps = [ ":electron_app_framework_bundle_data", ":electron_app_plist", ":electron_app_resources", ":electron_fuses", "//electron/buildflags", ] if (is_mas_build) { deps += [ ":electron_login_helper_app" ] } info_plist_target = ":electron_app_plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id", "ELECTRON_VERSION=$electron_version", ] ldflags = [ "-rpath", "@executable_path/../Frameworks", ] } if (enable_dsyms) { extract_symbols("electron_framework_syms") { binary = "$root_out_dir/$electron_framework_name.framework/Versions/$electron_framework_version/$electron_framework_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_framework_name.dSYM/Contents/Resources/DWARF/$electron_framework_name" deps = [ ":electron_framework" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] extract_symbols("electron_helper_syms_${_helper_target}") { binary = "$root_out_dir/$electron_helper_name${_helper_suffix}.app/Contents/MacOS/$electron_helper_name${_helper_suffix}" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_helper_name${_helper_suffix}.dSYM/Contents/Resources/DWARF/$electron_helper_name${_helper_suffix}" deps = [ ":electron_helper_app_${_helper_target}" ] } } extract_symbols("electron_app_syms") { binary = "$root_out_dir/$electron_product_name.app/Contents/MacOS/$electron_product_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_product_name.dSYM/Contents/Resources/DWARF/$electron_product_name" deps = [ ":electron_app" ] } extract_symbols("swiftshader_egl_syms") { binary = "$root_out_dir/libswiftshader_libEGL.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libswiftshader_libEGL.dylib.dSYM/Contents/Resources/DWARF/libswiftshader_libEGL.dylib" deps = [ "//third_party/swiftshader/src/OpenGL/libEGL:swiftshader_libEGL" ] } extract_symbols("swiftshader_gles_syms") { binary = "$root_out_dir/libswiftshader_libGLESv2.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libswiftshader_libGLESv2.dylib.dSYM/Contents/Resources/DWARF/libswiftshader_libGLESv2.dylib" deps = [ "//third_party/swiftshader/src/OpenGL/libGLESv2:swiftshader_libGLESv2", ] } extract_symbols("crashpad_handler_syms") { binary = "$root_out_dir/chrome_crashpad_handler" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/chrome_crashpad_handler.dSYM/Contents/Resources/DWARF/chrome_crashpad_handler" deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] } group("electron_symbols") { deps = [ ":electron_app_syms", ":electron_framework_syms", ":swiftshader_egl_syms", ":swiftshader_gles_syms", ] if (!is_mas_build) { deps += [ ":crashpad_handler_syms" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] deps += [ ":electron_helper_syms_${_helper_target}" ] } } } else { group("electron_symbols") { } } } else { windows_manifest("electron_app_manifest") { sources = [ "shell/browser/resources/win/disable_window_filtering.manifest", "shell/browser/resources/win/dpi_aware.manifest", as_invoker_manifest, common_controls_manifest, default_compatibility_manifest, ] } executable("electron_app") { output_name = electron_project_name if (is_win) { sources = [ "shell/app/electron_main_win.cc" ] } else if (is_linux) { sources = [ "shell/app/electron_main_linux.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", ] } include_dirs = [ "." ] deps = [ ":default_app_asar", ":electron_app_manifest", ":electron_lib", ":packed_resources", "//components/crash/core/app", "//content:sandbox_helper_win", "//electron/buildflags", "//ui/strings", ] data = [] data_deps = [] data += [ "$root_out_dir/resources.pak" ] data += [ "$root_out_dir/chrome_100_percent.pak" ] if (enable_hidpi) { data += [ "$root_out_dir/chrome_200_percent.pak" ] } foreach(locale, locales) { data += [ "$root_out_dir/locales/$locale.pak" ] } if (!is_mac) { data += [ "$root_out_dir/resources/default_app.asar" ] } if (use_v8_context_snapshot) { public_deps = [ "//tools/v8_context_snapshot:v8_context_snapshot" ] } if (is_linux) { data_deps += [ "//components/crash/core/app:chrome_crashpad_handler" ] } if (is_win) { sources += [ # TODO: we should be generating our .rc files more like how chrome does "shell/browser/resources/win/electron.rc", "shell/browser/resources/win/resource.h", ] deps += [ "//components/browser_watcher:browser_watcher_client", "//components/crash/core/app:run_as_crashpad_handler", ] ldflags = [] libs = [ "comctl32.lib", "uiautomationcore.lib", "wtsapi32.lib", ] configs -= [ "//build/config/win:console" ] configs += [ "//build/config/win:windowed", "//build/config/win:delayloads", ] if (current_cpu == "x86") { # Set the initial stack size to 0.5MiB, instead of the 1.5MiB needed by # Chrome's main thread. This saves significant memory on threads (like # those in the Windows thread pool, and others) whose stack size we can # only control through this setting. Because Chrome's main thread needs # a minimum 1.5 MiB stack, the main thread (in 32-bit builds only) uses # fibers to switch to a 1.5 MiB stack before running any other code. ldflags += [ "/STACK:0x80000" ] } else { # Increase the initial stack size. The default is 1MB, this is 8MB. ldflags += [ "/STACK:0x800000" ] } # This is to support renaming of electron.exe. node-gyp has hard-coded # executable names which it will recognise as node. This module definition # file claims that the electron executable is in fact named "node.exe", # which is one of the executable names that node-gyp recognizes. # See https://github.com/nodejs/node-gyp/commit/52ceec3a6d15de3a8f385f43dbe5ecf5456ad07a ldflags += [ "/DEF:" + rebase_path("build/electron.def", root_build_dir) ] inputs = [ "shell/browser/resources/win/electron.ico", "build/electron.def", ] } if (is_linux) { ldflags = [ "-pie", # Required for exporting all symbols of libuv. "-Wl,--whole-archive", "obj/third_party/electron_node/deps/uv/libuv.a", "-Wl,--no-whole-archive", ] if (!is_component_build && is_component_ffmpeg) { configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ] } } } if (is_official_build) { if (is_linux) { _target_executable_suffix = "" _target_shared_library_suffix = ".so" } else if (is_win) { _target_executable_suffix = ".exe" _target_shared_library_suffix = ".dll" } extract_symbols("electron_app_symbols") { binary = "$root_out_dir/$electron_project_name$_target_executable_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ ":electron_app" ] } extract_symbols("swiftshader_egl_symbols") { binary = "$root_out_dir/swiftshader/libEGL$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/swiftshader/src/OpenGL/libEGL:swiftshader_libEGL" ] } extract_symbols("swiftshader_gles_symbols") { binary = "$root_out_dir/swiftshader/libGLESv2$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/swiftshader/src/OpenGL/libGLESv2:swiftshader_libGLESv2", ] } group("electron_symbols") { deps = [ ":electron_app_symbols", ":swiftshader_egl_symbols", ":swiftshader_gles_symbols", ] } } } test("shell_browser_ui_unittests") { sources = [ "//electron/shell/browser/ui/accelerator_util_unittests.cc", "//electron/shell/browser/ui/run_all_unittests.cc", ] configs += [ ":electron_lib_config" ] deps = [ ":electron_lib", "//base", "//base/test:test_support", "//testing/gmock", "//testing/gtest", "//ui/base", "//ui/strings", ] } template("dist_zip") { _runtime_deps_target = "${target_name}__deps" _runtime_deps_file = "$root_out_dir/gen.runtime/" + get_label_info(target_name, "dir") + "/" + get_label_info(target_name, "name") + ".runtime_deps" group(_runtime_deps_target) { forward_variables_from(invoker, [ "deps", "data_deps", "data", "testonly", ]) write_runtime_deps = _runtime_deps_file } action(target_name) { script = "//electron/build/zip.py" deps = [ ":$_runtime_deps_target" ] forward_variables_from(invoker, [ "outputs", "testonly", ]) flatten = false flatten_relative_to = false if (defined(invoker.flatten)) { flatten = invoker.flatten if (defined(invoker.flatten_relative_to)) { flatten_relative_to = invoker.flatten_relative_to } } args = rebase_path(outputs + [ _runtime_deps_file ], root_build_dir) + [ target_cpu, target_os, "$flatten", "$flatten_relative_to", ] } } copy("electron_license") { sources = [ "LICENSE" ] outputs = [ "$root_build_dir/{{source_file_part}}" ] } copy("chromium_licenses") { deps = [ "//components/resources:about_credits" ] sources = [ "$root_gen_dir/components/resources/about_credits.html" ] outputs = [ "$root_build_dir/LICENSES.chromium.html" ] } group("licenses") { data_deps = [ ":chromium_licenses", ":electron_license", ] } copy("electron_version") { sources = [ "ELECTRON_VERSION" ] outputs = [ "$root_build_dir/version" ] } dist_zip("electron_dist_zip") { data_deps = [ ":electron_app", ":electron_version", ":licenses", ] if (is_linux) { data_deps += [ "//sandbox/linux:chrome_sandbox" ] } outputs = [ "$root_build_dir/dist.zip" ] } dist_zip("electron_ffmpeg_zip") { data_deps = [ "//third_party/ffmpeg" ] outputs = [ "$root_build_dir/ffmpeg.zip" ] } electron_chromedriver_deps = [ ":licenses", "//chrome/test/chromedriver", "//electron/buildflags", ] group("electron_chromedriver") { testonly = true public_deps = electron_chromedriver_deps } dist_zip("electron_chromedriver_zip") { testonly = true data_deps = electron_chromedriver_deps outputs = [ "$root_build_dir/chromedriver.zip" ] } mksnapshot_deps = [ ":licenses", "//v8:mksnapshot($v8_snapshot_toolchain)", ] if (use_v8_context_snapshot) { mksnapshot_deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_generator($v8_snapshot_toolchain)" ] } group("electron_mksnapshot") { public_deps = mksnapshot_deps } dist_zip("electron_mksnapshot_zip") { data_deps = mksnapshot_deps outputs = [ "$root_build_dir/mksnapshot.zip" ] } copy("hunspell_dictionaries") { sources = hunspell_dictionaries + hunspell_licenses outputs = [ "$target_gen_dir/electron_hunspell/{{source_file_part}}" ] } dist_zip("hunspell_dictionaries_zip") { data_deps = [ ":hunspell_dictionaries" ] flatten = true outputs = [ "$root_build_dir/hunspell_dictionaries.zip" ] } copy("libcxx_headers") { sources = libcxx_headers + libcxx_licenses + [ "//buildtools/third_party/libc++/__config_site" ] outputs = [ "$target_gen_dir/electron_libcxx_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxx_headers_zip") { data_deps = [ ":libcxx_headers" ] flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxx_include/buildtools/third_party/libc++/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxx_headers.zip" ] } copy("libcxxabi_headers") { sources = libcxxabi_headers + libcxxabi_licenses outputs = [ "$target_gen_dir/electron_libcxxabi_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxxabi_headers_zip") { data_deps = [ ":libcxxabi_headers" ] flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxxabi_include/buildtools/third_party/libc++abi/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxxabi_headers.zip" ] } action("libcxx_objects_zip") { deps = [ "//buildtools/third_party/libc++" ] script = "build/zip_libcxx.py" outputs = [ "$root_build_dir/libcxx_objects.zip" ] args = rebase_path(outputs) } group("electron") { public_deps = [ ":electron_app" ] }
closed
electron/electron
https://github.com/electron/electron
32,455
Update deprecated QuickLook Thumbnailing methods
Nearly all methods we use in `nativeImage.createThumbnailFromPath()` are deprecated on macOS as of 10.15 and scheduled for imminent removal - we should update our usage of those methods to the newer `QuickLookThumbnailing` framework accordingly. See [here](https://developer.apple.com/documentation/quicklook/previews_or_thumbnail_images_for_macos_10_14_or_earlier?language=objc) for deprecation information and [here](https://developer.apple.com/documentation/quicklookthumbnailing?language=objc) for the updated framework we should use.
https://github.com/electron/electron/issues/32455
https://github.com/electron/electron/pull/32456
c3d11e2ea2d9751a457c72805b7688a38ceac30a
4c39eb32b0d2be479b9a0856186c6dfeccae6b96
2022-01-13T13:46:22Z
c++
2022-02-02T22:01:05Z
shell/common/api/electron_api_native_image_mac.mm
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/api/electron_api_native_image.h" #include <string> #include <utility> #include <vector> #import <Cocoa/Cocoa.h> #import <QuickLook/QuickLook.h> #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "gin/arguments.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/promise.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" namespace electron { namespace api { NSData* bufferFromNSImage(NSImage* image) { CGImageRef ref = [image CGImageForProposedRect:nil context:nil hints:nil]; NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCGImage:ref]; [rep setSize:[image size]]; return [rep representationUsingType:NSPNGFileType properties:[[NSDictionary alloc] init]]; } double safeShift(double in, double def) { if (in >= 0 || in <= 1 || in == def) return in; return def; } // static v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath( v8::Isolate* isolate, const base::FilePath& path, const gfx::Size& size) { gin_helper::Promise<gfx::Image> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (size.IsEmpty()) { promise.RejectWithErrorMessage("size must not be empty"); return handle; } CGSize cg_size = size.ToCGSize(); base::ScopedCFTypeRef<CFURLRef> cfurl = base::mac::FilePathToCFURL(path); base::ScopedCFTypeRef<QLThumbnailRef> ql_thumbnail( QLThumbnailCreate(kCFAllocatorDefault, cfurl, cg_size, NULL)); __block gin_helper::Promise<gfx::Image> p = std::move(promise); // we do not want to blocking the main thread while waiting for quicklook to // generate the thumbnail QLThumbnailDispatchAsync( ql_thumbnail, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, /*flags*/ 0), ^{ base::ScopedCFTypeRef<CGImageRef> cg_thumbnail( QLThumbnailCopyImage(ql_thumbnail)); if (cg_thumbnail) { NSImage* result = [[[NSImage alloc] initWithCGImage:cg_thumbnail size:cg_size] autorelease]; gfx::Image thumbnail(result); dispatch_async(dispatch_get_main_queue(), ^{ p.Resolve(thumbnail); }); } else { dispatch_async(dispatch_get_main_queue(), ^{ p.RejectWithErrorMessage("unable to retrieve thumbnail preview " "image for the given path"); }); } }); return handle; } gin::Handle<NativeImage> NativeImage::CreateFromNamedImage(gin::Arguments* args, std::string name) { @autoreleasepool { std::vector<double> hsl_shift; // The string representations of NSImageNames don't match the strings // themselves; they instead follow the following pattern: // * NSImageNameActionTemplate -> "NSActionTemplate" // * NSImageNameMultipleDocuments -> "NSMultipleDocuments" // To account for this, we strip out "ImageName" from the passed string. std::string to_remove("ImageName"); size_t pos = name.find(to_remove); if (pos != std::string::npos) { name.erase(pos, to_remove.length()); } NSImage* image = [NSImage imageNamed:base::SysUTF8ToNSString(name)]; if (!image.valid) { return CreateEmpty(args->isolate()); } NSData* png_data = bufferFromNSImage(image); if (args->GetNext(&hsl_shift) && hsl_shift.size() == 3) { gfx::Image gfx_image = gfx::Image::CreateFrom1xPNGBytes( reinterpret_cast<const unsigned char*>((char*)[png_data bytes]), [png_data length]); color_utils::HSL shift = {safeShift(hsl_shift[0], -1), safeShift(hsl_shift[1], 0.5), safeShift(hsl_shift[2], 0.5)}; png_data = bufferFromNSImage( gfx::Image(gfx::ImageSkiaOperations::CreateHSLShiftedImage( gfx_image.AsImageSkia(), shift)) .AsNSImage()); } return CreateFromPNG(args->isolate(), (char*)[png_data bytes], [png_data length]); } } void NativeImage::SetTemplateImage(bool setAsTemplate) { [image_.AsNSImage() setTemplate:setAsTemplate]; } bool NativeImage::IsTemplateImage() { return [image_.AsNSImage() isTemplate]; } } // namespace api } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,455
Update deprecated QuickLook Thumbnailing methods
Nearly all methods we use in `nativeImage.createThumbnailFromPath()` are deprecated on macOS as of 10.15 and scheduled for imminent removal - we should update our usage of those methods to the newer `QuickLookThumbnailing` framework accordingly. See [here](https://developer.apple.com/documentation/quicklook/previews_or_thumbnail_images_for_macos_10_14_or_earlier?language=objc) for deprecation information and [here](https://developer.apple.com/documentation/quicklookthumbnailing?language=objc) for the updated framework we should use.
https://github.com/electron/electron/issues/32455
https://github.com/electron/electron/pull/32456
c3d11e2ea2d9751a457c72805b7688a38ceac30a
4c39eb32b0d2be479b9a0856186c6dfeccae6b96
2022-01-13T13:46:22Z
c++
2022-02-02T22:01:05Z
BUILD.gn
import("//build/config/locales.gni") import("//build/config/ui.gni") import("//build/config/win/manifest.gni") import("//components/os_crypt/features.gni") import("//components/spellcheck/spellcheck_build_features.gni") import("//content/public/app/mac_helpers.gni") import("//extensions/buildflags/buildflags.gni") import("//pdf/features.gni") import("//ppapi/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//testing/test.gni") import("//third_party/ffmpeg/ffmpeg_options.gni") import("//tools/generate_library_loader/generate_library_loader.gni") import("//tools/grit/grit_rule.gni") import("//tools/grit/repack.gni") import("//tools/v8_context_snapshot/v8_context_snapshot.gni") import("//v8/gni/snapshot_toolchain.gni") import("build/asar.gni") import("build/extract_symbols.gni") import("build/npm.gni") import("build/templated_file.gni") import("build/tsc.gni") import("build/webpack/webpack.gni") import("buildflags/buildflags.gni") import("electron_paks.gni") import("filenames.auto.gni") import("filenames.gni") import("filenames.hunspell.gni") import("filenames.libcxx.gni") import("filenames.libcxxabi.gni") if (is_mac) { import("//build/config/mac/rules.gni") import("//third_party/icu/config.gni") import("//ui/gl/features.gni") import("//v8/gni/v8.gni") import("build/rules.gni") assert( mac_deployment_target == "10.11.0", "Chromium has updated the mac_deployment_target, please update this assert, update the supported versions documentation (docs/tutorial/support.md) and flag this as a breaking change") } if (is_linux) { import("//build/config/linux/pkg_config.gni") pkg_config("gio_unix") { packages = [ "gio-unix-2.0" ] } pkg_config("libnotify_config") { packages = [ "glib-2.0", "gdk-pixbuf-2.0", ] } } declare_args() { use_prebuilt_v8_context_snapshot = false } branding = read_file("shell/app/BRANDING.json", "json") electron_project_name = branding.project_name electron_product_name = branding.product_name electron_mac_bundle_id = branding.mac_bundle_id if (is_mas_build) { assert(is_mac, "It doesn't make sense to build a MAS build on a non-mac platform") } if (enable_pdf_viewer) { assert(enable_pdf, "PDF viewer support requires enable_pdf=true") assert(enable_electron_extensions, "PDF viewer support requires enable_electron_extensions=true") } if (enable_electron_extensions) { assert(enable_extensions, "Chrome extension support requires enable_extensions=true") } config("branding") { defines = [ "ELECTRON_PRODUCT_NAME=\"$electron_product_name\"", "ELECTRON_PROJECT_NAME=\"$electron_project_name\"", ] } config("electron_lib_config") { include_dirs = [ "." ] } # We geneate the definitions twice here, once in //electron/electron.d.ts # and once in $target_gen_dir # The one in $target_gen_dir is used for the actual TSC build later one # and the one in //electron/electron.d.ts is used by your IDE (vscode) # for typescript prompting npm_action("build_electron_definitions") { script = "gn-typescript-definitions" args = [ rebase_path("$target_gen_dir/tsc/typings/electron.d.ts") ] inputs = auto_filenames.api_docs + [ "yarn.lock" ] outputs = [ "$target_gen_dir/tsc/typings/electron.d.ts" ] } webpack_build("electron_asar_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.asar_bundle_deps config_file = "//electron/build/webpack/webpack.config.asar.js" out_file = "$target_gen_dir/js2c/asar_bundle.js" } webpack_build("electron_browser_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.browser_bundle_deps config_file = "//electron/build/webpack/webpack.config.browser.js" out_file = "$target_gen_dir/js2c/browser_init.js" } webpack_build("electron_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.renderer_bundle_deps config_file = "//electron/build/webpack/webpack.config.renderer.js" out_file = "$target_gen_dir/js2c/renderer_init.js" } webpack_build("electron_worker_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.worker_bundle_deps config_file = "//electron/build/webpack/webpack.config.worker.js" out_file = "$target_gen_dir/js2c/worker_init.js" } webpack_build("electron_sandboxed_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.sandbox_bundle_deps config_file = "//electron/build/webpack/webpack.config.sandboxed_renderer.js" out_file = "$target_gen_dir/js2c/sandbox_bundle.js" } webpack_build("electron_isolated_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.isolated_bundle_deps config_file = "//electron/build/webpack/webpack.config.isolated_renderer.js" out_file = "$target_gen_dir/js2c/isolated_bundle.js" } action("electron_js2c") { deps = [ ":electron_asar_bundle", ":electron_browser_bundle", ":electron_isolated_renderer_bundle", ":electron_renderer_bundle", ":electron_sandboxed_renderer_bundle", ":electron_worker_bundle", ] sources = [ "$target_gen_dir/js2c/asar_bundle.js", "$target_gen_dir/js2c/browser_init.js", "$target_gen_dir/js2c/isolated_bundle.js", "$target_gen_dir/js2c/renderer_init.js", "$target_gen_dir/js2c/sandbox_bundle.js", "$target_gen_dir/js2c/worker_init.js", ] inputs = sources + [ "//third_party/electron_node/tools/js2c.py" ] outputs = [ "$root_gen_dir/electron_natives.cc" ] script = "build/js2c.py" args = [ rebase_path("//third_party/electron_node") ] + rebase_path(outputs, root_build_dir) + rebase_path(sources, root_build_dir) } action("generate_config_gypi") { outputs = [ "$root_gen_dir/config.gypi" ] script = "script/generate-config-gypi.py" args = rebase_path(outputs) + [ target_cpu ] } target_gen_default_app_js = "$target_gen_dir/js/default_app" typescript_build("default_app_js") { deps = [ ":build_electron_definitions" ] sources = filenames.default_app_ts_sources output_gen_dir = target_gen_default_app_js output_dir_name = "default_app" tsconfig = "tsconfig.default_app.json" } copy("default_app_static") { sources = filenames.default_app_static_sources outputs = [ "$target_gen_default_app_js/{{source}}" ] } copy("default_app_octicon_deps") { sources = filenames.default_app_octicon_sources outputs = [ "$target_gen_default_app_js/electron/default_app/octicon/{{source_file_part}}" ] } asar("default_app_asar") { deps = [ ":default_app_js", ":default_app_octicon_deps", ":default_app_static", ] root = "$target_gen_default_app_js/electron/default_app" sources = get_target_outputs(":default_app_js") + get_target_outputs(":default_app_static") + get_target_outputs(":default_app_octicon_deps") outputs = [ "$root_out_dir/resources/default_app.asar" ] } grit("resources") { source = "electron_resources.grd" outputs = [ "grit/electron_resources.h", "electron_resources.pak", ] # Mojo manifest overlays are generated. grit_flags = [ "-E", "target_gen_dir=" + rebase_path(target_gen_dir, root_build_dir), ] deps = [ ":copy_shell_devtools_discovery_page" ] output_dir = "$target_gen_dir" } copy("copy_shell_devtools_discovery_page") { sources = [ "//content/shell/resources/shell_devtools_discovery_page.html" ] outputs = [ "$target_gen_dir/shell_devtools_discovery_page.html" ] } if (is_linux) { generate_library_loader("libnotify_loader") { name = "LibNotifyLoader" output_h = "libnotify_loader.h" output_cc = "libnotify_loader.cc" header = "<libnotify/notify.h>" config = ":libnotify_config" functions = [ "notify_is_initted", "notify_init", "notify_get_server_caps", "notify_get_server_info", "notify_notification_new", "notify_notification_add_action", "notify_notification_set_image_from_pixbuf", "notify_notification_set_timeout", "notify_notification_set_urgency", "notify_notification_set_hint_string", "notify_notification_show", "notify_notification_close", ] } } npm_action("electron_version_args") { script = "generate-version-json" outputs = [ "$target_gen_dir/electron_version.args" ] args = rebase_path(outputs) inputs = [ "ELECTRON_VERSION", "script/generate-version-json.js", ] } templated_file("electron_version_header") { deps = [ ":electron_version_args" ] template = "build/templates/electron_version.tmpl" output = "$target_gen_dir/electron_version.h" args_files = get_target_outputs(":electron_version_args") } action("electron_fuses") { script = "build/fuses/build.py" inputs = [ "build/fuses/fuses.json5" ] outputs = [ "$target_gen_dir/fuses.h", "$target_gen_dir/fuses.cc", ] args = rebase_path(outputs) } action("electron_generate_node_defines") { script = "build/generate_node_defines.py" inputs = [ "//third_party/electron_node/src/tracing/trace_event_common.h", "//third_party/electron_node/src/tracing/trace_event.h", "//third_party/electron_node/src/util.h", ] outputs = [ "$target_gen_dir/push_and_undef_node_defines.h", "$target_gen_dir/pop_node_defines.h", ] args = [ rebase_path(target_gen_dir) ] + rebase_path(inputs) } source_set("electron_lib") { configs += [ "//v8:external_startup_data" ] configs += [ "//third_party/electron_node:node_internals" ] public_configs = [ ":branding", ":electron_lib_config", ] deps = [ ":electron_fuses", ":electron_generate_node_defines", ":electron_js2c", ":electron_version_header", ":resources", "buildflags", "chromium_src:chrome", "chromium_src:chrome_spellchecker", "shell/common/api:mojo", "//base:base_static", "//base/allocator:buildflags", "//chrome/app:command_ids", "//chrome/app/resources:platform_locale_settings", "//components/autofill/core/common:features", "//components/certificate_transparency", "//components/language/core/browser", "//components/net_log", "//components/network_hints/browser", "//components/network_hints/common:mojo_bindings", "//components/network_hints/renderer", "//components/network_session_configurator/common", "//components/os_crypt", "//components/pref_registry", "//components/prefs", "//components/security_state/content", "//components/upload_list", "//components/user_prefs", "//components/viz/host", "//components/viz/service", "//content/public/browser", "//content/public/child", "//content/public/gpu", "//content/public/renderer", "//content/public/utility", "//device/bluetooth", "//device/bluetooth/public/cpp", "//gin", "//media/capture/mojom:video_capture", "//media/mojo/mojom", "//net:extras", "//net:net_resources", "//ppapi/host", "//ppapi/proxy", "//ppapi/shared_impl", "//printing/buildflags", "//services/device/public/cpp/geolocation", "//services/device/public/cpp/hid", "//services/device/public/mojom", "//services/proxy_resolver:lib", "//services/video_capture/public/mojom:constants", "//services/viz/privileged/mojom/compositing", "//skia", "//third_party/blink/public:blink", "//third_party/blink/public:blink_devtools_inspector_resources", "//third_party/blink/public/platform/media", "//third_party/boringssl", "//third_party/electron_node:node_lib", "//third_party/inspector_protocol:crdtp", "//third_party/leveldatabase", "//third_party/libyuv", "//third_party/webrtc_overrides:webrtc_component", "//third_party/widevine/cdm:headers", "//third_party/zlib/google:zip", "//ui/base/idle", "//ui/events:dom_keycode_converter", "//ui/gl", "//ui/native_theme", "//ui/shell_dialogs", "//ui/views", "//v8", "//v8:v8_libplatform", ] public_deps = [ "//base", "//base:i18n", "//content/public/app", ] include_dirs = [ ".", "$target_gen_dir", # TODO(nornagon): replace usage of SchemeRegistry by an actually exported # API of blink, then remove this from the include_dirs. "//third_party/blink/renderer", ] defines = [ "V8_DEPRECATION_WARNINGS" ] libs = [] if (is_linux) { defines += [ "GDK_DISABLE_DEPRECATION_WARNINGS" ] } if (!is_mas_build) { deps += [ "//components/crash/core/app", "//components/crash/core/browser", ] } sources = filenames.lib_sources if (is_win) { sources += filenames.lib_sources_win } if (is_mac) { sources += filenames.lib_sources_mac } if (is_posix) { sources += filenames.lib_sources_posix } if (is_linux) { sources += filenames.lib_sources_linux } if (!is_mac) { sources += filenames.lib_sources_views } if (is_component_build) { defines += [ "NODE_SHARED_MODE" ] } if (enable_fake_location_provider) { sources += [ "shell/browser/fake_location_provider.cc", "shell/browser/fake_location_provider.h", ] } if (is_linux) { deps += [ "//build/config/linux/gtk:gtkprint", "//components/crash/content/browser", ] } if (is_mac) { deps += [ "//components/remote_cocoa/app_shim", "//components/remote_cocoa/browser", "//content/common:mac_helpers", "//ui/accelerated_widget_mac", ] if (!is_mas_build) { deps += [ "//third_party/crashpad/crashpad/client" ] } frameworks = [ "AVFoundation.framework", "Carbon.framework", "LocalAuthentication.framework", "QuartzCore.framework", "Quartz.framework", "Security.framework", "SecurityInterface.framework", "ServiceManagement.framework", "StoreKit.framework", ] sources += [ "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", ] if (is_mas_build) { sources += [ "shell/browser/api/electron_api_app_mas.mm" ] sources -= [ "shell/browser/auto_updater_mac.mm" ] defines += [ "MAS_BUILD" ] sources -= [ "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", ] } else { frameworks += [ "Squirrel.framework", "ReactiveObjC.framework", "Mantle.framework", ] deps += [ "//third_party/squirrel.mac:reactiveobjc_framework+link", "//third_party/squirrel.mac:squirrel_framework+link", ] # ReactiveObjC which is used by Squirrel requires using __weak. cflags_objcc = [ "-fobjc-weak" ] } } if (is_linux) { libs = [ "xshmfence" ] deps += [ ":libnotify_loader", "//build/config/linux/gtk", "//dbus", "//device/bluetooth", "//ui/base/ime/linux", "//ui/events/devices/x11", "//ui/events/platform/x11", "//ui/gtk", "//ui/views/controls/webview", "//ui/wm", ] if (ozone_platform_x11) { sources += filenames.lib_sources_linux_x11 public_deps += [ "//ui/base/x", "//ui/platform_window/x11", ] } configs += [ ":gio_unix" ] defines += [ # Disable warnings for g_settings_list_schemas. "GLIB_DISABLE_DEPRECATION_WARNINGS", "USE_X11=1", ] sources += [ "shell/browser/certificate_manager_model.cc", "shell/browser/certificate_manager_model.h", "shell/browser/ui/gtk/app_indicator_icon.cc", "shell/browser/ui/gtk/app_indicator_icon.h", "shell/browser/ui/gtk/app_indicator_icon_menu.cc", "shell/browser/ui/gtk/app_indicator_icon_menu.h", "shell/browser/ui/gtk/gtk_status_icon.cc", "shell/browser/ui/gtk/gtk_status_icon.h", "shell/browser/ui/gtk/menu_util.cc", "shell/browser/ui/gtk/menu_util.h", "shell/browser/ui/gtk/status_icon.cc", "shell/browser/ui/gtk/status_icon.h", "shell/browser/ui/gtk_util.cc", "shell/browser/ui/gtk_util.h", ] } if (is_win) { libs += [ "dwmapi.lib" ] deps += [ "//components/crash/core/app:crash_export_thunks", "//ui/native_theme:native_theme_browser", "//ui/views/controls/webview", "//ui/wm", "//ui/wm/public", ] public_deps += [ "//sandbox/win:sandbox", "//third_party/crashpad/crashpad/handler", ] } if (enable_plugins) { deps += [ "chromium_src:plugins" ] sources += [ "shell/renderer/pepper_helper.cc", "shell/renderer/pepper_helper.h", ] } if (enable_run_as_node) { sources += [ "shell/app/node_main.cc", "shell/app/node_main.h", ] } if (enable_osr) { sources += [ "shell/browser/osr/osr_host_display_client.cc", "shell/browser/osr/osr_host_display_client.h", "shell/browser/osr/osr_render_widget_host_view.cc", "shell/browser/osr/osr_render_widget_host_view.h", "shell/browser/osr/osr_video_consumer.cc", "shell/browser/osr/osr_video_consumer.h", "shell/browser/osr/osr_view_proxy.cc", "shell/browser/osr/osr_view_proxy.h", "shell/browser/osr/osr_web_contents_view.cc", "shell/browser/osr/osr_web_contents_view.h", ] if (is_mac) { sources += [ "shell/browser/osr/osr_host_display_client_mac.mm", "shell/browser/osr/osr_web_contents_view_mac.mm", ] } deps += [ "//components/viz/service", "//services/viz/public/mojom", "//ui/compositor", ] } if (enable_desktop_capturer) { sources += [ "shell/browser/api/electron_api_desktop_capturer.cc", "shell/browser/api/electron_api_desktop_capturer.h", ] } if (enable_views_api) { sources += [ "shell/browser/api/views/electron_api_image_view.cc", "shell/browser/api/views/electron_api_image_view.h", ] } if (enable_basic_printing) { sources += [ "shell/browser/printing/print_preview_message_handler.cc", "shell/browser/printing/print_preview_message_handler.h", "shell/browser/printing/print_view_manager_electron.cc", "shell/browser/printing/print_view_manager_electron.h", "shell/renderer/printing/print_render_frame_helper_delegate.cc", "shell/renderer/printing/print_render_frame_helper_delegate.h", ] deps += [ "//chrome/services/printing/public/mojom", "//components/printing/common:mojo_interfaces", ] if (is_mac) { deps += [ "//chrome/services/mac_notifications/public/mojom" ] } } if (enable_electron_extensions) { sources += filenames.lib_sources_extensions deps += [ "shell/browser/extensions/api:api_registration", "shell/common/extensions/api", "shell/common/extensions/api:extensions_features", "//chrome/browser/resources:component_extension_resources", "//components/update_client:update_client", "//components/zoom", "//extensions/browser", "//extensions/browser:core_api_provider", "//extensions/browser/updater", "//extensions/common", "//extensions/common:core_api_provider", "//extensions/renderer", ] } if (enable_pdf) { # Printing depends on some //pdf code, so it needs to be built even if the # pdf viewer isn't enabled. deps += [ "//pdf", "//pdf:features", ] } if (enable_pdf_viewer) { deps += [ "//chrome/browser/resources/pdf:resources", "//components/pdf/browser", "//components/pdf/renderer", "//pdf:pdf_ppapi", ] sources += [ "shell/browser/electron_pdf_web_contents_helper_client.cc", "shell/browser/electron_pdf_web_contents_helper_client.h", ] } sources += get_target_outputs(":electron_fuses") if (is_win && enable_win_dark_mode_window_ui) { sources += [ "shell/browser/win/dark_mode.cc", "shell/browser/win/dark_mode.h", ] libs += [ "uxtheme.lib" ] } if (allow_runtime_configurable_key_storage) { defines += [ "ALLOW_RUNTIME_CONFIGURABLE_KEY_STORAGE" ] } } electron_paks("packed_resources") { if (is_mac) { output_dir = "$root_gen_dir/electron_repack" copy_data_to_bundle = true } else { output_dir = root_out_dir } } if (is_mac) { electron_framework_name = "$electron_product_name Framework" electron_helper_name = "$electron_product_name Helper" electron_login_helper_name = "$electron_product_name Login Helper" electron_framework_version = "A" electron_version = read_file("ELECTRON_VERSION", "trim string") mac_xib_bundle_data("electron_xibs") { sources = [ "shell/common/resources/mac/MainMenu.xib" ] } action("fake_v8_context_snapshot_generator") { script = "build/fake_v8_context_snapshot_generator.py" args = [ rebase_path("$root_out_dir/$v8_context_snapshot_filename"), rebase_path("$root_out_dir/fake/$v8_context_snapshot_filename"), ] outputs = [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] } bundle_data("electron_framework_resources") { public_deps = [ ":packed_resources" ] sources = [] if (icu_use_data_file) { sources += [ "$root_out_dir/icudtl.dat" ] public_deps += [ "//third_party/icu:icudata" ] } if (v8_use_external_startup_data) { public_deps += [ "//v8" ] if (use_v8_context_snapshot) { if (use_prebuilt_v8_context_snapshot) { sources += [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] public_deps += [ ":fake_v8_context_snapshot_generator" ] } else { sources += [ "$root_out_dir/$v8_context_snapshot_filename" ] public_deps += [ "//tools/v8_context_snapshot" ] } } else { sources += [ "$root_out_dir/snapshot_blob.bin" ] } } outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } if (!is_component_build && is_component_ffmpeg) { bundle_data("electron_framework_libraries") { sources = [] public_deps = [] sources += [ "$root_out_dir/libffmpeg.dylib" ] public_deps += [ "//third_party/ffmpeg:ffmpeg" ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] } } else { group("electron_framework_libraries") { } } if (use_egl) { # Add the ANGLE .dylibs in the Libraries directory of the Framework. bundle_data("electron_angle_binaries") { sources = [ "$root_out_dir/egl_intermediates/libEGL.dylib", "$root_out_dir/egl_intermediates/libGLESv2.dylib", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:angle_library_copy" ] } # Add the SwiftShader .dylibs in the Libraries directory of the Framework. bundle_data("electron_swiftshader_binaries") { sources = [ "$root_out_dir/egl_intermediates/libswiftshader_libEGL.dylib", "$root_out_dir/egl_intermediates/libswiftshader_libGLESv2.dylib", "$root_out_dir/vk_intermediates/libvk_swiftshader.dylib", "$root_out_dir/vk_intermediates/vk_swiftshader_icd.json", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:swiftshader_egl_library_copy", "//ui/gl:swiftshader_vk_library_copy", ] } } group("electron_angle_library") { if (use_egl) { deps = [ ":electron_angle_binaries" ] } } group("electron_swiftshader_library") { if (use_egl) { deps = [ ":electron_swiftshader_binaries" ] } } bundle_data("electron_crashpad_helper") { sources = [ "$root_out_dir/chrome_crashpad_handler" ] outputs = [ "{{bundle_contents_dir}}/Helpers/{{source_file_part}}" ] public_deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] if (is_asan) { # crashpad_handler requires the ASan runtime at its @executable_path. sources += [ "$root_out_dir/libclang_rt.asan_osx_dynamic.dylib" ] public_deps += [ "//build/config/sanitizers:copy_asan_runtime" ] } } mac_framework_bundle("electron_framework") { output_name = electron_framework_name framework_version = electron_framework_version framework_contents = [ "Resources", "Libraries", ] if (!is_mas_build) { framework_contents += [ "Helpers" ] } public_deps = [ ":electron_framework_libraries", ":electron_lib", ] deps = [ ":electron_angle_library", ":electron_framework_libraries", ":electron_framework_resources", ":electron_swiftshader_library", ":electron_xibs", ] if (!is_mas_build) { deps += [ ":electron_crashpad_helper" ] } info_plist = "shell/common/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.framework", "ELECTRON_VERSION=$electron_version", ] include_dirs = [ "." ] sources = filenames.framework_sources frameworks = [] if (enable_osr) { frameworks += [ "IOSurface.framework" ] } ldflags = [ "-Wl,-install_name,@rpath/$output_name.framework/$output_name", "-rpath", "@loader_path/Libraries", # Required for exporting all symbols of libuv. "-Wl,-force_load,obj/third_party/electron_node/deps/uv/libuv.a", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } template("electron_helper_app") { mac_app_bundle(target_name) { assert(defined(invoker.helper_name_suffix)) output_name = electron_helper_name + invoker.helper_name_suffix deps = [ ":electron_framework+link" ] if (!is_mas_build) { deps += [ "//sandbox/mac:seatbelt" ] } defines = [ "HELPER_EXECUTABLE" ] sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", "shell/common/electron_constants.cc", ] include_dirs = [ "." ] info_plist = "shell/renderer/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.helper" ] ldflags = [ "-rpath", "@executable_path/../../..", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] electron_helper_app("electron_helper_app_${_helper_target}") { helper_name_suffix = _helper_suffix } } template("stripped_framework") { action(target_name) { assert(defined(invoker.framework)) script = "//electron/build/strip_framework.py" forward_variables_from(invoker, [ "deps" ]) inputs = [ "$root_out_dir/" + invoker.framework ] outputs = [ "$target_out_dir/stripped_frameworks/" + invoker.framework ] args = rebase_path(inputs) + rebase_path(outputs) } } stripped_framework("stripped_mantle_framework") { framework = "Mantle.framework" deps = [ "//third_party/squirrel.mac:mantle_framework" ] } stripped_framework("stripped_reactiveobjc_framework") { framework = "ReactiveObjC.framework" deps = [ "//third_party/squirrel.mac:reactiveobjc_framework" ] } stripped_framework("stripped_squirrel_framework") { framework = "Squirrel.framework" deps = [ "//third_party/squirrel.mac:squirrel_framework" ] } bundle_data("electron_app_framework_bundle_data") { sources = [ "$root_out_dir/$electron_framework_name.framework" ] if (!is_mas_build) { sources += get_target_outputs(":stripped_mantle_framework") + get_target_outputs(":stripped_reactiveobjc_framework") + get_target_outputs(":stripped_squirrel_framework") } outputs = [ "{{bundle_contents_dir}}/Frameworks/{{source_file_part}}" ] public_deps = [ ":electron_framework+link", ":stripped_mantle_framework", ":stripped_reactiveobjc_framework", ":stripped_squirrel_framework", ] foreach(helper_params, content_mac_helpers) { sources += [ "$root_out_dir/${electron_helper_name}${helper_params[2]}.app" ] public_deps += [ ":electron_helper_app_${helper_params[0]}" ] } } mac_app_bundle("electron_login_helper") { output_name = electron_login_helper_name sources = filenames.login_helper_sources include_dirs = [ "." ] frameworks = [ "AppKit.framework" ] info_plist = "shell/app/resources/mac/loginhelper-Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.loginhelper" ] } bundle_data("electron_login_helper_app") { public_deps = [ ":electron_login_helper" ] sources = [ "$root_out_dir/$electron_login_helper_name.app" ] outputs = [ "{{bundle_contents_dir}}/Library/LoginItems/{{source_file_part}}" ] } action("electron_app_lproj_dirs") { outputs = [] foreach(locale, locales_as_mac_outputs) { outputs += [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] } script = "build/mac/make_locale_dirs.py" args = rebase_path(outputs) } foreach(locale, locales_as_mac_outputs) { bundle_data("electron_app_strings_${locale}_bundle_data") { sources = [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] outputs = [ "{{bundle_resources_dir}}/$locale.lproj" ] public_deps = [ ":electron_app_lproj_dirs" ] } } group("electron_app_strings_bundle_data") { public_deps = [] foreach(locale, locales_as_mac_outputs) { public_deps += [ ":electron_app_strings_${locale}_bundle_data" ] } } bundle_data("electron_app_resources") { public_deps = [ ":default_app_asar", ":electron_app_strings_bundle_data", ] sources = [ "$root_out_dir/resources/default_app.asar", "shell/browser/resources/mac/electron.icns", ] outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } asar_hashed_info_plist("electron_app_plist") { keys = [ "DEFAULT_APP_ASAR_HEADER_SHA" ] hash_targets = [ ":default_app_asar_header_hash" ] plist_file = "shell/browser/resources/mac/Info.plist" } mac_app_bundle("electron_app") { output_name = electron_product_name sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", "shell/common/electron_constants.cc", ] include_dirs = [ "." ] deps = [ ":electron_app_framework_bundle_data", ":electron_app_plist", ":electron_app_resources", ":electron_fuses", "//electron/buildflags", ] if (is_mas_build) { deps += [ ":electron_login_helper_app" ] } info_plist_target = ":electron_app_plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id", "ELECTRON_VERSION=$electron_version", ] ldflags = [ "-rpath", "@executable_path/../Frameworks", ] } if (enable_dsyms) { extract_symbols("electron_framework_syms") { binary = "$root_out_dir/$electron_framework_name.framework/Versions/$electron_framework_version/$electron_framework_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_framework_name.dSYM/Contents/Resources/DWARF/$electron_framework_name" deps = [ ":electron_framework" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] extract_symbols("electron_helper_syms_${_helper_target}") { binary = "$root_out_dir/$electron_helper_name${_helper_suffix}.app/Contents/MacOS/$electron_helper_name${_helper_suffix}" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_helper_name${_helper_suffix}.dSYM/Contents/Resources/DWARF/$electron_helper_name${_helper_suffix}" deps = [ ":electron_helper_app_${_helper_target}" ] } } extract_symbols("electron_app_syms") { binary = "$root_out_dir/$electron_product_name.app/Contents/MacOS/$electron_product_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_product_name.dSYM/Contents/Resources/DWARF/$electron_product_name" deps = [ ":electron_app" ] } extract_symbols("swiftshader_egl_syms") { binary = "$root_out_dir/libswiftshader_libEGL.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libswiftshader_libEGL.dylib.dSYM/Contents/Resources/DWARF/libswiftshader_libEGL.dylib" deps = [ "//third_party/swiftshader/src/OpenGL/libEGL:swiftshader_libEGL" ] } extract_symbols("swiftshader_gles_syms") { binary = "$root_out_dir/libswiftshader_libGLESv2.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libswiftshader_libGLESv2.dylib.dSYM/Contents/Resources/DWARF/libswiftshader_libGLESv2.dylib" deps = [ "//third_party/swiftshader/src/OpenGL/libGLESv2:swiftshader_libGLESv2", ] } extract_symbols("crashpad_handler_syms") { binary = "$root_out_dir/chrome_crashpad_handler" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/chrome_crashpad_handler.dSYM/Contents/Resources/DWARF/chrome_crashpad_handler" deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] } group("electron_symbols") { deps = [ ":electron_app_syms", ":electron_framework_syms", ":swiftshader_egl_syms", ":swiftshader_gles_syms", ] if (!is_mas_build) { deps += [ ":crashpad_handler_syms" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] deps += [ ":electron_helper_syms_${_helper_target}" ] } } } else { group("electron_symbols") { } } } else { windows_manifest("electron_app_manifest") { sources = [ "shell/browser/resources/win/disable_window_filtering.manifest", "shell/browser/resources/win/dpi_aware.manifest", as_invoker_manifest, common_controls_manifest, default_compatibility_manifest, ] } executable("electron_app") { output_name = electron_project_name if (is_win) { sources = [ "shell/app/electron_main_win.cc" ] } else if (is_linux) { sources = [ "shell/app/electron_main_linux.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", ] } include_dirs = [ "." ] deps = [ ":default_app_asar", ":electron_app_manifest", ":electron_lib", ":packed_resources", "//components/crash/core/app", "//content:sandbox_helper_win", "//electron/buildflags", "//ui/strings", ] data = [] data_deps = [] data += [ "$root_out_dir/resources.pak" ] data += [ "$root_out_dir/chrome_100_percent.pak" ] if (enable_hidpi) { data += [ "$root_out_dir/chrome_200_percent.pak" ] } foreach(locale, locales) { data += [ "$root_out_dir/locales/$locale.pak" ] } if (!is_mac) { data += [ "$root_out_dir/resources/default_app.asar" ] } if (use_v8_context_snapshot) { public_deps = [ "//tools/v8_context_snapshot:v8_context_snapshot" ] } if (is_linux) { data_deps += [ "//components/crash/core/app:chrome_crashpad_handler" ] } if (is_win) { sources += [ # TODO: we should be generating our .rc files more like how chrome does "shell/browser/resources/win/electron.rc", "shell/browser/resources/win/resource.h", ] deps += [ "//components/browser_watcher:browser_watcher_client", "//components/crash/core/app:run_as_crashpad_handler", ] ldflags = [] libs = [ "comctl32.lib", "uiautomationcore.lib", "wtsapi32.lib", ] configs -= [ "//build/config/win:console" ] configs += [ "//build/config/win:windowed", "//build/config/win:delayloads", ] if (current_cpu == "x86") { # Set the initial stack size to 0.5MiB, instead of the 1.5MiB needed by # Chrome's main thread. This saves significant memory on threads (like # those in the Windows thread pool, and others) whose stack size we can # only control through this setting. Because Chrome's main thread needs # a minimum 1.5 MiB stack, the main thread (in 32-bit builds only) uses # fibers to switch to a 1.5 MiB stack before running any other code. ldflags += [ "/STACK:0x80000" ] } else { # Increase the initial stack size. The default is 1MB, this is 8MB. ldflags += [ "/STACK:0x800000" ] } # This is to support renaming of electron.exe. node-gyp has hard-coded # executable names which it will recognise as node. This module definition # file claims that the electron executable is in fact named "node.exe", # which is one of the executable names that node-gyp recognizes. # See https://github.com/nodejs/node-gyp/commit/52ceec3a6d15de3a8f385f43dbe5ecf5456ad07a ldflags += [ "/DEF:" + rebase_path("build/electron.def", root_build_dir) ] inputs = [ "shell/browser/resources/win/electron.ico", "build/electron.def", ] } if (is_linux) { ldflags = [ "-pie", # Required for exporting all symbols of libuv. "-Wl,--whole-archive", "obj/third_party/electron_node/deps/uv/libuv.a", "-Wl,--no-whole-archive", ] if (!is_component_build && is_component_ffmpeg) { configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ] } } } if (is_official_build) { if (is_linux) { _target_executable_suffix = "" _target_shared_library_suffix = ".so" } else if (is_win) { _target_executable_suffix = ".exe" _target_shared_library_suffix = ".dll" } extract_symbols("electron_app_symbols") { binary = "$root_out_dir/$electron_project_name$_target_executable_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ ":electron_app" ] } extract_symbols("swiftshader_egl_symbols") { binary = "$root_out_dir/swiftshader/libEGL$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/swiftshader/src/OpenGL/libEGL:swiftshader_libEGL" ] } extract_symbols("swiftshader_gles_symbols") { binary = "$root_out_dir/swiftshader/libGLESv2$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/swiftshader/src/OpenGL/libGLESv2:swiftshader_libGLESv2", ] } group("electron_symbols") { deps = [ ":electron_app_symbols", ":swiftshader_egl_symbols", ":swiftshader_gles_symbols", ] } } } test("shell_browser_ui_unittests") { sources = [ "//electron/shell/browser/ui/accelerator_util_unittests.cc", "//electron/shell/browser/ui/run_all_unittests.cc", ] configs += [ ":electron_lib_config" ] deps = [ ":electron_lib", "//base", "//base/test:test_support", "//testing/gmock", "//testing/gtest", "//ui/base", "//ui/strings", ] } template("dist_zip") { _runtime_deps_target = "${target_name}__deps" _runtime_deps_file = "$root_out_dir/gen.runtime/" + get_label_info(target_name, "dir") + "/" + get_label_info(target_name, "name") + ".runtime_deps" group(_runtime_deps_target) { forward_variables_from(invoker, [ "deps", "data_deps", "data", "testonly", ]) write_runtime_deps = _runtime_deps_file } action(target_name) { script = "//electron/build/zip.py" deps = [ ":$_runtime_deps_target" ] forward_variables_from(invoker, [ "outputs", "testonly", ]) flatten = false flatten_relative_to = false if (defined(invoker.flatten)) { flatten = invoker.flatten if (defined(invoker.flatten_relative_to)) { flatten_relative_to = invoker.flatten_relative_to } } args = rebase_path(outputs + [ _runtime_deps_file ], root_build_dir) + [ target_cpu, target_os, "$flatten", "$flatten_relative_to", ] } } copy("electron_license") { sources = [ "LICENSE" ] outputs = [ "$root_build_dir/{{source_file_part}}" ] } copy("chromium_licenses") { deps = [ "//components/resources:about_credits" ] sources = [ "$root_gen_dir/components/resources/about_credits.html" ] outputs = [ "$root_build_dir/LICENSES.chromium.html" ] } group("licenses") { data_deps = [ ":chromium_licenses", ":electron_license", ] } copy("electron_version") { sources = [ "ELECTRON_VERSION" ] outputs = [ "$root_build_dir/version" ] } dist_zip("electron_dist_zip") { data_deps = [ ":electron_app", ":electron_version", ":licenses", ] if (is_linux) { data_deps += [ "//sandbox/linux:chrome_sandbox" ] } outputs = [ "$root_build_dir/dist.zip" ] } dist_zip("electron_ffmpeg_zip") { data_deps = [ "//third_party/ffmpeg" ] outputs = [ "$root_build_dir/ffmpeg.zip" ] } electron_chromedriver_deps = [ ":licenses", "//chrome/test/chromedriver", "//electron/buildflags", ] group("electron_chromedriver") { testonly = true public_deps = electron_chromedriver_deps } dist_zip("electron_chromedriver_zip") { testonly = true data_deps = electron_chromedriver_deps outputs = [ "$root_build_dir/chromedriver.zip" ] } mksnapshot_deps = [ ":licenses", "//v8:mksnapshot($v8_snapshot_toolchain)", ] if (use_v8_context_snapshot) { mksnapshot_deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_generator($v8_snapshot_toolchain)" ] } group("electron_mksnapshot") { public_deps = mksnapshot_deps } dist_zip("electron_mksnapshot_zip") { data_deps = mksnapshot_deps outputs = [ "$root_build_dir/mksnapshot.zip" ] } copy("hunspell_dictionaries") { sources = hunspell_dictionaries + hunspell_licenses outputs = [ "$target_gen_dir/electron_hunspell/{{source_file_part}}" ] } dist_zip("hunspell_dictionaries_zip") { data_deps = [ ":hunspell_dictionaries" ] flatten = true outputs = [ "$root_build_dir/hunspell_dictionaries.zip" ] } copy("libcxx_headers") { sources = libcxx_headers + libcxx_licenses + [ "//buildtools/third_party/libc++/__config_site" ] outputs = [ "$target_gen_dir/electron_libcxx_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxx_headers_zip") { data_deps = [ ":libcxx_headers" ] flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxx_include/buildtools/third_party/libc++/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxx_headers.zip" ] } copy("libcxxabi_headers") { sources = libcxxabi_headers + libcxxabi_licenses outputs = [ "$target_gen_dir/electron_libcxxabi_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxxabi_headers_zip") { data_deps = [ ":libcxxabi_headers" ] flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxxabi_include/buildtools/third_party/libc++abi/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxxabi_headers.zip" ] } action("libcxx_objects_zip") { deps = [ "//buildtools/third_party/libc++" ] script = "build/zip_libcxx.py" outputs = [ "$root_build_dir/libcxx_objects.zip" ] args = rebase_path(outputs) } group("electron") { public_deps = [ ":electron_app" ] }
closed
electron/electron
https://github.com/electron/electron
32,455
Update deprecated QuickLook Thumbnailing methods
Nearly all methods we use in `nativeImage.createThumbnailFromPath()` are deprecated on macOS as of 10.15 and scheduled for imminent removal - we should update our usage of those methods to the newer `QuickLookThumbnailing` framework accordingly. See [here](https://developer.apple.com/documentation/quicklook/previews_or_thumbnail_images_for_macos_10_14_or_earlier?language=objc) for deprecation information and [here](https://developer.apple.com/documentation/quicklookthumbnailing?language=objc) for the updated framework we should use.
https://github.com/electron/electron/issues/32455
https://github.com/electron/electron/pull/32456
c3d11e2ea2d9751a457c72805b7688a38ceac30a
4c39eb32b0d2be479b9a0856186c6dfeccae6b96
2022-01-13T13:46:22Z
c++
2022-02-02T22:01:05Z
shell/common/api/electron_api_native_image_mac.mm
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/api/electron_api_native_image.h" #include <string> #include <utility> #include <vector> #import <Cocoa/Cocoa.h> #import <QuickLook/QuickLook.h> #include "base/mac/foundation_util.h" #include "base/strings/sys_string_conversions.h" #include "gin/arguments.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/promise.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" namespace electron { namespace api { NSData* bufferFromNSImage(NSImage* image) { CGImageRef ref = [image CGImageForProposedRect:nil context:nil hints:nil]; NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithCGImage:ref]; [rep setSize:[image size]]; return [rep representationUsingType:NSPNGFileType properties:[[NSDictionary alloc] init]]; } double safeShift(double in, double def) { if (in >= 0 || in <= 1 || in == def) return in; return def; } // static v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath( v8::Isolate* isolate, const base::FilePath& path, const gfx::Size& size) { gin_helper::Promise<gfx::Image> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (size.IsEmpty()) { promise.RejectWithErrorMessage("size must not be empty"); return handle; } CGSize cg_size = size.ToCGSize(); base::ScopedCFTypeRef<CFURLRef> cfurl = base::mac::FilePathToCFURL(path); base::ScopedCFTypeRef<QLThumbnailRef> ql_thumbnail( QLThumbnailCreate(kCFAllocatorDefault, cfurl, cg_size, NULL)); __block gin_helper::Promise<gfx::Image> p = std::move(promise); // we do not want to blocking the main thread while waiting for quicklook to // generate the thumbnail QLThumbnailDispatchAsync( ql_thumbnail, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, /*flags*/ 0), ^{ base::ScopedCFTypeRef<CGImageRef> cg_thumbnail( QLThumbnailCopyImage(ql_thumbnail)); if (cg_thumbnail) { NSImage* result = [[[NSImage alloc] initWithCGImage:cg_thumbnail size:cg_size] autorelease]; gfx::Image thumbnail(result); dispatch_async(dispatch_get_main_queue(), ^{ p.Resolve(thumbnail); }); } else { dispatch_async(dispatch_get_main_queue(), ^{ p.RejectWithErrorMessage("unable to retrieve thumbnail preview " "image for the given path"); }); } }); return handle; } gin::Handle<NativeImage> NativeImage::CreateFromNamedImage(gin::Arguments* args, std::string name) { @autoreleasepool { std::vector<double> hsl_shift; // The string representations of NSImageNames don't match the strings // themselves; they instead follow the following pattern: // * NSImageNameActionTemplate -> "NSActionTemplate" // * NSImageNameMultipleDocuments -> "NSMultipleDocuments" // To account for this, we strip out "ImageName" from the passed string. std::string to_remove("ImageName"); size_t pos = name.find(to_remove); if (pos != std::string::npos) { name.erase(pos, to_remove.length()); } NSImage* image = [NSImage imageNamed:base::SysUTF8ToNSString(name)]; if (!image.valid) { return CreateEmpty(args->isolate()); } NSData* png_data = bufferFromNSImage(image); if (args->GetNext(&hsl_shift) && hsl_shift.size() == 3) { gfx::Image gfx_image = gfx::Image::CreateFrom1xPNGBytes( reinterpret_cast<const unsigned char*>((char*)[png_data bytes]), [png_data length]); color_utils::HSL shift = {safeShift(hsl_shift[0], -1), safeShift(hsl_shift[1], 0.5), safeShift(hsl_shift[2], 0.5)}; png_data = bufferFromNSImage( gfx::Image(gfx::ImageSkiaOperations::CreateHSLShiftedImage( gfx_image.AsImageSkia(), shift)) .AsNSImage()); } return CreateFromPNG(args->isolate(), (char*)[png_data bytes], [png_data length]); } } void NativeImage::SetTemplateImage(bool setAsTemplate) { [image_.AsNSImage() setTemplate:setAsTemplate]; } bool NativeImage::IsTemplateImage() { return [image_.AsNSImage() isTemplate]; } } // namespace api } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,696
[Bug]: savePage no generated files
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.0 ### What operating system are you using? Windows ### Operating System Version WIN10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior win.webContents.savePage('d:/aaaaaa.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) it will generate a html page file at d: ### Actual Behavior savePage has three formats that can be used if use HTMLComplete only produced a aaaaaa_files empty folder if use HTMLonly No files are generated nor error callbacks are generated MHTML option works fine ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32696
https://github.com/electron/electron/pull/32728
d46431b564d9618ca1f057aa8f44f085a0c8550a
81fcd732c2080ca857bc7cb5d5b8c701ab382a90
2022-02-01T10:44:55Z
c++
2022-02-07T08:51:59Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents` - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents` | undefined - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/master:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Returns: * `event` Event Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'new-window' _Deprecated_ Returns: * `event` NewWindowWebContentsEvent * `url` string * `frameName` string * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. * `options` BrowserWindowConstructorOptions - The options which will be used for creating the new [`BrowserWindow`](browser-window.md). * `additionalFeatures` string[] - The non-standard features (features not handled by Chromium or Electron) given to `window.open()`. Deprecated, and will now always be the empty array `[]`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Deprecated in favor of [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Emitted when the page requests to open a new window for a `url`. It could be requested by `window.open` or an external link like `<a target='_blank'>`. By default a new `BrowserWindow` will be created for the `url`. Calling `event.preventDefault()` will prevent Electron from automatically creating a new [`BrowserWindow`](browser-window.md). If you call `event.preventDefault()` and manually create a new [`BrowserWindow`](browser-window.md) then you must set `event.newGuest` to reference the new [`BrowserWindow`](browser-window.md) instance, failing to do so may result in unexpected behavior. For example: ```javascript myBrowserWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { event.preventDefault() const win = new BrowserWindow({ webContents: options.webContents, // use existing webContents if provided show: false }) win.once('ready-to-show', () => win.show()) if (!options.webContents) { const loadOptions = { httpReferrer: referrer } if (postBody != null) { const { data, contentType, boundary } = postBody loadOptions.postData = postBody.data loadOptions.extraHeaders = `content-type: ${contentType}; boundary=${boundary}` } win.loadURL(url, loadOptions) // existing webContents will be navigated automatically } event.newGuest = win }) ``` #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` BrowserWindowConstructorOptions - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `event` Event * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. #### Event: 'will-redirect' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`] request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when bluetooth device needs to be selected on call to `navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api `webBluetooth` should be enabled. If `event.preventDefault` is not called, first available device will be selected. `callback` should be called with `deviceId` to be selected, passing empty string to `callback` will cancel the request. If no event listener is added for this event, all bluetooth requests will be cancelled. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` WebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. **Note:** The specified `preload` script option will appear as `preloadURL` (not `preload`) in the `webPreferences` object emitted with this event. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. #### Event: 'ipc-message-sync' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'; Specifying 'user' enables you to prevent websites from overriding the CSS you insert. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`] request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` * `size` [Size](structures/size.md) (optional) - The preferred size for the capturer. * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Increase the capturer count by one. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. This also affects the Page Visibility API. #### `contents.decrementCapturerCount([stayHidden, stayAwake])` * `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Decrease the capturer count by one. The page will be set to hidden or occluded state when its browser window is hidden or occluded and the capturer count reaches zero. If you want to decrease the hidden capturer count instead you should set `stayHidden` to true. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `headerFooter` Record<string, string> (optional) - the header and footer for the PDF. * `title` string - The title for the PDF header. * `url` string - the url for the PDF footer. * `landscape` boolean (optional) - `true` for landscape, `false` for portrait. * `marginsType` Integer (optional) - Specifies the type of margins to use. Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. * `scaleFactor` number (optional) - The scale factor of the web page. Can range from 0 to 100. * `pageRanges` Record<string, number> (optional) - The page range to print. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width` in microns. * `printBackground` boolean (optional) - Whether to print CSS backgrounds. * `printSelectionOnly` boolean (optional) - Whether to print selection only. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints window's web page as PDF with Chromium's preview printing custom settings. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. By default, an empty `options` will be regarded as: ```javascript { marginsType: 0, printBackground: false, printSelectionOnly: false, landscape: false, pageSize: 'A4', scaleFactor: 100 } ``` Use `page-break-before: always;` CSS style to force to print to a new page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE**: Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. An example of sending messages from the main process to the renderer process: ```javascript // In the main process. const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL(`file://${__dirname}/index.html`) win.webContents.on('did-finish-load', () => { win.webContents.send('ping', 'whoooooooh!') }) }) ``` ```html <!-- index.html --> <html> <body> <script> require('electron').ipcRenderer.on('ping', (event, message) => { console.log(message) // Prints 'whoooooooh!' }) </script> </body> </html> ``` #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | [number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The full file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether *offscreen rendering* is enabled. #### `contents.startPainting()` If *offscreen rendering* is enabled and not painting, start painting. #### `contents.stopPainting()` If *offscreen rendering* is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If *offscreen rendering* is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If *offscreen rendering* is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if *offscreen rendering* is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
closed
electron/electron
https://github.com/electron/electron
32,696
[Bug]: savePage no generated files
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.0 ### What operating system are you using? Windows ### Operating System Version WIN10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior win.webContents.savePage('d:/aaaaaa.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) it will generate a html page file at d: ### Actual Behavior savePage has three formats that can be used if use HTMLComplete only produced a aaaaaa_files empty folder if use HTMLonly No files are generated nor error callbacks are generated MHTML option works fine ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32696
https://github.com/electron/electron/pull/32728
d46431b564d9618ca1f057aa8f44f085a0c8550a
81fcd732c2080ca857bc7cb5d5b8c701ab382a90
2022-02-01T10:44:55Z
c++
2022-02-07T08:51:59Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/ignore_result.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !defined(OS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if defined(OS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if defined(OS_LINUX) || defined(OS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if defined(OS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if defined(OS_MAC) base::TimeDelta interval; if (ui::TextInsertionCaretBlinkPeriod(&interval)) return interval; #elif defined(OS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif defined(OS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if defined(OS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif defined(OS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if defined(OS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !defined(OS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif defined(OS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::DictionaryValue* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { base::DictionaryValue::Iterator it(*file_system_paths_value); for (; !it.IsAtEnd(); it.Advance()) { std::string type = it.value().is_string() ? it.value().GetString() : std::string(); result[it.key()] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { bool transparent = false; options.Get(options::kTransparent, &transparent); content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if defined(OS_LINUX) || defined(OS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionId& partition_id, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !defined(OS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission(user_gesture); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { bool guest = IsGuest() || type_ == Type::kBrowserView; absl::optional<SkColor> color = guest ? SK_ColorTRANSPARENT : web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(color); SetBackgroundColor(rwhv, color.value_or(SK_ColorWHITE)); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if defined(OS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if defined(OS_LINUX) || defined(OS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetList().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if defined(OS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if defined(OS_MAC) || defined(OS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !defined(OS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !defined(OS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // defined(OS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); ignore_result( web_contents()->IncrementCapturerCount(size, stay_hidden, stay_awake)); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronBrowser::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents, const viz::SurfaceId& surface_id, const gfx::Size& natural_size) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance()->EnterPictureInPicture( web_contents, surface_id, natural_size); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetWithoutPathExpansion(path.AsUTF8Unsafe(), std::make_unique<base::Value>(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetList()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !defined(OS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if defined(OS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,696
[Bug]: savePage no generated files
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.0 ### What operating system are you using? Windows ### Operating System Version WIN10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior win.webContents.savePage('d:/aaaaaa.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) it will generate a html page file at d: ### Actual Behavior savePage has three formats that can be used if use HTMLComplete only produced a aaaaaa_files empty folder if use HTMLonly No files are generated nor error callbacks are generated MHTML option works fine ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32696
https://github.com/electron/electron/pull/32728
d46431b564d9618ca1f057aa8f44f085a0c8550a
81fcd732c2080ca857bc7cb5d5b8c701ab382a90
2022-02-01T10:44:55Z
c++
2022-02-07T08:51:59Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,696
[Bug]: savePage no generated files
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.0 ### What operating system are you using? Windows ### Operating System Version WIN10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior win.webContents.savePage('d:/aaaaaa.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) it will generate a html page file at d: ### Actual Behavior savePage has three formats that can be used if use HTMLComplete only produced a aaaaaa_files empty folder if use HTMLonly No files are generated nor error callbacks are generated MHTML option works fine ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32696
https://github.com/electron/electron/pull/32728
d46431b564d9618ca1f057aa8f44f085a0c8550a
81fcd732c2080ca857bc7cb5d5b8c701ab382a90
2022-02-01T10:44:55Z
c++
2022-02-07T08:51:59Z
docs/api/web-contents.md
# webContents > Render and control web pages. Process: [Main](../glossary.md#main-process) `webContents` is an [EventEmitter][event-emitter]. It is responsible for rendering and controlling a web page and is a property of the [`BrowserWindow`](browser-window.md) object. An example of accessing the `webContents` object: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 1500 }) win.loadURL('http://github.com') const contents = win.webContents console.log(contents) ``` ## Methods These methods can be accessed from the `webContents` module: ```javascript const { webContents } = require('electron') console.log(webContents) ``` ### `webContents.getAllWebContents()` Returns `WebContents[]` - An array of all `WebContents` instances. This will contain web contents for all windows, webviews, opened devtools, and devtools extension background pages. ### `webContents.getFocusedWebContents()` Returns `WebContents` - The web contents that is focused in this application, otherwise returns `null`. ### `webContents.fromId(id)` * `id` Integer Returns `WebContents` | undefined - A WebContents instance with the given ID, or `undefined` if there is no WebContents associated with the given ID. ### `webContents.fromDevToolsTargetId(targetId)` * `targetId` string - The Chrome DevTools Protocol [TargetID](https://chromedevtools.github.io/devtools-protocol/tot/Target/#type-TargetID) associated with the WebContents instance. Returns `WebContents` | undefined - A WebContents instance with the given TargetID, or `undefined` if there is no WebContents associated with the given TargetID. When communicating with the [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/), it can be useful to lookup a WebContents instance based on its assigned TargetID. ```js async function lookupTargetId (browserWindow) { const wc = browserWindow.webContents await wc.debugger.attach('1.3') const { targetInfo } = await wc.debugger.sendCommand('Target.getTargetInfo') const { targetId } = targetInfo const targetWebContents = await webContents.fromDevToolsTargetId(targetId) } ``` ## Class: WebContents > Render and control the contents of a BrowserWindow instance. Process: [Main](../glossary.md#main-process)<br /> _This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._ ### Instance Events #### Event: 'did-finish-load' Emitted when the navigation is done, i.e. the spinner of the tab has stopped spinning, and the `onload` event was dispatched. #### Event: 'did-fail-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-finish-load` but emitted when the load failed. The full list of error codes and their meaning is available [here](https://source.chromium.org/chromium/chromium/src/+/master:net/base/net_error_list.h). #### Event: 'did-fail-provisional-load' Returns: * `event` Event * `errorCode` Integer * `errorDescription` string * `validatedURL` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer This event is like `did-fail-load` but emitted when the load was cancelled (e.g. `window.stop()` was invoked). #### Event: 'did-frame-finish-load' Returns: * `event` Event * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a frame has done navigation. #### Event: 'did-start-loading' Corresponds to the points in time when the spinner of the tab started spinning. #### Event: 'did-stop-loading' Corresponds to the points in time when the spinner of the tab stopped spinning. #### Event: 'dom-ready' Returns: * `event` Event Emitted when the document in the top-level frame is loaded. #### Event: 'page-title-updated' Returns: * `event` Event * `title` string * `explicitSet` boolean Fired when page title is set during navigation. `explicitSet` is false when title is synthesized from file url. #### Event: 'page-favicon-updated' Returns: * `event` Event * `favicons` string[] - Array of URLs. Emitted when page receives favicon urls. #### Event: 'new-window' _Deprecated_ Returns: * `event` NewWindowWebContentsEvent * `url` string * `frameName` string * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. * `options` BrowserWindowConstructorOptions - The options which will be used for creating the new [`BrowserWindow`](browser-window.md). * `additionalFeatures` string[] - The non-standard features (features not handled by Chromium or Electron) given to `window.open()`. Deprecated, and will now always be the empty array `[]`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Deprecated in favor of [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Emitted when the page requests to open a new window for a `url`. It could be requested by `window.open` or an external link like `<a target='_blank'>`. By default a new `BrowserWindow` will be created for the `url`. Calling `event.preventDefault()` will prevent Electron from automatically creating a new [`BrowserWindow`](browser-window.md). If you call `event.preventDefault()` and manually create a new [`BrowserWindow`](browser-window.md) then you must set `event.newGuest` to reference the new [`BrowserWindow`](browser-window.md) instance, failing to do so may result in unexpected behavior. For example: ```javascript myBrowserWindow.webContents.on('new-window', (event, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { event.preventDefault() const win = new BrowserWindow({ webContents: options.webContents, // use existing webContents if provided show: false }) win.once('ready-to-show', () => win.show()) if (!options.webContents) { const loadOptions = { httpReferrer: referrer } if (postBody != null) { const { data, contentType, boundary } = postBody loadOptions.postData = postBody.data loadOptions.extraHeaders = `content-type: ${contentType}; boundary=${boundary}` } win.loadURL(url, loadOptions) // existing webContents will be navigated automatically } event.newGuest = win }) ``` #### Event: 'did-create-window' Returns: * `window` BrowserWindow * `details` Object * `url` string - URL for the created window. * `frameName` string - Name given to the created window in the `window.open()` call. * `options` BrowserWindowConstructorOptions - The options used to create the BrowserWindow. They are merged in increasing precedence: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Unrecognized options are not filtered out. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` and `other`. Emitted _after_ successful creation of a window via `window.open` in the renderer. Not emitted if the creation of the window is canceled from [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `webContents.setWindowOpenHandler`. #### Event: 'will-navigate' Returns: * `event` Event * `url` string Emitted when a user or the page wants to start navigation. It can happen when the `window.location` object is changed or a user clicks a link in the page. This event will not emit when the navigation is started programmatically with APIs like `webContents.loadURL` and `webContents.back`. It is also not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. Calling `event.preventDefault()` will prevent the navigation. #### Event: 'did-start-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame (including main) starts navigating. `isInPlace` will be `true` for in-page navigations. #### Event: 'will-redirect' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when a server side redirect occurs during navigation. For example a 302 redirect. This event will be emitted after `did-start-navigation` and always before the `did-redirect-navigation` event for the same navigation. Calling `event.preventDefault()` will prevent the navigation (not just the redirect). #### Event: 'did-redirect-navigation' Returns: * `event` Event * `url` string * `isInPlace` boolean * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted after a server side redirect occurs during navigation. For example a 302 redirect. This event cannot be prevented, if you want to prevent redirects you should checkout out the `will-redirect` event above. #### Event: 'did-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations Emitted when a main frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-frame-navigate' Returns: * `event` Event * `url` string * `httpResponseCode` Integer - -1 for non HTTP navigations * `httpStatusText` string - empty for non HTTP navigations, * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when any frame navigation is done. This event is not emitted for in-page navigations, such as clicking anchor links or updating the `window.location.hash`. Use `did-navigate-in-page` event for this purpose. #### Event: 'did-navigate-in-page' Returns: * `event` Event * `url` string * `isMainFrame` boolean * `frameProcessId` Integer * `frameRoutingId` Integer Emitted when an in-page navigation happened in any frame. When in-page navigation happens, the page URL changes but does not cause navigation outside of the page. Examples of this occurring are when anchor links are clicked or when the DOM `hashchange` event is triggered. #### Event: 'will-prevent-unload' Returns: * `event` Event Emitted when a `beforeunload` event handler is attempting to cancel a page unload. Calling `event.preventDefault()` will ignore the `beforeunload` event handler and allow the page to be unloaded. ```javascript const { BrowserWindow, dialog } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('will-prevent-unload', (event) => { const choice = dialog.showMessageBoxSync(win, { type: 'question', buttons: ['Leave', 'Stay'], title: 'Do you want to leave this site?', message: 'Changes you made may not be saved.', defaultId: 0, cancelId: 1 }) const leave = (choice === 0) if (leave) { event.preventDefault() } }) ``` **Note:** This will be emitted for `BrowserViews` but will _not_ be respected - this is because we have chosen not to tie the `BrowserView` lifecycle to its owning BrowserWindow should one exist per the [specification](https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event). #### Event: 'crashed' _Deprecated_ Returns: * `event` Event * `killed` boolean Emitted when the renderer process crashes or is killed. **Deprecated:** This event is superceded by the `render-process-gone` event which contains more information about why the render process disappeared. It isn't always because it crashed. The `killed` boolean can be replaced by checking `reason === 'killed'` when you switch to that event. #### Event: 'render-process-gone' Returns: * `event` Event * `details` Object * `reason` string - The reason the render process is gone. Possible values: * `clean-exit` - Process exited with an exit code of zero * `abnormal-exit` - Process exited with a non-zero exit code * `killed` - Process was sent a SIGTERM or otherwise killed externally * `crashed` - Process crashed * `oom` - Process ran out of memory * `launch-failed` - Process never successfully launched * `integrity-failure` - Windows code integrity checks failed * `exitCode` Integer - The exit code of the process, unless `reason` is `launch-failed`, in which case `exitCode` will be a platform-specific launch failure error code. Emitted when the renderer process unexpectedly disappears. This is normally because it was crashed or killed. #### Event: 'unresponsive' Emitted when the web page becomes unresponsive. #### Event: 'responsive' Emitted when the unresponsive web page becomes responsive again. #### Event: 'plugin-crashed' Returns: * `event` Event * `name` string * `version` string Emitted when a plugin process has crashed. #### Event: 'destroyed' Emitted when `webContents` is destroyed. #### Event: 'before-input-event' Returns: * `event` Event * `input` Object - Input properties. * `type` string - Either `keyUp` or `keyDown`. * `key` string - Equivalent to [KeyboardEvent.key][keyboardevent]. * `code` string - Equivalent to [KeyboardEvent.code][keyboardevent]. * `isAutoRepeat` boolean - Equivalent to [KeyboardEvent.repeat][keyboardevent]. * `isComposing` boolean - Equivalent to [KeyboardEvent.isComposing][keyboardevent]. * `shift` boolean - Equivalent to [KeyboardEvent.shiftKey][keyboardevent]. * `control` boolean - Equivalent to [KeyboardEvent.controlKey][keyboardevent]. * `alt` boolean - Equivalent to [KeyboardEvent.altKey][keyboardevent]. * `meta` boolean - Equivalent to [KeyboardEvent.metaKey][keyboardevent]. * `location` number - Equivalent to [KeyboardEvent.location][keyboardevent]. * `modifiers` string[] - See [InputEvent.modifiers](structures/input-event.md). Emitted before dispatching the `keydown` and `keyup` events in the page. Calling `event.preventDefault` will prevent the page `keydown`/`keyup` events and the menu shortcuts. To only prevent the menu shortcuts, use [`setIgnoreMenuShortcuts`](#contentssetignoremenushortcutsignore): ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('before-input-event', (event, input) => { // For example, only enable application menu keyboard shortcuts when // Ctrl/Cmd are down. win.webContents.setIgnoreMenuShortcuts(!input.control && !input.meta) }) ``` #### Event: 'enter-html-full-screen' Emitted when the window enters a full-screen state triggered by HTML API. #### Event: 'leave-html-full-screen' Emitted when the window leaves a full-screen state triggered by HTML API. #### Event: 'zoom-changed' Returns: * `event` Event * `zoomDirection` string - Can be `in` or `out`. Emitted when the user is requesting to change the zoom level using the mouse wheel. #### Event: 'blur' Emitted when the `WebContents` loses focus. #### Event: 'focus' Emitted when the `WebContents` gains focus. Note that on macOS, having focus means the `WebContents` is the first responder of window, so switching focus between windows would not trigger the `focus` and `blur` events of `WebContents`, as the first responder of each window is not changed. The `focus` and `blur` events of `WebContents` should only be used to detect focus change between different `WebContents` and `BrowserView` in the same window. #### Event: 'devtools-opened' Emitted when DevTools is opened. #### Event: 'devtools-closed' Emitted when DevTools is closed. #### Event: 'devtools-focused' Emitted when DevTools is focused / opened. #### Event: 'certificate-error' Returns: * `event` Event * `url` string * `error` string - The error code. * `certificate` [Certificate](structures/certificate.md) * `callback` Function * `isTrusted` boolean - Indicates whether the certificate can be considered trusted. * `isMainFrame` boolean Emitted when failed to verify the `certificate` for `url`. The usage is the same with [the `certificate-error` event of `app`](app.md#event-certificate-error). #### Event: 'select-client-certificate' Returns: * `event` Event * `url` URL * `certificateList` [Certificate[]](structures/certificate.md) * `callback` Function * `certificate` [Certificate](structures/certificate.md) - Must be a certificate from the given list. Emitted when a client certificate is requested. The usage is the same with [the `select-client-certificate` event of `app`](app.md#event-select-client-certificate). #### Event: 'login' Returns: * `event` Event * `authenticationResponseDetails` Object * `url` URL * `authInfo` Object * `isProxy` boolean * `scheme` string * `host` string * `port` Integer * `realm` string * `callback` Function * `username` string (optional) * `password` string (optional) Emitted when `webContents` wants to do basic auth. The usage is the same with [the `login` event of `app`](app.md#event-login). #### Event: 'found-in-page' Returns: * `event` Event * `result` Object * `requestId` Integer * `activeMatchOrdinal` Integer - Position of the active match. * `matches` Integer - Number of Matches. * `selectionArea` Rectangle - Coordinates of first match region. * `finalUpdate` boolean Emitted when a result is available for [`webContents.findInPage`] request. #### Event: 'media-started-playing' Emitted when media starts playing. #### Event: 'media-paused' Emitted when media is paused or done playing. #### Event: 'did-change-theme-color' Returns: * `event` Event * `color` (string | null) - Theme color is in format of '#rrggbb'. It is `null` when no theme color is set. Emitted when a page's theme color changes. This is usually due to encountering a meta tag: ```html <meta name='theme-color' content='#ff0000'> ``` #### Event: 'update-target-url' Returns: * `event` Event * `url` string Emitted when mouse moves over a link or the keyboard moves the focus to a link. #### Event: 'cursor-changed' Returns: * `event` Event * `type` string * `image` [NativeImage](native-image.md) (optional) * `scale` Float (optional) - scaling factor for the custom cursor. * `size` [Size](structures/size.md) (optional) - the size of the `image`. * `hotspot` [Point](structures/point.md) (optional) - coordinates of the custom cursor's hotspot. Emitted when the cursor's type changes. The `type` parameter can be `default`, `crosshair`, `pointer`, `text`, `wait`, `help`, `e-resize`, `n-resize`, `ne-resize`, `nw-resize`, `s-resize`, `se-resize`, `sw-resize`, `w-resize`, `ns-resize`, `ew-resize`, `nesw-resize`, `nwse-resize`, `col-resize`, `row-resize`, `m-panning`, `e-panning`, `n-panning`, `ne-panning`, `nw-panning`, `s-panning`, `se-panning`, `sw-panning`, `w-panning`, `move`, `vertical-text`, `cell`, `context-menu`, `alias`, `progress`, `nodrop`, `copy`, `none`, `not-allowed`, `zoom-in`, `zoom-out`, `grab`, `grabbing` or `custom`. If the `type` parameter is `custom`, the `image` parameter will hold the custom cursor image in a [`NativeImage`](native-image.md), and `scale`, `size` and `hotspot` will hold additional information about the custom cursor. #### Event: 'context-menu' Returns: * `event` Event * `params` Object * `x` Integer - x coordinate. * `y` Integer - y coordinate. * `frame` WebFrameMain - Frame from which the context menu was invoked. * `linkURL` string - URL of the link that encloses the node the context menu was invoked on. * `linkText` string - Text associated with the link. May be an empty string if the contents of the link are an image. * `pageURL` string - URL of the top level page that the context menu was invoked on. * `frameURL` string - URL of the subframe that the context menu was invoked on. * `srcURL` string - Source URL for the element that the context menu was invoked on. Elements with source URLs are images, audio and video. * `mediaType` string - Type of the node the context menu was invoked on. Can be `none`, `image`, `audio`, `video`, `canvas`, `file` or `plugin`. * `hasImageContents` boolean - Whether the context menu was invoked on an image which has non-empty contents. * `isEditable` boolean - Whether the context is editable. * `selectionText` string - Text of the selection that the context menu was invoked on. * `titleText` string - Title text of the selection that the context menu was invoked on. * `altText` string - Alt text of the selection that the context menu was invoked on. * `suggestedFilename` string - Suggested filename to be used when saving file through 'Save Link As' option of context menu. * `selectionRect` [Rectangle](structures/rectangle.md) - Rect representing the coordinates in the document space of the selection. * `selectionStartOffset` number - Start position of the selection text. * `referrerPolicy` [Referrer](structures/referrer.md) - The referrer policy of the frame on which the menu is invoked. * `misspelledWord` string - The misspelled word under the cursor, if any. * `dictionarySuggestions` string[] - An array of suggested words to show the user to replace the `misspelledWord`. Only available if there is a misspelled word and spellchecker is enabled. * `frameCharset` string - The character encoding of the frame on which the menu was invoked. * `inputFieldType` string - If the context menu was invoked on an input field, the type of that field. Possible values are `none`, `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. * `mediaFlags` Object - The flags for the media element the context menu was invoked on. * `inError` boolean - Whether the media element has crashed. * `isPaused` boolean - Whether the media element is paused. * `isMuted` boolean - Whether the media element is muted. * `hasAudio` boolean - Whether the media element has audio. * `isLooping` boolean - Whether the media element is looping. * `isControlsVisible` boolean - Whether the media element's controls are visible. * `canToggleControls` boolean - Whether the media element's controls are toggleable. * `canPrint` boolean - Whether the media element can be printed. * `canSave` boolean - Whether or not the media element can be downloaded. * `canShowPictureInPicture` boolean - Whether the media element can show picture-in-picture. * `isShowingPictureInPicture` boolean - Whether the media element is currently showing picture-in-picture. * `canRotate` boolean - Whether the media element can be rotated. * `canLoop` boolean - Whether the media element can be looped. * `editFlags` Object - These flags indicate whether the renderer believes it is able to perform the corresponding action. * `canUndo` boolean - Whether the renderer believes it can undo. * `canRedo` boolean - Whether the renderer believes it can redo. * `canCut` boolean - Whether the renderer believes it can cut. * `canCopy` boolean - Whether the renderer believes it can copy. * `canPaste` boolean - Whether the renderer believes it can paste. * `canDelete` boolean - Whether the renderer believes it can delete. * `canSelectAll` boolean - Whether the renderer believes it can select all. * `canEditRichly` boolean - Whether the renderer believes it can edit text richly. Emitted when there is a new context menu that needs to be handled. #### Event: 'select-bluetooth-device' Returns: * `event` Event * `devices` [BluetoothDevice[]](structures/bluetooth-device.md) * `callback` Function * `deviceId` string Emitted when bluetooth device needs to be selected on call to `navigator.bluetooth.requestDevice`. To use `navigator.bluetooth` api `webBluetooth` should be enabled. If `event.preventDefault` is not called, first available device will be selected. `callback` should be called with `deviceId` to be selected, passing empty string to `callback` will cancel the request. If no event listener is added for this event, all bluetooth requests will be cancelled. ```javascript const { app, BrowserWindow } = require('electron') let win = null app.commandLine.appendSwitch('enable-experimental-web-platform-features') app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { event.preventDefault() const result = deviceList.find((device) => { return device.deviceName === 'test' }) if (!result) { callback('') } else { callback(result.deviceId) } }) }) ``` #### Event: 'paint' Returns: * `event` Event * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ webPreferences: { offscreen: true } }) win.webContents.on('paint', (event, dirty, image) => { // updateBitmap(dirty, image.getBitmap()) }) win.loadURL('http://github.com') ``` #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload #### Event: 'will-attach-webview' Returns: * `event` Event * `webPreferences` WebPreferences - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. * `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web contents. Calling `event.preventDefault()` will destroy the guest page. This event can be used to configure `webPreferences` for the `webContents` of a `<webview>` before it's loaded, and provides the ability to set settings that can't be set via `<webview>` attributes. **Note:** The specified `preload` script option will appear as `preloadURL` (not `preload`) in the `webPreferences` object emitted with this event. #### Event: 'did-attach-webview' Returns: * `event` Event * `webContents` WebContents - The guest web contents that is used by the `<webview>`. Emitted when a `<webview>` has been attached to this web contents. #### Event: 'console-message' Returns: * `event` Event * `level` Integer - The log level, from 0 to 3. In order it matches `verbose`, `info`, `warning` and `error`. * `message` string - The actual console message * `line` Integer - The line number of the source that triggered this console message * `sourceId` string Emitted when the associated window logs a console message. #### Event: 'preload-error' Returns: * `event` Event * `preloadPath` string * `error` Error Emitted when the preload script `preloadPath` throws an unhandled exception `error`. #### Event: 'ipc-message' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends an asynchronous message via `ipcRenderer.send()`. #### Event: 'ipc-message-sync' Returns: * `event` Event * `channel` string * `...args` any[] Emitted when the renderer process sends a synchronous message via `ipcRenderer.sendSync()`. #### Event: 'preferred-size-changed' Returns: * `event` Event * `preferredSize` [Size](structures/size.md) - The minimum size needed to contain the layout of the document—without requiring scrolling. Emitted when the `WebContents` preferred size has changed. This event will only be emitted when `enablePreferredSizeMode` is set to `true` in `webPreferences`. #### Event: 'frame-created' Returns: * `event` Event * `details` Object * `frame` WebFrameMain Emitted when the [mainFrame](web-contents.md#contentsmainframe-readonly), an `<iframe>`, or a nested `<iframe>` is loaded within the page. ### Instance Methods #### `contents.loadURL(url[, options])` * `url` string * `options` Object (optional) * `httpReferrer` (string | [Referrer](structures/referrer.md)) (optional) - An HTTP Referrer url. * `userAgent` string (optional) - A user agent originating the request. * `extraHeaders` string (optional) - Extra headers separated by "\n". * `postData` ([UploadRawData](structures/upload-raw-data.md) | [UploadFile](structures/upload-file.md))[] (optional) * `baseURLForDataURL` string (optional) - Base url (with trailing path separator) for files to be loaded by the data url. This is needed only if the specified `url` is a data url and needs to load other files. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). A noop rejection handler is already attached, which avoids unhandled rejection errors. Loads the `url` in the window. The `url` must contain the protocol prefix, e.g. the `http://` or `file://`. If the load should bypass http cache then use the `pragma` header to achieve it. ```javascript const { webContents } = require('electron') const options = { extraHeaders: 'pragma: no-cache\n' } webContents.loadURL('https://github.com', options) ``` #### `contents.loadFile(filePath[, options])` * `filePath` string * `options` Object (optional) * `query` Record<string, string> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. Returns `Promise<void>` - the promise will resolve when the page has finished loading (see [`did-finish-load`](web-contents.md#event-did-finish-load)), and rejects if the page fails to load (see [`did-fail-load`](web-contents.md#event-did-fail-load)). Loads the given file in the window, `filePath` should be a path to an HTML file relative to the root of your application. For instance an app structure like this: ```sh | root | - package.json | - src | - main.js | - index.html ``` Would require code like this ```js win.loadFile('src/index.html') ``` #### `contents.downloadURL(url)` * `url` string Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. #### `contents.getURL()` Returns `string` - The URL of the current web page. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com').then(() => { const currentURL = win.webContents.getURL() console.log(currentURL) }) ``` #### `contents.getTitle()` Returns `string` - The title of the current web page. #### `contents.isDestroyed()` Returns `boolean` - Whether the web page is destroyed. #### `contents.focus()` Focuses the web page. #### `contents.isFocused()` Returns `boolean` - Whether the web page is focused. #### `contents.isLoading()` Returns `boolean` - Whether web page is still loading resources. #### `contents.isLoadingMainFrame()` Returns `boolean` - Whether the main frame (and not just iframes or frames within it) is still loading. #### `contents.isWaitingForResponse()` Returns `boolean` - Whether the web page is waiting for a first-response from the main resource of the page. #### `contents.stop()` Stops any pending navigation. #### `contents.reload()` Reloads the current web page. #### `contents.reloadIgnoringCache()` Reloads current page and ignores cache. #### `contents.canGoBack()` Returns `boolean` - Whether the browser can go back to previous web page. #### `contents.canGoForward()` Returns `boolean` - Whether the browser can go forward to next web page. #### `contents.canGoToOffset(offset)` * `offset` Integer Returns `boolean` - Whether the web page can go to `offset`. #### `contents.clearHistory()` Clears the navigation history. #### `contents.goBack()` Makes the browser go back a web page. #### `contents.goForward()` Makes the browser go forward a web page. #### `contents.goToIndex(index)` * `index` Integer Navigates browser to the specified absolute web page index. #### `contents.goToOffset(offset)` * `offset` Integer Navigates to the specified offset from the "current entry". #### `contents.isCrashed()` Returns `boolean` - Whether the renderer process has crashed. #### `contents.forcefullyCrashRenderer()` Forcefully terminates the renderer process that is currently hosting this `webContents`. This will cause the `render-process-gone` event to be emitted with the `reason=killed || reason=crashed`. Please note that some webContents share renderer processes and therefore calling this method may also crash the host process for other webContents as well. Calling `reload()` immediately after calling this method will force the reload to occur in a new process. This should be used when this process is unstable or unusable, for instance in order to recover from the `unresponsive` event. ```js contents.on('unresponsive', async () => { const { response } = await dialog.showMessageBox({ message: 'App X has become unresponsive', title: 'Do you want to try forcefully reloading the app?', buttons: ['OK', 'Cancel'], cancelId: 1 }) if (response === 0) { contents.forcefullyCrashRenderer() contents.reload() } }) ``` #### `contents.setUserAgent(userAgent)` * `userAgent` string Overrides the user agent for this web page. #### `contents.getUserAgent()` Returns `string` - The user agent for this web page. #### `contents.insertCSS(css[, options])` * `css` string * `options` Object (optional) * `cssOrigin` string (optional) - Can be either 'user' or 'author'; Specifying 'user' enables you to prevent websites from overriding the CSS you insert. Default is 'author'. Returns `Promise<string>` - A promise that resolves with a key for the inserted CSS that can later be used to remove the CSS via `contents.removeInsertedCSS(key)`. Injects CSS into the current web page and returns a unique key for the inserted stylesheet. ```js contents.on('did-finish-load', () => { contents.insertCSS('html, body { background-color: #f00; }') }) ``` #### `contents.removeInsertedCSS(key)` * `key` string Returns `Promise<void>` - Resolves if the removal was successful. Removes the inserted CSS from the current web page. The stylesheet is identified by its key, which is returned from `contents.insertCSS(css)`. ```js contents.on('did-finish-load', async () => { const key = await contents.insertCSS('html, body { background-color: #f00; }') contents.removeInsertedCSS(key) }) ``` #### `contents.executeJavaScript(code[, userGesture])` * `code` string * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Evaluates `code` in page. In the browser window some HTML APIs like `requestFullScreen` can only be invoked by a gesture from the user. Setting `userGesture` to `true` will remove this limitation. Code execution will be suspended until web page stop loading. ```js contents.executeJavaScript('fetch("https://jsonplaceholder.typicode.com/users/1").then(resp => resp.json())', true) .then((result) => { console.log(result) // Will be the JSON object from the fetch call }) ``` #### `contents.executeJavaScriptInIsolatedWorld(worldId, scripts[, userGesture])` * `worldId` Integer - The ID of the world to run the javascript in, `0` is the default world, `999` is the world used by Electron's `contextIsolation` feature. You can provide any integer here. * `scripts` [WebSource[]](structures/web-source.md) * `userGesture` boolean (optional) - Default is `false`. Returns `Promise<any>` - A promise that resolves with the result of the executed code or is rejected if the result of the code is a rejected promise. Works like `executeJavaScript` but evaluates `scripts` in an isolated context. #### `contents.setIgnoreMenuShortcuts(ignore)` * `ignore` boolean Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` * `handler` Function<{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` * `features` string - Comma separated list of window features provided to `window.open()`. * `disposition` string - Can be `default`, `foreground-tab`, `background-tab`, `new-window`, `save-to-disk` or `other`. * `referrer` [Referrer](structures/referrer.md) - The referrer that will be passed to the new window. May or may not result in the `Referer` header being sent, depending on the referrer policy. * `postBody` [PostBody](structures/post-body.md) (optional) - The post data that will be sent to the new window, along with the appropriate headers that will be set. If no post data is to be sent, the value will be `null`. Only defined when the window is being created by a form that set `target=_blank`. Returns `{action: 'deny'} | {action: 'allow', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions}` - `deny` cancels the creation of the new window. `allow` will allow the new window to be created. Specifying `overrideBrowserWindowOptions` allows customization of the created window. Returning an unrecognized value such as a null, undefined, or an object without a recognized 'action' value will result in a console error and have the same effect as returning `{action: 'deny'}`. Called before creating a window a new window is requested by the renderer, e.g. by `window.open()`, a link with `target="_blank"`, shift+clicking on a link, or submitting a form with `<form target="_blank">`. See [`window.open()`](window-open.md) for more details and how to use this in conjunction with `did-create-window`. #### `contents.setAudioMuted(muted)` * `muted` boolean Mute the audio on the current web page. #### `contents.isAudioMuted()` Returns `boolean` - Whether this page has been muted. #### `contents.isCurrentlyAudible()` Returns `boolean` - Whether audio is currently playing. #### `contents.setZoomFactor(factor)` * `factor` Double - Zoom factor; default is 1.0. Changes the zoom factor to the specified factor. Zoom factor is zoom percent divided by 100, so 300% = 3.0. The factor must be greater than 0.0. #### `contents.getZoomFactor()` Returns `number` - the current zoom factor. #### `contents.setZoomLevel(level)` * `level` number - Zoom level. Changes the zoom level to the specified level. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. > **NOTE**: The zoom policy at the Chromium level is same-origin, meaning that the > zoom level for a specific domain propagates across all instances of windows with > the same domain. Differentiating the window URLs will make zoom work per-window. #### `contents.getZoomLevel()` Returns `number` - the current zoom level. #### `contents.setVisualZoomLevelLimits(minimumLevel, maximumLevel)` * `minimumLevel` number * `maximumLevel` number Returns `Promise<void>` Sets the maximum and minimum pinch-to-zoom level. > **NOTE**: Visual zoom is disabled by default in Electron. To re-enable it, call: > > ```js > contents.setVisualZoomLevelLimits(1, 3) > ``` #### `contents.undo()` Executes the editing command `undo` in web page. #### `contents.redo()` Executes the editing command `redo` in web page. #### `contents.cut()` Executes the editing command `cut` in web page. #### `contents.copy()` Executes the editing command `copy` in web page. #### `contents.copyImageAt(x, y)` * `x` Integer * `y` Integer Copy the image at the given position to the clipboard. #### `contents.paste()` Executes the editing command `paste` in web page. #### `contents.pasteAndMatchStyle()` Executes the editing command `pasteAndMatchStyle` in web page. #### `contents.delete()` Executes the editing command `delete` in web page. #### `contents.selectAll()` Executes the editing command `selectAll` in web page. #### `contents.unselect()` Executes the editing command `unselect` in web page. #### `contents.replace(text)` * `text` string Executes the editing command `replace` in web page. #### `contents.replaceMisspelling(text)` * `text` string Executes the editing command `replaceMisspelling` in web page. #### `contents.insertText(text)` * `text` string Returns `Promise<void>` Inserts `text` to the focused element. #### `contents.findInPage(text[, options])` * `text` string - Content to be searched, must not be empty. * `options` Object (optional) * `forward` boolean (optional) - Whether to search forward or backward, defaults to `true`. * `findNext` boolean (optional) - Whether to begin a new text finding session with this request. Should be `true` for initial requests, and `false` for follow-up requests. Defaults to `false`. * `matchCase` boolean (optional) - Whether search should be case-sensitive, defaults to `false`. Returns `Integer` - The request id used for the request. Starts a request to find all matches for the `text` in the web page. The result of the request can be obtained by subscribing to [`found-in-page`](web-contents.md#event-found-in-page) event. #### `contents.stopFindInPage(action)` * `action` string - Specifies the action to take place when ending [`webContents.findInPage`] request. * `clearSelection` - Clear the selection. * `keepSelection` - Translate the selection into a normal selection. * `activateSelection` - Focus and click the selection node. Stops any `findInPage` request for the `webContents` with the provided `action`. ```javascript const { webContents } = require('electron') webContents.on('found-in-page', (event, result) => { if (result.finalUpdate) webContents.stopFindInPage('clearSelection') }) const requestId = webContents.findInPage('api') console.log(requestId) ``` #### `contents.capturePage([rect])` * `rect` [Rectangle](structures/rectangle.md) (optional) - The area of the page to be captured. Returns `Promise<NativeImage>` - Resolves with a [NativeImage](native-image.md) Captures a snapshot of the page within `rect`. Omitting `rect` will capture the whole visible page. #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count is large then 0. #### `contents.incrementCapturerCount([size, stayHidden, stayAwake])` * `size` [Size](structures/size.md) (optional) - The preferred size for the capturer. * `stayHidden` boolean (optional) - Keep the page hidden instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Increase the capturer count by one. The page is considered visible when its browser window is hidden and the capturer count is non-zero. If you would like the page to stay hidden, you should ensure that `stayHidden` is set to true. This also affects the Page Visibility API. #### `contents.decrementCapturerCount([stayHidden, stayAwake])` * `stayHidden` boolean (optional) - Keep the page in hidden state instead of visible. * `stayAwake` boolean (optional) - Keep the system awake instead of allowing it to sleep. Decrease the capturer count by one. The page will be set to hidden or occluded state when its browser window is hidden or occluded and the capturer count reaches zero. If you want to decrease the hidden capturer count instead you should set `stayHidden` to true. #### `contents.getPrinters()` _Deprecated_ Get the system printer list. Returns [`PrinterInfo[]`](structures/printer-info.md) **Deprecated:** Should use the new [`contents.getPrintersAsync`](web-contents.md#contentsgetprintersasync) API. #### `contents.getPrintersAsync()` Get the system printer list. Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/printer-info.md) #### `contents.print([options], [callback])` * `options` Object (optional) * `silent` boolean (optional) - Don't ask user for print settings. Default is `false`. * `printBackground` boolean (optional) - Prints the background color and image of the web page. Default is `false`. * `deviceName` string (optional) - Set the printer device name to use. Must be the system-defined name and not the 'friendly' name, e.g 'Brother_QL_820NWB' and not 'Brother QL-820NWB'. * `color` boolean (optional) - Set whether the printed web page will be in color or grayscale. Default is `true`. * `margins` Object (optional) * `marginType` string (optional) - Can be `default`, `none`, `printableArea`, or `custom`. If `custom` is chosen, you will also need to specify `top`, `bottom`, `left`, and `right`. * `top` number (optional) - The top margin of the printed web page, in pixels. * `bottom` number (optional) - The bottom margin of the printed web page, in pixels. * `left` number (optional) - The left margin of the printed web page, in pixels. * `right` number (optional) - The right margin of the printed web page, in pixels. * `landscape` boolean (optional) - Whether the web page should be printed in landscape mode. Default is `false`. * `scaleFactor` number (optional) - The scale factor of the web page. * `pagesPerSheet` number (optional) - The number of pages to print per page sheet. * `collate` boolean (optional) - Whether the web page should be collated. * `copies` number (optional) - The number of copies of the web page to print. * `pageRanges` Object[] (optional) - The page range to print. On macOS, only one range is honored. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. * `dpi` Record<string, number> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. * `footer` string (optional) - string to be printed as page footer. * `pageSize` string | Size (optional) - Specify page size of the printed document. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height`. * `callback` Function (optional) * `success` boolean - Indicates success of the print call. * `failureReason` string - Error description called back if the print fails. When a custom `pageSize` is passed, Chromium attempts to validate platform specific minimum values for `width_microns` and `height_microns`. Width and height must both be minimum 353 microns but may be higher on some operating systems. Prints window's web page. When `silent` is set to `true`, Electron will pick the system's default printer if `deviceName` is empty and the default settings for printing. Use `page-break-before: always;` CSS style to force to print to a new page. Example usage: ```js const options = { silent: true, deviceName: 'My-Printer', pageRanges: [{ from: 0, to: 1 }] } win.webContents.print(options, (success, errorType) => { if (!success) console.log(errorType) }) ``` #### `contents.printToPDF(options)` * `options` Object * `headerFooter` Record<string, string> (optional) - the header and footer for the PDF. * `title` string - The title for the PDF header. * `url` string - the url for the PDF footer. * `landscape` boolean (optional) - `true` for landscape, `false` for portrait. * `marginsType` Integer (optional) - Specifies the type of margins to use. Uses 0 for default margin, 1 for no margin, and 2 for minimum margin. * `scaleFactor` number (optional) - The scale factor of the web page. Can range from 0 to 100. * `pageRanges` Record<string, number> (optional) - The page range to print. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `pageSize` string | Size (optional) - Specify page size of the generated PDF. Can be `A3`, `A4`, `A5`, `Legal`, `Letter`, `Tabloid` or an Object containing `height` and `width` in microns. * `printBackground` boolean (optional) - Whether to print CSS backgrounds. * `printSelectionOnly` boolean (optional) - Whether to print selection only. Returns `Promise<Buffer>` - Resolves with the generated PDF data. Prints window's web page as PDF with Chromium's preview printing custom settings. The `landscape` will be ignored if `@page` CSS at-rule is used in the web page. By default, an empty `options` will be regarded as: ```javascript { marginsType: 0, printBackground: false, printSelectionOnly: false, landscape: false, pageSize: 'A4', scaleFactor: 100 } ``` Use `page-break-before: always;` CSS style to force to print to a new page. An example of `webContents.printToPDF`: ```javascript const { BrowserWindow } = require('electron') const fs = require('fs') const path = require('path') const os = require('os') const win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL('http://github.com') win.webContents.on('did-finish-load', () => { // Use default printing options const pdfPath = path.join(os.homedir(), 'Desktop', 'temp.pdf') win.webContents.printToPDF({}).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) }) ``` #### `contents.addWorkSpace(path)` * `path` string Adds the specified path to DevTools workspace. Must be used after DevTools creation: ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.webContents.on('devtools-opened', () => { win.webContents.addWorkSpace(__dirname) }) ``` #### `contents.removeWorkSpace(path)` * `path` string Removes the specified path from DevTools workspace. #### `contents.setDevToolsWebContents(devToolsWebContents)` * `devToolsWebContents` WebContents Uses the `devToolsWebContents` as the target `WebContents` to show devtools. The `devToolsWebContents` must not have done any navigation, and it should not be used for other purposes after the call. By default Electron manages the devtools by creating an internal `WebContents` with native view, which developers have very limited control of. With the `setDevToolsWebContents` method, developers can use any `WebContents` to show the devtools in it, including `BrowserWindow`, `BrowserView` and `<webview>` tag. Note that closing the devtools does not destroy the `devToolsWebContents`, it is caller's responsibility to destroy `devToolsWebContents`. An example of showing devtools in a `<webview>` tag: ```html <html> <head> <style type="text/css"> * { margin: 0; } #browser { height: 70%; } #devtools { height: 30%; } </style> </head> <body> <webview id="browser" src="https://github.com"></webview> <webview id="devtools" src="about:blank"></webview> <script> const { ipcRenderer } = require('electron') const emittedOnce = (element, eventName) => new Promise(resolve => { element.addEventListener(eventName, event => resolve(event), { once: true }) }) const browserView = document.getElementById('browser') const devtoolsView = document.getElementById('devtools') const browserReady = emittedOnce(browserView, 'dom-ready') const devtoolsReady = emittedOnce(devtoolsView, 'dom-ready') Promise.all([browserReady, devtoolsReady]).then(() => { const targetId = browserView.getWebContentsId() const devtoolsId = devtoolsView.getWebContentsId() ipcRenderer.send('open-devtools', targetId, devtoolsId) }) </script> </body> </html> ``` ```js // Main process const { ipcMain, webContents } = require('electron') ipcMain.on('open-devtools', (event, targetContentsId, devtoolsContentsId) => { const target = webContents.fromId(targetContentsId) const devtools = webContents.fromId(devtoolsContentsId) target.setDevToolsWebContents(devtools) target.openDevTools() }) ``` An example of showing devtools in a `BrowserWindow`: ```js const { app, BrowserWindow } = require('electron') let win = null let devtools = null app.whenReady().then(() => { win = new BrowserWindow() devtools = new BrowserWindow() win.loadURL('https://github.com') win.webContents.setDevToolsWebContents(devtools.webContents) win.webContents.openDevTools({ mode: 'detach' }) }) ``` #### `contents.openDevTools([options])` * `options` Object (optional) * `mode` string - Opens the devtools with specified dock state, can be `left`, `right`, `bottom`, `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's possible to dock back. In `detach` mode it's not. * `activate` boolean (optional) - Whether to bring the opened devtools window to the foreground. The default is `true`. Opens the devtools. When `contents` is a `<webview>` tag, the `mode` would be `detach` by default, explicitly passing an empty `mode` can force using last used dock state. #### `contents.closeDevTools()` Closes the devtools. #### `contents.isDevToolsOpened()` Returns `boolean` - Whether the devtools is opened. #### `contents.isDevToolsFocused()` Returns `boolean` - Whether the devtools view is focused . #### `contents.toggleDevTools()` Toggles the developer tools. #### `contents.inspectElement(x, y)` * `x` Integer * `y` Integer Starts inspecting element at position (`x`, `y`). #### `contents.inspectSharedWorker()` Opens the developer tools for the shared worker context. #### `contents.inspectSharedWorkerById(workerId)` * `workerId` string Inspects the shared worker based on its ID. #### `contents.getAllSharedWorkers()` Returns [`SharedWorkerInfo[]`](structures/shared-worker-info.md) - Information about all Shared Workers. #### `contents.inspectServiceWorker()` Opens the developer tools for the service worker context. #### `contents.send(channel, ...args)` * `channel` string * `...args` any[] Send an asynchronous message to the renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE**: Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. An example of sending messages from the main process to the renderer process: ```javascript // In the main process. const { app, BrowserWindow } = require('electron') let win = null app.whenReady().then(() => { win = new BrowserWindow({ width: 800, height: 600 }) win.loadURL(`file://${__dirname}/index.html`) win.webContents.on('did-finish-load', () => { win.webContents.send('ping', 'whoooooooh!') }) }) ``` ```html <!-- index.html --> <html> <body> <script> require('electron').ipcRenderer.on('ping', (event, message) => { console.log(message) // Prints 'whoooooooh!' }) </script> </body> </html> ``` #### `contents.sendToFrame(frameId, channel, ...args)` * `frameId` Integer | [number, number] - the ID of the frame to send to, or a pair of `[processId, frameId]` if the frame is in a different process to the main frame. * `channel` string * `...args` any[] Send an asynchronous message to a specific frame in a renderer process via `channel`, along with arguments. Arguments will be serialized with the [Structured Clone Algorithm][SCA], just like [`postMessage`][], so prototype chains will not be included. Sending Functions, Promises, Symbols, WeakMaps, or WeakSets will throw an exception. > **NOTE:** Sending non-standard JavaScript types such as DOM objects or > special Electron objects will throw an exception. The renderer process can handle the message by listening to `channel` with the [`ipcRenderer`](ipc-renderer.md) module. If you want to get the `frameId` of a given renderer context you should use the `webFrame.routingId` value. E.g. ```js // In a renderer process console.log('My frameId is:', require('electron').webFrame.routingId) ``` You can also read `frameId` from all incoming IPC messages in the main process. ```js // In the main process ipcMain.on('ping', (event) => { console.info('Message came from frameId:', event.frameId) }) ``` #### `contents.postMessage(channel, message, [transfer])` * `channel` string * `message` any * `transfer` MessagePortMain[] (optional) Send a message to the renderer process, optionally transferring ownership of zero or more [`MessagePortMain`][] objects. The transferred `MessagePortMain` objects will be available in the renderer process by accessing the `ports` property of the emitted event. When they arrive in the renderer, they will be native DOM `MessagePort` objects. For example: ```js // Main process const { port1, port2 } = new MessageChannelMain() webContents.postMessage('port', { message: 'hello' }, [port1]) // Renderer process ipcRenderer.on('port', (e, msg) => { const [port] = e.ports // ... }) ``` #### `contents.enableDeviceEmulation(parameters)` * `parameters` Object * `screenPosition` string - Specify the screen type to emulate (default: `desktop`): * `desktop` - Desktop screen type. * `mobile` - Mobile screen type. * `screenSize` [Size](structures/size.md) - Set the emulated screen size (screenPosition == mobile). * `viewPosition` [Point](structures/point.md) - Position the view on the screen (screenPosition == mobile) (default: `{ x: 0, y: 0 }`). * `deviceScaleFactor` Integer - Set the device scale factor (if zero defaults to original device scale factor) (default: `0`). * `viewSize` [Size](structures/size.md) - Set the emulated view size (empty means no override) * `scale` Float - Scale of emulated view inside available space (not in fit to view mode) (default: `1`). Enable device emulation with the given parameters. #### `contents.disableDeviceEmulation()` Disable device emulation enabled by `webContents.enableDeviceEmulation`. #### `contents.sendInputEvent(inputEvent)` * `inputEvent` [MouseInputEvent](structures/mouse-input-event.md) | [MouseWheelInputEvent](structures/mouse-wheel-input-event.md) | [KeyboardInputEvent](structures/keyboard-input-event.md) Sends an input `event` to the page. **Note:** The [`BrowserWindow`](browser-window.md) containing the contents needs to be focused for `sendInputEvent()` to work. #### `contents.beginFrameSubscription([onlyDirty ,]callback)` * `onlyDirty` boolean (optional) - Defaults to `false`. * `callback` Function * `image` [NativeImage](native-image.md) * `dirtyRect` [Rectangle](structures/rectangle.md) Begin subscribing for presentation events and captured frames, the `callback` will be called with `callback(image, dirtyRect)` when there is a presentation event. The `image` is an instance of [NativeImage](native-image.md) that stores the captured frame. The `dirtyRect` is an object with `x, y, width, height` properties that describes which part of the page was repainted. If `onlyDirty` is set to `true`, `image` will only contain the repainted area. `onlyDirty` defaults to `false`. #### `contents.endFrameSubscription()` End subscribing for frame presentation events. #### `contents.startDrag(item)` * `item` Object * `file` string - The path to the file being dragged. * `files` string[] (optional) - The paths to the files being dragged. (`files` will override `file` field) * `icon` [NativeImage](native-image.md) | string - The image must be non-empty on macOS. Sets the `item` as dragging item for current drag-drop operation, `file` is the absolute path of the file to be dragged, and `icon` is the image showing under the cursor when dragging. #### `contents.savePage(fullPath, saveType)` * `fullPath` string - The full file path. * `saveType` string - Specify the save type. * `HTMLOnly` - Save only the HTML of the page. * `HTMLComplete` - Save complete-html page. * `MHTML` - Save complete-html page as MHTML. Returns `Promise<void>` - resolves if the page is saved. ```javascript const { BrowserWindow } = require('electron') const win = new BrowserWindow() win.loadURL('https://github.com') win.webContents.on('did-finish-load', async () => { win.webContents.savePage('/tmp/test.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) }) ``` #### `contents.showDefinitionForSelection()` _macOS_ Shows pop-up dictionary that searches the selected word on the page. #### `contents.isOffscreen()` Returns `boolean` - Indicates whether *offscreen rendering* is enabled. #### `contents.startPainting()` If *offscreen rendering* is enabled and not painting, start painting. #### `contents.stopPainting()` If *offscreen rendering* is enabled and painting, stop painting. #### `contents.isPainting()` Returns `boolean` - If *offscreen rendering* is enabled returns whether it is currently painting. #### `contents.setFrameRate(fps)` * `fps` Integer If *offscreen rendering* is enabled sets the frame rate to the specified number. Only values between 1 and 240 are accepted. #### `contents.getFrameRate()` Returns `Integer` - If *offscreen rendering* is enabled returns the current frame rate. #### `contents.invalidate()` Schedules a full repaint of the window this web contents is in. If *offscreen rendering* is enabled invalidates the frame and generates a new one through the `'paint'` event. #### `contents.getWebRTCIPHandlingPolicy()` Returns `string` - Returns the WebRTC IP Handling Policy. #### `contents.setWebRTCIPHandlingPolicy(policy)` * `policy` string - Specify the WebRTC IP Handling Policy. * `default` - Exposes user's public and local IPs. This is the default behavior. When this policy is used, WebRTC has the right to enumerate all interfaces and bind them to discover public interfaces. * `default_public_interface_only` - Exposes user's public IP, but does not expose user's local IP. When this policy is used, WebRTC should only use the default route used by http. This doesn't expose any local addresses. * `default_public_and_private_interfaces` - Exposes user's public and local IPs. When this policy is used, WebRTC should only use the default route used by http. This also exposes the associated default private address. Default route is the route chosen by the OS on a multi-homed endpoint. * `disable_non_proxied_udp` - Does not expose public or local IPs. When this policy is used, WebRTC should only use TCP to contact peers or servers unless the proxy server supports UDP. Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. Returns `string` - The identifier of a WebContents stream. This identifier can be used with `navigator.mediaDevices.getUserMedia` using a `chromeMediaSource` of `tab`. The identifier is restricted to the web contents that it is registered to and is only valid for 10 seconds. #### `contents.getOSProcessId()` Returns `Integer` - The operating system `pid` of the associated renderer process. #### `contents.getProcessId()` Returns `Integer` - The Chromium internal `pid` of the associated renderer. Can be compared to the `frameProcessId` passed by frame specific navigation events (e.g. `did-frame-navigate`) #### `contents.takeHeapSnapshot(filePath)` * `filePath` string - Path to the output file. Returns `Promise<void>` - Indicates whether the snapshot has been created successfully. Takes a V8 heap snapshot and saves it to `filePath`. #### `contents.getBackgroundThrottling()` Returns `boolean` - whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.setBackgroundThrottling(allowed)` * `allowed` boolean Controls whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.getType()` Returns `string` - the type of the webContent. Can be `backgroundPage`, `window`, `browserView`, `remote`, `webview` or `offscreen`. #### `contents.setImageAnimationPolicy(policy)` * `policy` string - Can be `animate`, `animateOnce` or `noAnimation`. Sets the image animation policy for this webContents. The policy only affects _new_ images, existing images that are currently being animated are unaffected. This is a known limitation in Chromium, you can force image animation to be recalculated with `img.src = img.src` which will result in no network traffic but will update the animation policy. This corresponds to the [animationPolicy][] accessibility feature in Chromium. [animationPolicy]: https://developer.chrome.com/docs/extensions/reference/accessibilityFeatures/#property-animationPolicy ### Instance Properties #### `contents.audioMuted` A `boolean` property that determines whether this page is muted. #### `contents.userAgent` A `string` property that determines the user agent for this web page. #### `contents.zoomLevel` A `number` property that determines the zoom level for this web contents. The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. The formula for this is `scale := 1.2 ^ level`. #### `contents.zoomFactor` A `number` property that determines the zoom factor for this web contents. The zoom factor is the zoom percent divided by 100, so 300% = 3.0. #### `contents.frameRate` An `Integer` property that sets the frame rate of the web contents to the specified number. Only values between 1 and 240 are accepted. Only applicable if *offscreen rendering* is enabled. #### `contents.id` _Readonly_ A `Integer` representing the unique ID of this WebContents. Each ID is unique among all `WebContents` instances of the entire Electron application. #### `contents.session` _Readonly_ A [`Session`](session.md) used by this webContents. #### `contents.hostWebContents` _Readonly_ A [`WebContents`](web-contents.md) instance that might own this `WebContents`. #### `contents.devToolsWebContents` _Readonly_ A `WebContents | null` property that represents the of DevTools `WebContents` associated with a given `WebContents`. **Note:** Users should never store this object because it may become `null` when the DevTools has been closed. #### `contents.debugger` _Readonly_ A [`Debugger`](debugger.md) instance for this webContents. #### `contents.backgroundThrottling` A `boolean` property that determines whether or not this WebContents will throttle animations and timers when the page becomes backgrounded. This also affects the Page Visibility API. #### `contents.mainFrame` _Readonly_ A [`WebFrameMain`](web-frame-main.md) property that represents the top frame of the page's frame hierarchy. [keyboardevent]: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent [event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`postMessage`]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
closed
electron/electron
https://github.com/electron/electron
32,696
[Bug]: savePage no generated files
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.0 ### What operating system are you using? Windows ### Operating System Version WIN10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior win.webContents.savePage('d:/aaaaaa.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) it will generate a html page file at d: ### Actual Behavior savePage has three formats that can be used if use HTMLComplete only produced a aaaaaa_files empty folder if use HTMLonly No files are generated nor error callbacks are generated MHTML option works fine ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32696
https://github.com/electron/electron/pull/32728
d46431b564d9618ca1f057aa8f44f085a0c8550a
81fcd732c2080ca857bc7cb5d5b8c701ab382a90
2022-02-01T10:44:55Z
c++
2022-02-07T08:51:59Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/ignore_result.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !defined(OS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if defined(OS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if defined(OS_LINUX) || defined(OS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if defined(OS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if defined(OS_MAC) base::TimeDelta interval; if (ui::TextInsertionCaretBlinkPeriod(&interval)) return interval; #elif defined(OS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif defined(OS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if defined(OS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif defined(OS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if defined(OS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !defined(OS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif defined(OS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::DictionaryValue* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { base::DictionaryValue::Iterator it(*file_system_paths_value); for (; !it.IsAtEnd(); it.Advance()) { std::string type = it.value().is_string() ? it.value().GetString() : std::string(); result[it.key()] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { bool transparent = false; options.Get(options::kTransparent, &transparent); content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if defined(OS_LINUX) || defined(OS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionId& partition_id, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !defined(OS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission(user_gesture); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { bool guest = IsGuest() || type_ == Type::kBrowserView; absl::optional<SkColor> color = guest ? SK_ColorTRANSPARENT : web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(color); SetBackgroundColor(rwhv, color.value_or(SK_ColorWHITE)); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if defined(OS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if defined(OS_LINUX) || defined(OS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetList().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if defined(OS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if defined(OS_MAC) || defined(OS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !defined(OS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !defined(OS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // defined(OS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); ignore_result( web_contents()->IncrementCapturerCount(size, stay_hidden, stay_awake)); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronBrowser::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents, const viz::SurfaceId& surface_id, const gfx::Size& natural_size) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance()->EnterPictureInPicture( web_contents, surface_id, natural_size); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetWithoutPathExpansion(path.AsUTF8Unsafe(), std::make_unique<base::Value>(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetList()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !defined(OS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if defined(OS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,696
[Bug]: savePage no generated files
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.0 ### What operating system are you using? Windows ### Operating System Version WIN10 20H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior win.webContents.savePage('d:/aaaaaa.html', 'HTMLComplete').then(() => { console.log('Page was saved successfully.') }).catch(err => { console.log(err) }) it will generate a html page file at d: ### Actual Behavior savePage has three formats that can be used if use HTMLComplete only produced a aaaaaa_files empty folder if use HTMLonly No files are generated nor error callbacks are generated MHTML option works fine ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32696
https://github.com/electron/electron/pull/32728
d46431b564d9618ca1f057aa8f44f085a0c8550a
81fcd732c2080ca857bc7cb5d5b8c701ab382a90
2022-02-01T10:44:55Z
c++
2022-02-07T08:51:59Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,750
[Bug]: webContents.print() crashes with a non-null callback
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [x] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior Calling webContents.print({}, () => {}) will not crash, and will show the system print dialog. ### Actual Behavior The electron app crashes, even when the aforementioned print() call is encapsulated within a try-catch block. ### Testcase Gist URL https://gist.github.com/1ab968669f64a7707306e876ab2ff5bc ### Additional Information Looks pretty similar to #32276, though I'm not able to reproduce the crash in 16.0.5 as the author of that issue claims. Calling the print() API and providing undefined or null as the callback parameter still shows the dialog, although canceling that print dialog will still result in a crash (as documented in #32684). It's also worth noting that when running in Electron Fiddle, both the print dialog cancellation crash and this new crash share the same error code (3221225477), so I'm wondering if they're related, and if the PR fixing the dialog cancellation crash (#32632) might fix this as well.
https://github.com/electron/electron/issues/32750
https://github.com/electron/electron/pull/32767
c09ce25ab6d2315f8dffb5e5c8e10543d695a2f0
58af7d2a9ab1f3ce7f94b6141a534cb336aa2684
2022-02-04T16:52:48Z
c++
2022-02-08T15:15:30Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cfisobjc.patch mas-cgdisplayusesforcetogray.patch mas-audiodeviceduck.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_abort_report_np.patch mas_avoid_usage_of_pthread_fchdir_np.patch mas_avoid_usage_of_setapplicationisdaemon_and.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch put_back_deleted_colors_for_autofill.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch chore_use_electron_resources_not_chrome_for_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch ui_gtk_public_header.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch fix_use_electron_generated_resources.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch make_include_of_stack_trace_h_unconditional.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch mas_gate_private_enterprise_APIs.patch load_v8_snapshot_in_browser_process.patch fix_patch_out_permissions_checks_in_exclusive_access.patch fix_aspect_ratio_with_max_size.patch revert_stop_using_nsrunloop_in_renderer_process.patch fix_dont_delete_SerialPortManager_on_main_thread.patch feat_add_data_transfer_to_requestsingleinstancelock.patch fix_crash_when_saving_edited_pdf_files.patch
closed
electron/electron
https://github.com/electron/electron
32,750
[Bug]: webContents.print() crashes with a non-null callback
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [x] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior Calling webContents.print({}, () => {}) will not crash, and will show the system print dialog. ### Actual Behavior The electron app crashes, even when the aforementioned print() call is encapsulated within a try-catch block. ### Testcase Gist URL https://gist.github.com/1ab968669f64a7707306e876ab2ff5bc ### Additional Information Looks pretty similar to #32276, though I'm not able to reproduce the crash in 16.0.5 as the author of that issue claims. Calling the print() API and providing undefined or null as the callback parameter still shows the dialog, although canceling that print dialog will still result in a crash (as documented in #32684). It's also worth noting that when running in Electron Fiddle, both the print dialog cancellation crash and this new crash share the same error code (3221225477), so I'm wondering if they're related, and if the PR fixing the dialog cancellation crash (#32632) might fix this as well.
https://github.com/electron/electron/issues/32750
https://github.com/electron/electron/pull/32767
c09ce25ab6d2315f8dffb5e5c8e10543d695a2f0
58af7d2a9ab1f3ce7f94b6141a534cb336aa2684
2022-02-04T16:52:48Z
c++
2022-02-08T15:15:30Z
patches/chromium/drop_extra_printingcontext_calls_to_newpage_pagedone.patch
closed
electron/electron
https://github.com/electron/electron
32,750
[Bug]: webContents.print() crashes with a non-null callback
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [x] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior Calling webContents.print({}, () => {}) will not crash, and will show the system print dialog. ### Actual Behavior The electron app crashes, even when the aforementioned print() call is encapsulated within a try-catch block. ### Testcase Gist URL https://gist.github.com/1ab968669f64a7707306e876ab2ff5bc ### Additional Information Looks pretty similar to #32276, though I'm not able to reproduce the crash in 16.0.5 as the author of that issue claims. Calling the print() API and providing undefined or null as the callback parameter still shows the dialog, although canceling that print dialog will still result in a crash (as documented in #32684). It's also worth noting that when running in Electron Fiddle, both the print dialog cancellation crash and this new crash share the same error code (3221225477), so I'm wondering if they're related, and if the PR fixing the dialog cancellation crash (#32632) might fix this as well.
https://github.com/electron/electron/issues/32750
https://github.com/electron/electron/pull/32767
c09ce25ab6d2315f8dffb5e5c8e10543d695a2f0
58af7d2a9ab1f3ce7f94b6141a534cb336aa2684
2022-02-04T16:52:48Z
c++
2022-02-08T15:15:30Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cfisobjc.patch mas-cgdisplayusesforcetogray.patch mas-audiodeviceduck.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_abort_report_np.patch mas_avoid_usage_of_pthread_fchdir_np.patch mas_avoid_usage_of_setapplicationisdaemon_and.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch put_back_deleted_colors_for_autofill.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch chore_use_electron_resources_not_chrome_for_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch ui_gtk_public_header.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch fix_use_electron_generated_resources.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch make_include_of_stack_trace_h_unconditional.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch mas_gate_private_enterprise_APIs.patch load_v8_snapshot_in_browser_process.patch fix_patch_out_permissions_checks_in_exclusive_access.patch fix_aspect_ratio_with_max_size.patch revert_stop_using_nsrunloop_in_renderer_process.patch fix_dont_delete_SerialPortManager_on_main_thread.patch feat_add_data_transfer_to_requestsingleinstancelock.patch fix_crash_when_saving_edited_pdf_files.patch
closed
electron/electron
https://github.com/electron/electron
32,750
[Bug]: webContents.print() crashes with a non-null callback
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [x] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 version 20H2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior Calling webContents.print({}, () => {}) will not crash, and will show the system print dialog. ### Actual Behavior The electron app crashes, even when the aforementioned print() call is encapsulated within a try-catch block. ### Testcase Gist URL https://gist.github.com/1ab968669f64a7707306e876ab2ff5bc ### Additional Information Looks pretty similar to #32276, though I'm not able to reproduce the crash in 16.0.5 as the author of that issue claims. Calling the print() API and providing undefined or null as the callback parameter still shows the dialog, although canceling that print dialog will still result in a crash (as documented in #32684). It's also worth noting that when running in Electron Fiddle, both the print dialog cancellation crash and this new crash share the same error code (3221225477), so I'm wondering if they're related, and if the PR fixing the dialog cancellation crash (#32632) might fix this as well.
https://github.com/electron/electron/issues/32750
https://github.com/electron/electron/pull/32767
c09ce25ab6d2315f8dffb5e5c8e10543d695a2f0
58af7d2a9ab1f3ce7f94b6141a534cb336aa2684
2022-02-04T16:52:48Z
c++
2022-02-08T15:15:30Z
patches/chromium/drop_extra_printingcontext_calls_to_newpage_pagedone.patch
closed
electron/electron
https://github.com/electron/electron
32,702
[Bug]: `mainWindow.webContents.openDevTools` modes no longer work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version 12.2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior `mainWindow.webContents.openDevTools()` should be able to pass `{mode}` to set a specific dock position. ### Actual Behavior `mainWindow.webContents.openDevTools()` `mode` value no longer has any effect. To reproduce, add: ``` mainWindow.webContents.openDevTools({ mode: 'bottom' }) ``` to `createWindow` in the default Fiddle. Observe that it opens on the right side instead of the bottom. ### Testcase Gist URL _No response_ ### Additional Information Error originates [here](https://github.com/electron/electron/blob/b0f315a637b05bc445fc7e6084baa840891c1207/shell/browser/ui/inspectable_web_contents.cc#L589-L592) This was introduced in this [roll](https://chromium.googlesource.com/chromium/src/+log/98.0.4706.0..98.0.4758.9?n=10000&pretty=full), which contained this [roll](https://chromium.googlesource.com/devtools/devtools-frontend/+log/1b5567f78aca..b6f648d8921e?n=10000) and is almost certainly a result of [this CL](https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3264212) which removes legacy globals. We'll need to find an alternative way to fix this, or patch devtools to bring back the globals.
https://github.com/electron/electron/issues/32702
https://github.com/electron/electron/pull/32829
fe43296f7fd11171ebd73c0e6d248b9c6da5279d
84cf685e761b2dd22f064e0dbf33b290bbec5fc0
2022-02-01T15:03:25Z
c++
2022-02-17T05:59:13Z
patches/config.json
{ "src/electron/patches/chromium": "src", "src/electron/patches/boringssl": "src/third_party/boringssl/src", "src/electron/patches/webrtc": "src/third_party/webrtc", "src/electron/patches/v8": "src/v8", "src/electron/patches/node": "src/third_party/electron_node", "src/electron/patches/nan": "src/third_party/nan", "src/electron/patches/perfetto": "src/third_party/perfetto", "src/electron/patches/squirrel.mac": "src/third_party/squirrel.mac", "src/electron/patches/Mantle": "src/third_party/squirrel.mac/vendor/Mantle", "src/electron/patches/ReactiveObjC": "src/third_party/squirrel.mac/vendor/ReactiveObjC" }
closed
electron/electron
https://github.com/electron/electron
32,702
[Bug]: `mainWindow.webContents.openDevTools` modes no longer work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version 12.2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior `mainWindow.webContents.openDevTools()` should be able to pass `{mode}` to set a specific dock position. ### Actual Behavior `mainWindow.webContents.openDevTools()` `mode` value no longer has any effect. To reproduce, add: ``` mainWindow.webContents.openDevTools({ mode: 'bottom' }) ``` to `createWindow` in the default Fiddle. Observe that it opens on the right side instead of the bottom. ### Testcase Gist URL _No response_ ### Additional Information Error originates [here](https://github.com/electron/electron/blob/b0f315a637b05bc445fc7e6084baa840891c1207/shell/browser/ui/inspectable_web_contents.cc#L589-L592) This was introduced in this [roll](https://chromium.googlesource.com/chromium/src/+log/98.0.4706.0..98.0.4758.9?n=10000&pretty=full), which contained this [roll](https://chromium.googlesource.com/devtools/devtools-frontend/+log/1b5567f78aca..b6f648d8921e?n=10000) and is almost certainly a result of [this CL](https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3264212) which removes legacy globals. We'll need to find an alternative way to fix this, or patch devtools to bring back the globals.
https://github.com/electron/electron/issues/32702
https://github.com/electron/electron/pull/32829
fe43296f7fd11171ebd73c0e6d248b9c6da5279d
84cf685e761b2dd22f064e0dbf33b290bbec5fc0
2022-02-01T15:03:25Z
c++
2022-02-17T05:59:13Z
patches/devtools_frontend/.patches
closed
electron/electron
https://github.com/electron/electron
32,702
[Bug]: `mainWindow.webContents.openDevTools` modes no longer work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version 12.2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior `mainWindow.webContents.openDevTools()` should be able to pass `{mode}` to set a specific dock position. ### Actual Behavior `mainWindow.webContents.openDevTools()` `mode` value no longer has any effect. To reproduce, add: ``` mainWindow.webContents.openDevTools({ mode: 'bottom' }) ``` to `createWindow` in the default Fiddle. Observe that it opens on the right side instead of the bottom. ### Testcase Gist URL _No response_ ### Additional Information Error originates [here](https://github.com/electron/electron/blob/b0f315a637b05bc445fc7e6084baa840891c1207/shell/browser/ui/inspectable_web_contents.cc#L589-L592) This was introduced in this [roll](https://chromium.googlesource.com/chromium/src/+log/98.0.4706.0..98.0.4758.9?n=10000&pretty=full), which contained this [roll](https://chromium.googlesource.com/devtools/devtools-frontend/+log/1b5567f78aca..b6f648d8921e?n=10000) and is almost certainly a result of [this CL](https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3264212) which removes legacy globals. We'll need to find an alternative way to fix this, or patch devtools to bring back the globals.
https://github.com/electron/electron/issues/32702
https://github.com/electron/electron/pull/32829
fe43296f7fd11171ebd73c0e6d248b9c6da5279d
84cf685e761b2dd22f064e0dbf33b290bbec5fc0
2022-02-01T15:03:25Z
c++
2022-02-17T05:59:13Z
patches/devtools_frontend/fix_expose_globals_to_allow_patching_devtools_dock.patch
closed
electron/electron
https://github.com/electron/electron
32,702
[Bug]: `mainWindow.webContents.openDevTools` modes no longer work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version 12.2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior `mainWindow.webContents.openDevTools()` should be able to pass `{mode}` to set a specific dock position. ### Actual Behavior `mainWindow.webContents.openDevTools()` `mode` value no longer has any effect. To reproduce, add: ``` mainWindow.webContents.openDevTools({ mode: 'bottom' }) ``` to `createWindow` in the default Fiddle. Observe that it opens on the right side instead of the bottom. ### Testcase Gist URL _No response_ ### Additional Information Error originates [here](https://github.com/electron/electron/blob/b0f315a637b05bc445fc7e6084baa840891c1207/shell/browser/ui/inspectable_web_contents.cc#L589-L592) This was introduced in this [roll](https://chromium.googlesource.com/chromium/src/+log/98.0.4706.0..98.0.4758.9?n=10000&pretty=full), which contained this [roll](https://chromium.googlesource.com/devtools/devtools-frontend/+log/1b5567f78aca..b6f648d8921e?n=10000) and is almost certainly a result of [this CL](https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3264212) which removes legacy globals. We'll need to find an alternative way to fix this, or patch devtools to bring back the globals.
https://github.com/electron/electron/issues/32702
https://github.com/electron/electron/pull/32829
fe43296f7fd11171ebd73c0e6d248b9c6da5279d
84cf685e761b2dd22f064e0dbf33b290bbec5fc0
2022-02-01T15:03:25Z
c++
2022-02-17T05:59:13Z
patches/config.json
{ "src/electron/patches/chromium": "src", "src/electron/patches/boringssl": "src/third_party/boringssl/src", "src/electron/patches/webrtc": "src/third_party/webrtc", "src/electron/patches/v8": "src/v8", "src/electron/patches/node": "src/third_party/electron_node", "src/electron/patches/nan": "src/third_party/nan", "src/electron/patches/perfetto": "src/third_party/perfetto", "src/electron/patches/squirrel.mac": "src/third_party/squirrel.mac", "src/electron/patches/Mantle": "src/third_party/squirrel.mac/vendor/Mantle", "src/electron/patches/ReactiveObjC": "src/third_party/squirrel.mac/vendor/ReactiveObjC" }
closed
electron/electron
https://github.com/electron/electron
32,702
[Bug]: `mainWindow.webContents.openDevTools` modes no longer work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version 12.2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior `mainWindow.webContents.openDevTools()` should be able to pass `{mode}` to set a specific dock position. ### Actual Behavior `mainWindow.webContents.openDevTools()` `mode` value no longer has any effect. To reproduce, add: ``` mainWindow.webContents.openDevTools({ mode: 'bottom' }) ``` to `createWindow` in the default Fiddle. Observe that it opens on the right side instead of the bottom. ### Testcase Gist URL _No response_ ### Additional Information Error originates [here](https://github.com/electron/electron/blob/b0f315a637b05bc445fc7e6084baa840891c1207/shell/browser/ui/inspectable_web_contents.cc#L589-L592) This was introduced in this [roll](https://chromium.googlesource.com/chromium/src/+log/98.0.4706.0..98.0.4758.9?n=10000&pretty=full), which contained this [roll](https://chromium.googlesource.com/devtools/devtools-frontend/+log/1b5567f78aca..b6f648d8921e?n=10000) and is almost certainly a result of [this CL](https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3264212) which removes legacy globals. We'll need to find an alternative way to fix this, or patch devtools to bring back the globals.
https://github.com/electron/electron/issues/32702
https://github.com/electron/electron/pull/32829
fe43296f7fd11171ebd73c0e6d248b9c6da5279d
84cf685e761b2dd22f064e0dbf33b290bbec5fc0
2022-02-01T15:03:25Z
c++
2022-02-17T05:59:13Z
patches/devtools_frontend/.patches
closed
electron/electron
https://github.com/electron/electron
32,702
[Bug]: `mainWindow.webContents.openDevTools` modes no longer work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-beta.3 ### What operating system are you using? macOS ### Operating System Version 12.2 ### What arch are you using? x64 ### Last Known Working Electron version 17.0.0-beta.2 ### Expected Behavior `mainWindow.webContents.openDevTools()` should be able to pass `{mode}` to set a specific dock position. ### Actual Behavior `mainWindow.webContents.openDevTools()` `mode` value no longer has any effect. To reproduce, add: ``` mainWindow.webContents.openDevTools({ mode: 'bottom' }) ``` to `createWindow` in the default Fiddle. Observe that it opens on the right side instead of the bottom. ### Testcase Gist URL _No response_ ### Additional Information Error originates [here](https://github.com/electron/electron/blob/b0f315a637b05bc445fc7e6084baa840891c1207/shell/browser/ui/inspectable_web_contents.cc#L589-L592) This was introduced in this [roll](https://chromium.googlesource.com/chromium/src/+log/98.0.4706.0..98.0.4758.9?n=10000&pretty=full), which contained this [roll](https://chromium.googlesource.com/devtools/devtools-frontend/+log/1b5567f78aca..b6f648d8921e?n=10000) and is almost certainly a result of [this CL](https://chromium-review.googlesource.com/c/devtools/devtools-frontend/+/3264212) which removes legacy globals. We'll need to find an alternative way to fix this, or patch devtools to bring back the globals.
https://github.com/electron/electron/issues/32702
https://github.com/electron/electron/pull/32829
fe43296f7fd11171ebd73c0e6d248b9c6da5279d
84cf685e761b2dd22f064e0dbf33b290bbec5fc0
2022-02-01T15:03:25Z
c++
2022-02-17T05:59:13Z
patches/devtools_frontend/fix_expose_globals_to_allow_patching_devtools_dock.patch
closed
electron/electron
https://github.com/electron/electron
32,884
[Bug]: stale process with high cpu usage on windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18 nightly, 17.0.0, 15.3.4, 13.6.3 ### What operating system are you using? Windows ### Operating System Version Win 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 12.1.2 ### Expected Behavior When I quit Electron, all processes (main, renderer, gpu) are terminated. ### Actual Behavior When the renderer process is busy during application shutdown, it gets stuck in some weird state and doesn't terminate. Even after work is finished, it remains consuming a complete thread of CPU power. ### Testcase Gist URL https://gist.github.com/3358b37700ca6fb8b7952ff1d72a209b ### Additional Information In the fiddle the main process terminates while the renderer process is kept busy. This augments the race condition causing a stale renderer process (let's say in 9 of 10 cases). If you change the timeouts so that the renderer has a chance to finish work before it gets shut down, all processes quit as expected. I tracked down the first affected version to be 13.0.0-beta.21 resp. 14.0.0-nightly.20210426. Both include a Chromium roll which introduced this issue: - E14 https://github.com/electron/electron/pull/28462 - E13 https://github.com/electron/electron/pull/28660 Halting the process and analyzing the stacktraces, all share the Chromium method `RequestNewLayerTreeFrameSink`. Please find more discussion around that on Slack. Only Windows seems to be affected, both 32 and 64bit. **This issue does not occur with renderer sandbox enabled.** Comment from Milan regarding sandbox: When sandboxed, the renderer processes are enclosed in a win32 job object, which has the `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` flag set, this forces them to be killed when the main process is gone. There was an attempt to do this for non-sandboxed renderers as well (without setting any other limitations through the win32 job object), however it got reverted as it caused some regression caught by tests. Possibly related: #29056. Unhappy users: https://answers.microsoft.com/en-us/skype/forum/sk_sign-sk_out-sk_win10/high-cpu-usage-after-signing-out-and-then-quitting/8cf5f9d1-00a7-4d4b-991e-96993be2f10b cc @dsanders11 @zarubond @deepak1556
https://github.com/electron/electron/issues/32884
https://github.com/electron/electron/pull/32888
36e730da9367b6e75e9fed882b9e8d652226919d
b1463d2da138dcbc20d87cf31b9807d697690592
2022-02-14T10:32:23Z
c++
2022-02-18T05:02:22Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_ui_factory.h" #include "ui/gtk/gtk_util.h" #include "ui/ozone/public/ozone_platform.h" #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts( const content::MainFunctionParams& params) : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::PreEarlyInitialization(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) screen_ = views::CreateDesktopScreen(); display::Screen::SetScreenInstance(screen_.get()); #if BUILDFLAG(IS_LINUX) views::LinuxUI::instance()->UpdateDeviceScaleFactor(); #endif #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = BuildGtkUi(); linux_ui->Initialize(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); views::LinuxUI::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareMessageLoop(); node_bindings_->RunMessageLoop(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::DictionaryValue()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure(run_loop->QuitClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(chrome::DIR_USER_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,884
[Bug]: stale process with high cpu usage on windows
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18 nightly, 17.0.0, 15.3.4, 13.6.3 ### What operating system are you using? Windows ### Operating System Version Win 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 12.1.2 ### Expected Behavior When I quit Electron, all processes (main, renderer, gpu) are terminated. ### Actual Behavior When the renderer process is busy during application shutdown, it gets stuck in some weird state and doesn't terminate. Even after work is finished, it remains consuming a complete thread of CPU power. ### Testcase Gist URL https://gist.github.com/3358b37700ca6fb8b7952ff1d72a209b ### Additional Information In the fiddle the main process terminates while the renderer process is kept busy. This augments the race condition causing a stale renderer process (let's say in 9 of 10 cases). If you change the timeouts so that the renderer has a chance to finish work before it gets shut down, all processes quit as expected. I tracked down the first affected version to be 13.0.0-beta.21 resp. 14.0.0-nightly.20210426. Both include a Chromium roll which introduced this issue: - E14 https://github.com/electron/electron/pull/28462 - E13 https://github.com/electron/electron/pull/28660 Halting the process and analyzing the stacktraces, all share the Chromium method `RequestNewLayerTreeFrameSink`. Please find more discussion around that on Slack. Only Windows seems to be affected, both 32 and 64bit. **This issue does not occur with renderer sandbox enabled.** Comment from Milan regarding sandbox: When sandboxed, the renderer processes are enclosed in a win32 job object, which has the `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` flag set, this forces them to be killed when the main process is gone. There was an attempt to do this for non-sandboxed renderers as well (without setting any other limitations through the win32 job object), however it got reverted as it caused some regression caught by tests. Possibly related: #29056. Unhappy users: https://answers.microsoft.com/en-us/skype/forum/sk_sign-sk_out-sk_win10/high-cpu-usage-after-signing-out-and-then-quitting/8cf5f9d1-00a7-4d4b-991e-96993be2f10b cc @dsanders11 @zarubond @deepak1556
https://github.com/electron/electron/issues/32884
https://github.com/electron/electron/pull/32888
36e730da9367b6e75e9fed882b9e8d652226919d
b1463d2da138dcbc20d87cf31b9807d697690592
2022-02-14T10:32:23Z
c++
2022-02-18T05:02:22Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_ui_factory.h" #include "ui/gtk/gtk_util.h" #include "ui/ozone/public/ozone_platform.h" #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts( const content::MainFunctionParams& params) : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::PreEarlyInitialization(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) screen_ = views::CreateDesktopScreen(); display::Screen::SetScreenInstance(screen_.get()); #if BUILDFLAG(IS_LINUX) views::LinuxUI::instance()->UpdateDeviceScaleFactor(); #endif #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = BuildGtkUi(); linux_ui->Initialize(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); views::LinuxUI::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareMessageLoop(); node_bindings_->RunMessageLoop(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::DictionaryValue()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure(run_loop->QuitClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(chrome::DIR_USER_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,463
[Bug]: setAsDefaultProtocolClient sets wrong command
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.7 ### What operating system are you using? Windows ### Operating System Version Windows 10 Build 19043 ### What arch are you using? x64 ### Last Known Working Electron version 13.1.2 ### Expected Behavior `app.setAsDefaultProtocolClient(protocol, process.execPath, [path.resolve(process.argv[1]), '--arg']);` to work as expected. ### Actual Behavior electron will put quotes around the entire list of arguments instead of each individually (if necessary), so the generated command is something like "C:\example\node_modules\electron\dist\electron.exe" "c:\example --arg" "%1" which then leads to an error "Unable to find Electron app at c:\example --args". ### Testcase Gist URL !!! Please note that by the nature of setAsDefaultProtocolClient this testcase will make a systemwide setting! https://gist.github.com/a1f2fdbe04624b6f7a6877a89581143c ### Additional Information This was almost certainly introduced by the "fix" for https://github.com/electron/electron/issues/32141
https://github.com/electron/electron/issues/32463
https://github.com/electron/electron/pull/32953
9d72c8b0ad2ee41541b01ce6594012b40d869f0b
bdad6335c4e18aecbb3c4f3176fc100e542f0477
2022-01-13T14:53:01Z
c++
2022-02-21T07:43:27Z
shell/browser/browser_win.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/browser.h" // must come before other includes. fixes bad #defines from <shlwapi.h>. #include "base/win/shlwapi.h" // NOLINT(build/include_order) #include <windows.h> // NOLINT(build/include_order) #include <atlbase.h> // NOLINT(build/include_order) #include <shlobj.h> // NOLINT(build/include_order) #include <shobjidl.h> // NOLINT(build/include_order) #include "base/base_paths.h" #include "base/file_version_info.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "base/win/registry.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "chrome/browser/icon_manager.h" #include "electron/electron_version.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/badging/badge_manager.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/ui/message_box.h" #include "shell/browser/ui/win/jump_list.h" #include "shell/browser/window_list.h" #include "shell/common/application_info.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/arguments.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/skia_util.h" #include "skia/ext/legacy_display_globals.h" #include "third_party/skia/include/core/SkFont.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/keycodes/keyboard_code_conversion_win.h" #include "ui/strings/grit/ui_strings.h" namespace electron { namespace { bool GetProcessExecPath(std::wstring* exe) { base::FilePath path; if (!base::PathService::Get(base::FILE_EXE, &path)) { return false; } *exe = path.value(); return true; } bool GetProtocolLaunchPath(gin::Arguments* args, std::wstring* exe) { if (!args->GetNext(exe) && !GetProcessExecPath(exe)) { return false; } // Read in optional args arg std::vector<std::wstring> launch_args; if (args->GetNext(&launch_args) && !launch_args.empty()) *exe = base::StringPrintf(L"\"%ls\" \"%ls\" \"%%1\"", exe->c_str(), base::JoinString(launch_args, L" ").c_str()); else *exe = base::StringPrintf(L"\"%ls\" \"%%1\"", exe->c_str()); return true; } // Windows treats a given scheme as an Internet scheme only if its registry // entry has a "URL Protocol" key. Check this, otherwise we allow ProgIDs to be // used as custom protocols which leads to security bugs. bool IsValidCustomProtocol(const std::wstring& scheme) { if (scheme.empty()) return false; base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, scheme.c_str(), KEY_QUERY_VALUE); return cmd_key.Valid() && cmd_key.HasValue(L"URL Protocol"); } // Helper for GetApplicationInfoForProtocol(). // takes in an assoc_str // (https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/ne-shlwapi-assocstr) // and returns the application name, icon and path that handles the protocol. // // Windows 8 introduced a new protocol->executable binding system which cannot // be retrieved in the HKCR registry subkey method implemented below. We call // AssocQueryString with the new Win8-only flag ASSOCF_IS_PROTOCOL instead. std::wstring GetAppInfoHelperForProtocol(ASSOCSTR assoc_str, const GURL& url) { const std::wstring url_scheme = base::ASCIIToWide(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) return std::wstring(); wchar_t out_buffer[1024]; DWORD buffer_size = base::size(out_buffer); HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL, assoc_str, url_scheme.c_str(), NULL, out_buffer, &buffer_size); if (FAILED(hr)) { DLOG(WARNING) << "AssocQueryString failed!"; return std::wstring(); } return std::wstring(out_buffer); } void OnIconDataAvailable(const base::FilePath& app_path, const std::wstring& app_display_name, gin_helper::Promise<gin_helper::Dictionary> promise, gfx::Image icon) { if (!icon.IsEmpty()) { v8::HandleScope scope(promise.isolate()); gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate()); dict.Set("path", app_path); dict.Set("name", app_display_name); dict.Set("icon", icon); promise.Resolve(dict); } else { promise.RejectWithErrorMessage("Failed to get file icon."); } } std::wstring GetAppDisplayNameForProtocol(const GURL& url) { return GetAppInfoHelperForProtocol(ASSOCSTR_FRIENDLYAPPNAME, url); } std::wstring GetAppPathForProtocol(const GURL& url) { return GetAppInfoHelperForProtocol(ASSOCSTR_EXECUTABLE, url); } std::wstring GetAppForProtocolUsingRegistry(const GURL& url) { const std::wstring url_scheme = base::ASCIIToWide(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) return std::wstring(); // First, try and extract the application's display name. std::wstring command_to_launch; base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, url_scheme.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } // Otherwise, parse the command line in the registry, and return the basename // of the program path if it exists. const std::wstring cmd_key_path = url_scheme + L"\\shell\\open\\command"; base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return std::wstring(); } bool FormatCommandLineString(std::wstring* exe, const std::vector<std::u16string>& launch_args) { if (exe->empty() && !GetProcessExecPath(exe)) { return false; } if (!launch_args.empty()) { std::u16string joined_launch_args = base::JoinString(launch_args, u" "); *exe = base::StringPrintf(L"%ls %ls", exe->c_str(), base::as_wcstr(joined_launch_args)); } return true; } // Helper for GetLoginItemSettings(). // iterates over all the entries in a windows registry path and returns // a list of launchItem with matching paths to our application. // if a launchItem with a matching path also has a matching entry within the // startup_approved_key_path, set executable_will_launch_at_login to be `true` std::vector<Browser::LaunchItem> GetLoginItemSettingsHelper( base::win::RegistryValueIterator* it, boolean* executable_will_launch_at_login, std::wstring scope, const Browser::LoginItemSettings& options) { std::vector<Browser::LaunchItem> launch_items; base::FilePath lookup_exe_path; if (options.path.empty()) { std::wstring process_exe_path; GetProcessExecPath(&process_exe_path); lookup_exe_path = base::CommandLine::FromString(process_exe_path).GetProgram(); } else { lookup_exe_path = base::CommandLine::FromString(base::as_wcstr(options.path)) .GetProgram(); } if (!lookup_exe_path.empty()) { while (it->Valid()) { base::CommandLine registry_launch_cmd = base::CommandLine::FromString(it->Value()); base::FilePath registry_launch_path = registry_launch_cmd.GetProgram(); bool exe_match = base::FilePath::CompareEqualIgnoreCase( lookup_exe_path.value(), registry_launch_path.value()); // add launch item to vector if it has a matching path (case-insensitive) if (exe_match) { Browser::LaunchItem launch_item; launch_item.name = it->Name(); launch_item.path = registry_launch_path.value(); launch_item.args = registry_launch_cmd.GetArgs(); launch_item.scope = scope; launch_item.enabled = true; // attempt to update launch_item.enabled if there is a matching key // value entry in the StartupApproved registry HKEY hkey; // StartupApproved registry path LPCTSTR path = TEXT( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp" "roved\\Run"); LONG res; if (scope == L"user") { res = RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_QUERY_VALUE, &hkey); } else { res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hkey); } if (res == ERROR_SUCCESS) { DWORD type, size; wchar_t startup_binary[12]; LONG result = RegQueryValueEx(hkey, it->Name(), nullptr, &type, reinterpret_cast<BYTE*>(&startup_binary), &(size = sizeof(startup_binary))); if (result == ERROR_SUCCESS) { if (type == REG_BINARY) { // any other binary other than this indicates that the program is // not set to launch at login wchar_t binary_accepted[12] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; wchar_t binary_accepted_alt[12] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; std::string reg_binary(reinterpret_cast<char*>(binary_accepted)); std::string reg_binary_alt( reinterpret_cast<char*>(binary_accepted_alt)); std::string reg_startup_binary( reinterpret_cast<char*>(startup_binary)); launch_item.enabled = (reg_startup_binary == reg_binary) || (reg_startup_binary == reg_binary_alt); } } } *executable_will_launch_at_login = *executable_will_launch_at_login || launch_item.enabled; launch_items.push_back(launch_item); } it->operator++(); } } return launch_items; } std::unique_ptr<FileVersionInfo> FetchFileVersionInfo() { base::FilePath path; if (base::PathService::Get(base::FILE_EXE, &path)) { base::ThreadRestrictions::ScopedAllowIO allow_io; return FileVersionInfo::CreateFileVersionInfo(path); } return std::unique_ptr<FileVersionInfo>(); } } // namespace Browser::UserTask::UserTask() = default; Browser::UserTask::UserTask(const UserTask&) = default; Browser::UserTask::~UserTask() = default; void GetFileIcon(const base::FilePath& path, v8::Isolate* isolate, base::CancelableTaskTracker* cancelable_task_tracker_, const std::wstring app_display_name, gin_helper::Promise<gin_helper::Dictionary> promise) { base::FilePath normalized_path = path.NormalizePathSeparators(); IconLoader::IconSize icon_size = IconLoader::IconSize::LARGE; auto* icon_manager = ElectronBrowserMainParts::Get()->GetIconManager(); gfx::Image* icon = icon_manager->LookupIconFromFilepath(normalized_path, icon_size, 1.0f); if (icon) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("icon", *icon); dict.Set("name", app_display_name); dict.Set("path", normalized_path); promise.Resolve(dict); } else { icon_manager->LoadIcon(normalized_path, icon_size, 1.0f, base::BindOnce(&OnIconDataAvailable, normalized_path, app_display_name, std::move(promise)), cancelable_task_tracker_); } } void GetApplicationInfoForProtocolUsingRegistry( v8::Isolate* isolate, const GURL& url, gin_helper::Promise<gin_helper::Dictionary> promise, base::CancelableTaskTracker* cancelable_task_tracker_) { base::FilePath app_path; const std::wstring url_scheme = base::ASCIIToWide(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) { promise.RejectWithErrorMessage("invalid url_scheme"); return; } std::wstring command_to_launch; const std::wstring cmd_key_path = url_scheme + L"\\shell\\open\\command"; base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); app_path = command_line.GetProgram(); } else { promise.RejectWithErrorMessage( "Unable to retrieve installation path to app"); return; } const std::wstring app_display_name = GetAppForProtocolUsingRegistry(url); if (app_display_name.empty()) { promise.RejectWithErrorMessage( "Unable to retrieve application display name"); return; } GetFileIcon(app_path, isolate, cancelable_task_tracker_, app_display_name, std::move(promise)); } // resolves `Promise<Object>` - Resolve with an object containing the following: // * `icon` NativeImage - the display icon of the app handling the protocol. // * `path` String - installation path of the app handling the protocol. // * `name` String - display name of the app handling the protocol. void GetApplicationInfoForProtocolUsingAssocQuery( v8::Isolate* isolate, const GURL& url, gin_helper::Promise<gin_helper::Dictionary> promise, base::CancelableTaskTracker* cancelable_task_tracker_) { std::wstring app_path = GetAppPathForProtocol(url); if (app_path.empty()) { promise.RejectWithErrorMessage( "Unable to retrieve installation path to app"); return; } std::wstring app_display_name = GetAppDisplayNameForProtocol(url); if (app_display_name.empty()) { promise.RejectWithErrorMessage("Unable to retrieve display name of app"); return; } base::FilePath app_path_file_path = base::FilePath(app_path); GetFileIcon(app_path_file_path, isolate, cancelable_task_tracker_, app_display_name, std::move(promise)); } void Browser::AddRecentDocument(const base::FilePath& path) { CComPtr<IShellItem> item; HRESULT hr = SHCreateItemFromParsingName(path.value().c_str(), NULL, IID_PPV_ARGS(&item)); if (SUCCEEDED(hr)) { SHARDAPPIDINFO info; info.psi = item; info.pszAppID = GetAppUserModelID(); SHAddToRecentDocs(SHARD_APPIDINFO, &info); } } void Browser::ClearRecentDocuments() { SHAddToRecentDocs(SHARD_APPIDINFO, nullptr); } void Browser::SetAppUserModelID(const std::wstring& name) { electron::SetAppUserModelID(name); } bool Browser::SetUserTasks(const std::vector<UserTask>& tasks) { JumpList jump_list(GetAppUserModelID()); if (!jump_list.Begin()) return false; JumpListCategory category; category.type = JumpListCategory::Type::kTasks; category.items.reserve(tasks.size()); JumpListItem item; item.type = JumpListItem::Type::kTask; for (const auto& task : tasks) { item.title = task.title; item.path = task.program; item.arguments = task.arguments; item.icon_path = task.icon_path; item.icon_index = task.icon_index; item.description = task.description; item.working_dir = task.working_dir; category.items.push_back(item); } jump_list.AppendCategory(category); return jump_list.Commit(); } bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol, gin::Arguments* args) { if (protocol.empty()) return false; // Main Registry Key HKEY root = HKEY_CURRENT_USER; std::wstring keyPath = L"Software\\Classes\\"; // Command Key std::wstring wprotocol = base::UTF8ToWide(protocol); std::wstring shellPath = wprotocol + L"\\shell"; std::wstring cmdPath = keyPath + shellPath + L"\\open\\command"; base::win::RegKey classesKey; base::win::RegKey commandKey; if (FAILED(classesKey.Open(root, keyPath.c_str(), KEY_ALL_ACCESS))) // Classes key doesn't exist, that's concerning, but I guess // we're not the default handler return true; if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS))) // Key doesn't even exist, we can confirm that it is not set return true; std::wstring keyVal; if (FAILED(commandKey.ReadValue(L"", &keyVal))) // Default value not set, we can confirm that it is not set return true; std::wstring exe; if (!GetProtocolLaunchPath(args, &exe)) return false; if (keyVal == exe) { // Let's kill the key if (FAILED(classesKey.DeleteKey(shellPath.c_str()))) return false; // Let's clean up after ourselves base::win::RegKey protocolKey; std::wstring protocolPath = keyPath + wprotocol; if (SUCCEEDED( protocolKey.Open(root, protocolPath.c_str(), KEY_ALL_ACCESS))) { protocolKey.DeleteValue(L"URL Protocol"); // Overwrite the default value to be empty, we can't delete it right away protocolKey.WriteValue(L"", L""); protocolKey.DeleteValue(L""); } // If now empty, delete the whole key classesKey.DeleteEmptyKey(wprotocol.c_str()); return true; } else { return true; } } bool Browser::SetAsDefaultProtocolClient(const std::string& protocol, gin::Arguments* args) { // HKEY_CLASSES_ROOT // $PROTOCOL // (Default) = "URL:$NAME" // URL Protocol = "" // shell // open // command // (Default) = "$COMMAND" "%1" // // However, the "HKEY_CLASSES_ROOT" key can only be written by the // Administrator user. So, we instead write to "HKEY_CURRENT_USER\ // Software\Classes", which is inherited by "HKEY_CLASSES_ROOT" // anyway, and can be written by unprivileged users. if (protocol.empty()) return false; std::wstring exe; if (!GetProtocolLaunchPath(args, &exe)) return false; // Main Registry Key HKEY root = HKEY_CURRENT_USER; std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol); std::wstring urlDecl = base::UTF8ToWide("URL:" + protocol); // Command Key std::wstring cmdPath = keyPath + L"\\shell\\open\\command"; // Write information to registry base::win::RegKey key(root, keyPath.c_str(), KEY_ALL_ACCESS); if (FAILED(key.WriteValue(L"URL Protocol", L"")) || FAILED(key.WriteValue(L"", urlDecl.c_str()))) return false; base::win::RegKey commandKey(root, cmdPath.c_str(), KEY_ALL_ACCESS); if (FAILED(commandKey.WriteValue(L"", exe.c_str()))) return false; return true; } bool Browser::IsDefaultProtocolClient(const std::string& protocol, gin::Arguments* args) { if (protocol.empty()) return false; std::wstring exe; if (!GetProtocolLaunchPath(args, &exe)) return false; // Main Registry Key HKEY root = HKEY_CURRENT_USER; std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol); // Command Key std::wstring cmdPath = keyPath + L"\\shell\\open\\command"; base::win::RegKey key; base::win::RegKey commandKey; if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS))) // Key doesn't exist, we can confirm that it is not set return false; if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS))) // Key doesn't exist, we can confirm that it is not set return false; std::wstring keyVal; if (FAILED(commandKey.ReadValue(L"", &keyVal))) // Default value not set, we can confirm that it is not set return false; // Default value is the same as current file path return keyVal == exe; } std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) { // Windows 8 or above has a new protocol association query. if (base::win::GetVersion() >= base::win::Version::WIN8) { std::wstring application_name = GetAppDisplayNameForProtocol(url); if (!application_name.empty()) return base::WideToUTF16(application_name); } return base::WideToUTF16(GetAppForProtocolUsingRegistry(url)); } v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol( v8::Isolate* isolate, const GURL& url) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // Windows 8 or above has a new protocol association query. if (base::win::GetVersion() >= base::win::Version::WIN8) { GetApplicationInfoForProtocolUsingAssocQuery( isolate, url, std::move(promise), &cancelable_task_tracker_); return handle; } GetApplicationInfoForProtocolUsingRegistry(isolate, url, std::move(promise), &cancelable_task_tracker_); return handle; } bool Browser::SetBadgeCount(absl::optional<int> count) { absl::optional<std::string> badge_content; if (count.has_value() && count.value() == 0) { badge_content = absl::nullopt; } else { badge_content = badging::BadgeManager::GetBadgeString(count); } // There are 3 different cases when the badge has a value: // 1. |contents| is between 1 and 99 inclusive => Set the accessibility text // to a pluralized notification count (e.g. 4 Unread Notifications). // 2. |contents| is greater than 99 => Set the accessibility text to // More than |kMaxBadgeContent| unread notifications, so the // accessibility text matches what is displayed on the badge (e.g. More // than 99 notifications). // 3. The badge is set to 'flag' => Set the accessibility text to something // less specific (e.g. Unread Notifications). std::string badge_alt_string; if (count.has_value()) { badge_count_ = count.value(); badge_alt_string = (uint64_t)badge_count_ <= badging::kMaxBadgeContent // Case 1. ? l10n_util::GetPluralStringFUTF8( IDS_BADGE_UNREAD_NOTIFICATIONS, badge_count_) // Case 2. : l10n_util::GetPluralStringFUTF8( IDS_BADGE_UNREAD_NOTIFICATIONS_SATURATED, badging::kMaxBadgeContent); } else { // Case 3. badge_alt_string = l10n_util::GetStringUTF8(IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED); badge_count_ = 0; } for (auto* window : WindowList::GetWindows()) { // On Windows set the badge on the first window found. UpdateBadgeContents(window->GetAcceleratedWidget(), badge_content, badge_alt_string); } return true; } void Browser::UpdateBadgeContents( HWND hwnd, const absl::optional<std::string>& badge_content, const std::string& badge_alt_string) { SkBitmap badge; if (badge_content) { std::string content = badge_content.value(); constexpr int kOverlayIconSize = 16; // This is the color used by the Windows 10 Badge API, for platform // consistency. constexpr int kBackgroundColor = SkColorSetRGB(0x26, 0x25, 0x2D); constexpr int kForegroundColor = SK_ColorWHITE; constexpr int kRadius = kOverlayIconSize / 2; // The minimum gap to have between our content and the edge of the badge. constexpr int kMinMargin = 3; // The amount of space we have to render the icon. constexpr int kMaxBounds = kOverlayIconSize - 2 * kMinMargin; constexpr int kMaxTextSize = 24; // Max size for our text. constexpr int kMinTextSize = 7; // Min size for our text. badge.allocN32Pixels(kOverlayIconSize, kOverlayIconSize); SkCanvas canvas(badge, skia::LegacyDisplayGlobals::GetSkSurfaceProps()); SkPaint paint; paint.setAntiAlias(true); paint.setColor(kBackgroundColor); canvas.clear(SK_ColorTRANSPARENT); canvas.drawCircle(kRadius, kRadius, kRadius, paint); paint.reset(); paint.setColor(kForegroundColor); SkFont font; SkRect bounds; int text_size = kMaxTextSize; // Find the largest |text_size| larger than |kMinTextSize| in which // |content| fits into our 16x16px icon, with margins. do { font.setSize(text_size--); font.measureText(content.c_str(), content.size(), SkTextEncoding::kUTF8, &bounds); } while (text_size >= kMinTextSize && (bounds.width() > kMaxBounds || bounds.height() > kMaxBounds)); canvas.drawSimpleText( content.c_str(), content.size(), SkTextEncoding::kUTF8, kRadius - bounds.width() / 2 - bounds.x(), kRadius - bounds.height() / 2 - bounds.y(), font, paint); } taskbar_host_.SetOverlayIcon(hwnd, badge, badge_alt_string); } void Browser::SetLoginItemSettings(LoginItemSettings settings) { std::wstring key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_ALL_ACCESS); std::wstring startup_approved_key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved" L"\\Run"; base::win::RegKey startup_approved_key( HKEY_CURRENT_USER, startup_approved_key_path.c_str(), KEY_ALL_ACCESS); PCWSTR key_name = !settings.name.empty() ? settings.name.c_str() : GetAppUserModelID(); if (settings.open_at_login) { std::wstring exe = base::UTF16ToWide(settings.path); if (FormatCommandLineString(&exe, settings.args)) { key.WriteValue(key_name, exe.c_str()); if (settings.enabled) { startup_approved_key.DeleteValue(key_name); } else { HKEY hard_key; LPCTSTR path = TEXT( "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp" "roved\\Run"); LONG res = RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hard_key); if (res == ERROR_SUCCESS) { UCHAR disable_startup_binary[] = {0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; RegSetValueEx(hard_key, key_name, 0, REG_BINARY, reinterpret_cast<const BYTE*>(disable_startup_binary), sizeof(disable_startup_binary)); } } } } else { // if open at login is false, delete both values startup_approved_key.DeleteValue(key_name); key.DeleteValue(key_name); } } Browser::LoginItemSettings Browser::GetLoginItemSettings( const LoginItemSettings& options) { LoginItemSettings settings; std::wstring keyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; base::win::RegKey key(HKEY_CURRENT_USER, keyPath.c_str(), KEY_ALL_ACCESS); std::wstring keyVal; // keep old openAtLogin behaviour if (!FAILED(key.ReadValue(GetAppUserModelID(), &keyVal))) { std::wstring exe = base::UTF16ToWide(options.path); if (FormatCommandLineString(&exe, options.args)) { settings.open_at_login = keyVal == exe; } } // iterate over current user and machine registries and populate launch items // if there exists a launch entry with property enabled=='true', // set executable_will_launch_at_login to 'true'. boolean executable_will_launch_at_login = false; std::vector<Browser::LaunchItem> launch_items; base::win::RegistryValueIterator hkcu_iterator(HKEY_CURRENT_USER, keyPath.c_str()); base::win::RegistryValueIterator hklm_iterator(HKEY_LOCAL_MACHINE, keyPath.c_str()); launch_items = GetLoginItemSettingsHelper( &hkcu_iterator, &executable_will_launch_at_login, L"user", options); std::vector<Browser::LaunchItem> launch_items_hklm = GetLoginItemSettingsHelper(&hklm_iterator, &executable_will_launch_at_login, L"machine", options); launch_items.insert(launch_items.end(), launch_items_hklm.begin(), launch_items_hklm.end()); settings.executable_will_launch_at_login = executable_will_launch_at_login; settings.launch_items = launch_items; return settings; } PCWSTR Browser::GetAppUserModelID() { return GetRawAppUserModelID(); } std::string Browser::GetExecutableFileVersion() const { base::FilePath path; if (base::PathService::Get(base::FILE_EXE, &path)) { base::ThreadRestrictions::ScopedAllowIO allow_io; std::unique_ptr<FileVersionInfo> version_info = FetchFileVersionInfo(); return base::UTF16ToUTF8(version_info->product_version()); } return ELECTRON_VERSION_STRING; } std::string Browser::GetExecutableFileProductName() const { return GetApplicationName(); } bool Browser::IsEmojiPanelSupported() { // emoji picker is supported on Windows 10's Spring 2018 update & above. return base::win::GetVersion() >= base::win::Version::WIN10_RS4; } void Browser::ShowEmojiPanel() { // This sends Windows Key + '.' (both keydown and keyup events). // "SendInput" is used because Windows needs to receive these events and // open the Emoji picker. INPUT input[4] = {}; input[0].type = INPUT_KEYBOARD; input[0].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND); input[1].type = INPUT_KEYBOARD; input[1].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD); input[2].type = INPUT_KEYBOARD; input[2].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND); input[2].ki.dwFlags |= KEYEVENTF_KEYUP; input[3].type = INPUT_KEYBOARD; input[3].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD); input[3].ki.dwFlags |= KEYEVENTF_KEYUP; ::SendInput(4, input, sizeof(INPUT)); } void Browser::ShowAboutPanel() { base::Value dict(base::Value::Type::DICTIONARY); std::string aboutMessage = ""; gfx::ImageSkia image; // grab defaults from Windows .EXE file std::unique_ptr<FileVersionInfo> exe_info = FetchFileVersionInfo(); dict.SetStringKey("applicationName", exe_info->file_description()); dict.SetStringKey("applicationVersion", exe_info->product_version()); if (about_panel_options_.is_dict()) { dict.MergeDictionary(&about_panel_options_); } std::vector<std::string> stringOptions = { "applicationName", "applicationVersion", "copyright", "credits"}; const std::string* str; for (std::string opt : stringOptions) { if ((str = dict.FindStringKey(opt))) { aboutMessage.append(*str).append("\r\n"); } } if ((str = dict.FindStringKey("iconPath"))) { base::FilePath path = base::FilePath::FromUTF8Unsafe(*str); electron::util::PopulateImageSkiaRepsFromPath(&image, path); } electron::MessageBoxSettings settings = {}; settings.message = aboutMessage; settings.icon = image; settings.type = electron::MessageBoxType::kInformation; electron::ShowMessageBoxSync(settings); } void Browser::SetAboutPanelOptions(base::DictionaryValue options) { about_panel_options_ = std::move(options); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,463
[Bug]: setAsDefaultProtocolClient sets wrong command
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.7 ### What operating system are you using? Windows ### Operating System Version Windows 10 Build 19043 ### What arch are you using? x64 ### Last Known Working Electron version 13.1.2 ### Expected Behavior `app.setAsDefaultProtocolClient(protocol, process.execPath, [path.resolve(process.argv[1]), '--arg']);` to work as expected. ### Actual Behavior electron will put quotes around the entire list of arguments instead of each individually (if necessary), so the generated command is something like "C:\example\node_modules\electron\dist\electron.exe" "c:\example --arg" "%1" which then leads to an error "Unable to find Electron app at c:\example --args". ### Testcase Gist URL !!! Please note that by the nature of setAsDefaultProtocolClient this testcase will make a systemwide setting! https://gist.github.com/a1f2fdbe04624b6f7a6877a89581143c ### Additional Information This was almost certainly introduced by the "fix" for https://github.com/electron/electron/issues/32141
https://github.com/electron/electron/issues/32463
https://github.com/electron/electron/pull/32953
9d72c8b0ad2ee41541b01ce6594012b40d869f0b
bdad6335c4e18aecbb3c4f3176fc100e542f0477
2022-01-13T14:53:01Z
c++
2022-02-21T07:43:27Z
shell/browser/browser_win.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/browser.h" // must come before other includes. fixes bad #defines from <shlwapi.h>. #include "base/win/shlwapi.h" // NOLINT(build/include_order) #include <windows.h> // NOLINT(build/include_order) #include <atlbase.h> // NOLINT(build/include_order) #include <shlobj.h> // NOLINT(build/include_order) #include <shobjidl.h> // NOLINT(build/include_order) #include "base/base_paths.h" #include "base/file_version_info.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_restrictions.h" #include "base/win/registry.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "chrome/browser/icon_manager.h" #include "electron/electron_version.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/badging/badge_manager.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/ui/message_box.h" #include "shell/browser/ui/win/jump_list.h" #include "shell/browser/window_list.h" #include "shell/common/application_info.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/arguments.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/skia_util.h" #include "skia/ext/legacy_display_globals.h" #include "third_party/skia/include/core/SkFont.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/keycodes/keyboard_code_conversion_win.h" #include "ui/strings/grit/ui_strings.h" namespace electron { namespace { bool GetProcessExecPath(std::wstring* exe) { base::FilePath path; if (!base::PathService::Get(base::FILE_EXE, &path)) { return false; } *exe = path.value(); return true; } bool GetProtocolLaunchPath(gin::Arguments* args, std::wstring* exe) { if (!args->GetNext(exe) && !GetProcessExecPath(exe)) { return false; } // Read in optional args arg std::vector<std::wstring> launch_args; if (args->GetNext(&launch_args) && !launch_args.empty()) *exe = base::StringPrintf(L"\"%ls\" \"%ls\" \"%%1\"", exe->c_str(), base::JoinString(launch_args, L" ").c_str()); else *exe = base::StringPrintf(L"\"%ls\" \"%%1\"", exe->c_str()); return true; } // Windows treats a given scheme as an Internet scheme only if its registry // entry has a "URL Protocol" key. Check this, otherwise we allow ProgIDs to be // used as custom protocols which leads to security bugs. bool IsValidCustomProtocol(const std::wstring& scheme) { if (scheme.empty()) return false; base::win::RegKey cmd_key(HKEY_CLASSES_ROOT, scheme.c_str(), KEY_QUERY_VALUE); return cmd_key.Valid() && cmd_key.HasValue(L"URL Protocol"); } // Helper for GetApplicationInfoForProtocol(). // takes in an assoc_str // (https://docs.microsoft.com/en-us/windows/win32/api/shlwapi/ne-shlwapi-assocstr) // and returns the application name, icon and path that handles the protocol. // // Windows 8 introduced a new protocol->executable binding system which cannot // be retrieved in the HKCR registry subkey method implemented below. We call // AssocQueryString with the new Win8-only flag ASSOCF_IS_PROTOCOL instead. std::wstring GetAppInfoHelperForProtocol(ASSOCSTR assoc_str, const GURL& url) { const std::wstring url_scheme = base::ASCIIToWide(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) return std::wstring(); wchar_t out_buffer[1024]; DWORD buffer_size = base::size(out_buffer); HRESULT hr = AssocQueryString(ASSOCF_IS_PROTOCOL, assoc_str, url_scheme.c_str(), NULL, out_buffer, &buffer_size); if (FAILED(hr)) { DLOG(WARNING) << "AssocQueryString failed!"; return std::wstring(); } return std::wstring(out_buffer); } void OnIconDataAvailable(const base::FilePath& app_path, const std::wstring& app_display_name, gin_helper::Promise<gin_helper::Dictionary> promise, gfx::Image icon) { if (!icon.IsEmpty()) { v8::HandleScope scope(promise.isolate()); gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate()); dict.Set("path", app_path); dict.Set("name", app_display_name); dict.Set("icon", icon); promise.Resolve(dict); } else { promise.RejectWithErrorMessage("Failed to get file icon."); } } std::wstring GetAppDisplayNameForProtocol(const GURL& url) { return GetAppInfoHelperForProtocol(ASSOCSTR_FRIENDLYAPPNAME, url); } std::wstring GetAppPathForProtocol(const GURL& url) { return GetAppInfoHelperForProtocol(ASSOCSTR_EXECUTABLE, url); } std::wstring GetAppForProtocolUsingRegistry(const GURL& url) { const std::wstring url_scheme = base::ASCIIToWide(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) return std::wstring(); // First, try and extract the application's display name. std::wstring command_to_launch; base::win::RegKey cmd_key_name(HKEY_CLASSES_ROOT, url_scheme.c_str(), KEY_READ); if (cmd_key_name.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS && !command_to_launch.empty()) { return command_to_launch; } // Otherwise, parse the command line in the registry, and return the basename // of the program path if it exists. const std::wstring cmd_key_path = url_scheme + L"\\shell\\open\\command"; base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); return command_line.GetProgram().BaseName().value(); } return std::wstring(); } bool FormatCommandLineString(std::wstring* exe, const std::vector<std::u16string>& launch_args) { if (exe->empty() && !GetProcessExecPath(exe)) { return false; } if (!launch_args.empty()) { std::u16string joined_launch_args = base::JoinString(launch_args, u" "); *exe = base::StringPrintf(L"%ls %ls", exe->c_str(), base::as_wcstr(joined_launch_args)); } return true; } // Helper for GetLoginItemSettings(). // iterates over all the entries in a windows registry path and returns // a list of launchItem with matching paths to our application. // if a launchItem with a matching path also has a matching entry within the // startup_approved_key_path, set executable_will_launch_at_login to be `true` std::vector<Browser::LaunchItem> GetLoginItemSettingsHelper( base::win::RegistryValueIterator* it, boolean* executable_will_launch_at_login, std::wstring scope, const Browser::LoginItemSettings& options) { std::vector<Browser::LaunchItem> launch_items; base::FilePath lookup_exe_path; if (options.path.empty()) { std::wstring process_exe_path; GetProcessExecPath(&process_exe_path); lookup_exe_path = base::CommandLine::FromString(process_exe_path).GetProgram(); } else { lookup_exe_path = base::CommandLine::FromString(base::as_wcstr(options.path)) .GetProgram(); } if (!lookup_exe_path.empty()) { while (it->Valid()) { base::CommandLine registry_launch_cmd = base::CommandLine::FromString(it->Value()); base::FilePath registry_launch_path = registry_launch_cmd.GetProgram(); bool exe_match = base::FilePath::CompareEqualIgnoreCase( lookup_exe_path.value(), registry_launch_path.value()); // add launch item to vector if it has a matching path (case-insensitive) if (exe_match) { Browser::LaunchItem launch_item; launch_item.name = it->Name(); launch_item.path = registry_launch_path.value(); launch_item.args = registry_launch_cmd.GetArgs(); launch_item.scope = scope; launch_item.enabled = true; // attempt to update launch_item.enabled if there is a matching key // value entry in the StartupApproved registry HKEY hkey; // StartupApproved registry path LPCTSTR path = TEXT( "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp" "roved\\Run"); LONG res; if (scope == L"user") { res = RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_QUERY_VALUE, &hkey); } else { res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, path, 0, KEY_QUERY_VALUE, &hkey); } if (res == ERROR_SUCCESS) { DWORD type, size; wchar_t startup_binary[12]; LONG result = RegQueryValueEx(hkey, it->Name(), nullptr, &type, reinterpret_cast<BYTE*>(&startup_binary), &(size = sizeof(startup_binary))); if (result == ERROR_SUCCESS) { if (type == REG_BINARY) { // any other binary other than this indicates that the program is // not set to launch at login wchar_t binary_accepted[12] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; wchar_t binary_accepted_alt[12] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; std::string reg_binary(reinterpret_cast<char*>(binary_accepted)); std::string reg_binary_alt( reinterpret_cast<char*>(binary_accepted_alt)); std::string reg_startup_binary( reinterpret_cast<char*>(startup_binary)); launch_item.enabled = (reg_startup_binary == reg_binary) || (reg_startup_binary == reg_binary_alt); } } } *executable_will_launch_at_login = *executable_will_launch_at_login || launch_item.enabled; launch_items.push_back(launch_item); } it->operator++(); } } return launch_items; } std::unique_ptr<FileVersionInfo> FetchFileVersionInfo() { base::FilePath path; if (base::PathService::Get(base::FILE_EXE, &path)) { base::ThreadRestrictions::ScopedAllowIO allow_io; return FileVersionInfo::CreateFileVersionInfo(path); } return std::unique_ptr<FileVersionInfo>(); } } // namespace Browser::UserTask::UserTask() = default; Browser::UserTask::UserTask(const UserTask&) = default; Browser::UserTask::~UserTask() = default; void GetFileIcon(const base::FilePath& path, v8::Isolate* isolate, base::CancelableTaskTracker* cancelable_task_tracker_, const std::wstring app_display_name, gin_helper::Promise<gin_helper::Dictionary> promise) { base::FilePath normalized_path = path.NormalizePathSeparators(); IconLoader::IconSize icon_size = IconLoader::IconSize::LARGE; auto* icon_manager = ElectronBrowserMainParts::Get()->GetIconManager(); gfx::Image* icon = icon_manager->LookupIconFromFilepath(normalized_path, icon_size, 1.0f); if (icon) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); dict.Set("icon", *icon); dict.Set("name", app_display_name); dict.Set("path", normalized_path); promise.Resolve(dict); } else { icon_manager->LoadIcon(normalized_path, icon_size, 1.0f, base::BindOnce(&OnIconDataAvailable, normalized_path, app_display_name, std::move(promise)), cancelable_task_tracker_); } } void GetApplicationInfoForProtocolUsingRegistry( v8::Isolate* isolate, const GURL& url, gin_helper::Promise<gin_helper::Dictionary> promise, base::CancelableTaskTracker* cancelable_task_tracker_) { base::FilePath app_path; const std::wstring url_scheme = base::ASCIIToWide(url.scheme()); if (!IsValidCustomProtocol(url_scheme)) { promise.RejectWithErrorMessage("invalid url_scheme"); return; } std::wstring command_to_launch; const std::wstring cmd_key_path = url_scheme + L"\\shell\\open\\command"; base::win::RegKey cmd_key_exe(HKEY_CLASSES_ROOT, cmd_key_path.c_str(), KEY_READ); if (cmd_key_exe.ReadValue(NULL, &command_to_launch) == ERROR_SUCCESS) { base::CommandLine command_line( base::CommandLine::FromString(command_to_launch)); app_path = command_line.GetProgram(); } else { promise.RejectWithErrorMessage( "Unable to retrieve installation path to app"); return; } const std::wstring app_display_name = GetAppForProtocolUsingRegistry(url); if (app_display_name.empty()) { promise.RejectWithErrorMessage( "Unable to retrieve application display name"); return; } GetFileIcon(app_path, isolate, cancelable_task_tracker_, app_display_name, std::move(promise)); } // resolves `Promise<Object>` - Resolve with an object containing the following: // * `icon` NativeImage - the display icon of the app handling the protocol. // * `path` String - installation path of the app handling the protocol. // * `name` String - display name of the app handling the protocol. void GetApplicationInfoForProtocolUsingAssocQuery( v8::Isolate* isolate, const GURL& url, gin_helper::Promise<gin_helper::Dictionary> promise, base::CancelableTaskTracker* cancelable_task_tracker_) { std::wstring app_path = GetAppPathForProtocol(url); if (app_path.empty()) { promise.RejectWithErrorMessage( "Unable to retrieve installation path to app"); return; } std::wstring app_display_name = GetAppDisplayNameForProtocol(url); if (app_display_name.empty()) { promise.RejectWithErrorMessage("Unable to retrieve display name of app"); return; } base::FilePath app_path_file_path = base::FilePath(app_path); GetFileIcon(app_path_file_path, isolate, cancelable_task_tracker_, app_display_name, std::move(promise)); } void Browser::AddRecentDocument(const base::FilePath& path) { CComPtr<IShellItem> item; HRESULT hr = SHCreateItemFromParsingName(path.value().c_str(), NULL, IID_PPV_ARGS(&item)); if (SUCCEEDED(hr)) { SHARDAPPIDINFO info; info.psi = item; info.pszAppID = GetAppUserModelID(); SHAddToRecentDocs(SHARD_APPIDINFO, &info); } } void Browser::ClearRecentDocuments() { SHAddToRecentDocs(SHARD_APPIDINFO, nullptr); } void Browser::SetAppUserModelID(const std::wstring& name) { electron::SetAppUserModelID(name); } bool Browser::SetUserTasks(const std::vector<UserTask>& tasks) { JumpList jump_list(GetAppUserModelID()); if (!jump_list.Begin()) return false; JumpListCategory category; category.type = JumpListCategory::Type::kTasks; category.items.reserve(tasks.size()); JumpListItem item; item.type = JumpListItem::Type::kTask; for (const auto& task : tasks) { item.title = task.title; item.path = task.program; item.arguments = task.arguments; item.icon_path = task.icon_path; item.icon_index = task.icon_index; item.description = task.description; item.working_dir = task.working_dir; category.items.push_back(item); } jump_list.AppendCategory(category); return jump_list.Commit(); } bool Browser::RemoveAsDefaultProtocolClient(const std::string& protocol, gin::Arguments* args) { if (protocol.empty()) return false; // Main Registry Key HKEY root = HKEY_CURRENT_USER; std::wstring keyPath = L"Software\\Classes\\"; // Command Key std::wstring wprotocol = base::UTF8ToWide(protocol); std::wstring shellPath = wprotocol + L"\\shell"; std::wstring cmdPath = keyPath + shellPath + L"\\open\\command"; base::win::RegKey classesKey; base::win::RegKey commandKey; if (FAILED(classesKey.Open(root, keyPath.c_str(), KEY_ALL_ACCESS))) // Classes key doesn't exist, that's concerning, but I guess // we're not the default handler return true; if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS))) // Key doesn't even exist, we can confirm that it is not set return true; std::wstring keyVal; if (FAILED(commandKey.ReadValue(L"", &keyVal))) // Default value not set, we can confirm that it is not set return true; std::wstring exe; if (!GetProtocolLaunchPath(args, &exe)) return false; if (keyVal == exe) { // Let's kill the key if (FAILED(classesKey.DeleteKey(shellPath.c_str()))) return false; // Let's clean up after ourselves base::win::RegKey protocolKey; std::wstring protocolPath = keyPath + wprotocol; if (SUCCEEDED( protocolKey.Open(root, protocolPath.c_str(), KEY_ALL_ACCESS))) { protocolKey.DeleteValue(L"URL Protocol"); // Overwrite the default value to be empty, we can't delete it right away protocolKey.WriteValue(L"", L""); protocolKey.DeleteValue(L""); } // If now empty, delete the whole key classesKey.DeleteEmptyKey(wprotocol.c_str()); return true; } else { return true; } } bool Browser::SetAsDefaultProtocolClient(const std::string& protocol, gin::Arguments* args) { // HKEY_CLASSES_ROOT // $PROTOCOL // (Default) = "URL:$NAME" // URL Protocol = "" // shell // open // command // (Default) = "$COMMAND" "%1" // // However, the "HKEY_CLASSES_ROOT" key can only be written by the // Administrator user. So, we instead write to "HKEY_CURRENT_USER\ // Software\Classes", which is inherited by "HKEY_CLASSES_ROOT" // anyway, and can be written by unprivileged users. if (protocol.empty()) return false; std::wstring exe; if (!GetProtocolLaunchPath(args, &exe)) return false; // Main Registry Key HKEY root = HKEY_CURRENT_USER; std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol); std::wstring urlDecl = base::UTF8ToWide("URL:" + protocol); // Command Key std::wstring cmdPath = keyPath + L"\\shell\\open\\command"; // Write information to registry base::win::RegKey key(root, keyPath.c_str(), KEY_ALL_ACCESS); if (FAILED(key.WriteValue(L"URL Protocol", L"")) || FAILED(key.WriteValue(L"", urlDecl.c_str()))) return false; base::win::RegKey commandKey(root, cmdPath.c_str(), KEY_ALL_ACCESS); if (FAILED(commandKey.WriteValue(L"", exe.c_str()))) return false; return true; } bool Browser::IsDefaultProtocolClient(const std::string& protocol, gin::Arguments* args) { if (protocol.empty()) return false; std::wstring exe; if (!GetProtocolLaunchPath(args, &exe)) return false; // Main Registry Key HKEY root = HKEY_CURRENT_USER; std::wstring keyPath = base::UTF8ToWide("Software\\Classes\\" + protocol); // Command Key std::wstring cmdPath = keyPath + L"\\shell\\open\\command"; base::win::RegKey key; base::win::RegKey commandKey; if (FAILED(key.Open(root, keyPath.c_str(), KEY_ALL_ACCESS))) // Key doesn't exist, we can confirm that it is not set return false; if (FAILED(commandKey.Open(root, cmdPath.c_str(), KEY_ALL_ACCESS))) // Key doesn't exist, we can confirm that it is not set return false; std::wstring keyVal; if (FAILED(commandKey.ReadValue(L"", &keyVal))) // Default value not set, we can confirm that it is not set return false; // Default value is the same as current file path return keyVal == exe; } std::u16string Browser::GetApplicationNameForProtocol(const GURL& url) { // Windows 8 or above has a new protocol association query. if (base::win::GetVersion() >= base::win::Version::WIN8) { std::wstring application_name = GetAppDisplayNameForProtocol(url); if (!application_name.empty()) return base::WideToUTF16(application_name); } return base::WideToUTF16(GetAppForProtocolUsingRegistry(url)); } v8::Local<v8::Promise> Browser::GetApplicationInfoForProtocol( v8::Isolate* isolate, const GURL& url) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); // Windows 8 or above has a new protocol association query. if (base::win::GetVersion() >= base::win::Version::WIN8) { GetApplicationInfoForProtocolUsingAssocQuery( isolate, url, std::move(promise), &cancelable_task_tracker_); return handle; } GetApplicationInfoForProtocolUsingRegistry(isolate, url, std::move(promise), &cancelable_task_tracker_); return handle; } bool Browser::SetBadgeCount(absl::optional<int> count) { absl::optional<std::string> badge_content; if (count.has_value() && count.value() == 0) { badge_content = absl::nullopt; } else { badge_content = badging::BadgeManager::GetBadgeString(count); } // There are 3 different cases when the badge has a value: // 1. |contents| is between 1 and 99 inclusive => Set the accessibility text // to a pluralized notification count (e.g. 4 Unread Notifications). // 2. |contents| is greater than 99 => Set the accessibility text to // More than |kMaxBadgeContent| unread notifications, so the // accessibility text matches what is displayed on the badge (e.g. More // than 99 notifications). // 3. The badge is set to 'flag' => Set the accessibility text to something // less specific (e.g. Unread Notifications). std::string badge_alt_string; if (count.has_value()) { badge_count_ = count.value(); badge_alt_string = (uint64_t)badge_count_ <= badging::kMaxBadgeContent // Case 1. ? l10n_util::GetPluralStringFUTF8( IDS_BADGE_UNREAD_NOTIFICATIONS, badge_count_) // Case 2. : l10n_util::GetPluralStringFUTF8( IDS_BADGE_UNREAD_NOTIFICATIONS_SATURATED, badging::kMaxBadgeContent); } else { // Case 3. badge_alt_string = l10n_util::GetStringUTF8(IDS_BADGE_UNREAD_NOTIFICATIONS_UNSPECIFIED); badge_count_ = 0; } for (auto* window : WindowList::GetWindows()) { // On Windows set the badge on the first window found. UpdateBadgeContents(window->GetAcceleratedWidget(), badge_content, badge_alt_string); } return true; } void Browser::UpdateBadgeContents( HWND hwnd, const absl::optional<std::string>& badge_content, const std::string& badge_alt_string) { SkBitmap badge; if (badge_content) { std::string content = badge_content.value(); constexpr int kOverlayIconSize = 16; // This is the color used by the Windows 10 Badge API, for platform // consistency. constexpr int kBackgroundColor = SkColorSetRGB(0x26, 0x25, 0x2D); constexpr int kForegroundColor = SK_ColorWHITE; constexpr int kRadius = kOverlayIconSize / 2; // The minimum gap to have between our content and the edge of the badge. constexpr int kMinMargin = 3; // The amount of space we have to render the icon. constexpr int kMaxBounds = kOverlayIconSize - 2 * kMinMargin; constexpr int kMaxTextSize = 24; // Max size for our text. constexpr int kMinTextSize = 7; // Min size for our text. badge.allocN32Pixels(kOverlayIconSize, kOverlayIconSize); SkCanvas canvas(badge, skia::LegacyDisplayGlobals::GetSkSurfaceProps()); SkPaint paint; paint.setAntiAlias(true); paint.setColor(kBackgroundColor); canvas.clear(SK_ColorTRANSPARENT); canvas.drawCircle(kRadius, kRadius, kRadius, paint); paint.reset(); paint.setColor(kForegroundColor); SkFont font; SkRect bounds; int text_size = kMaxTextSize; // Find the largest |text_size| larger than |kMinTextSize| in which // |content| fits into our 16x16px icon, with margins. do { font.setSize(text_size--); font.measureText(content.c_str(), content.size(), SkTextEncoding::kUTF8, &bounds); } while (text_size >= kMinTextSize && (bounds.width() > kMaxBounds || bounds.height() > kMaxBounds)); canvas.drawSimpleText( content.c_str(), content.size(), SkTextEncoding::kUTF8, kRadius - bounds.width() / 2 - bounds.x(), kRadius - bounds.height() / 2 - bounds.y(), font, paint); } taskbar_host_.SetOverlayIcon(hwnd, badge, badge_alt_string); } void Browser::SetLoginItemSettings(LoginItemSettings settings) { std::wstring key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_ALL_ACCESS); std::wstring startup_approved_key_path = L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved" L"\\Run"; base::win::RegKey startup_approved_key( HKEY_CURRENT_USER, startup_approved_key_path.c_str(), KEY_ALL_ACCESS); PCWSTR key_name = !settings.name.empty() ? settings.name.c_str() : GetAppUserModelID(); if (settings.open_at_login) { std::wstring exe = base::UTF16ToWide(settings.path); if (FormatCommandLineString(&exe, settings.args)) { key.WriteValue(key_name, exe.c_str()); if (settings.enabled) { startup_approved_key.DeleteValue(key_name); } else { HKEY hard_key; LPCTSTR path = TEXT( "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApp" "roved\\Run"); LONG res = RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_ALL_ACCESS, &hard_key); if (res == ERROR_SUCCESS) { UCHAR disable_startup_binary[] = {0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; RegSetValueEx(hard_key, key_name, 0, REG_BINARY, reinterpret_cast<const BYTE*>(disable_startup_binary), sizeof(disable_startup_binary)); } } } } else { // if open at login is false, delete both values startup_approved_key.DeleteValue(key_name); key.DeleteValue(key_name); } } Browser::LoginItemSettings Browser::GetLoginItemSettings( const LoginItemSettings& options) { LoginItemSettings settings; std::wstring keyPath = L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"; base::win::RegKey key(HKEY_CURRENT_USER, keyPath.c_str(), KEY_ALL_ACCESS); std::wstring keyVal; // keep old openAtLogin behaviour if (!FAILED(key.ReadValue(GetAppUserModelID(), &keyVal))) { std::wstring exe = base::UTF16ToWide(options.path); if (FormatCommandLineString(&exe, options.args)) { settings.open_at_login = keyVal == exe; } } // iterate over current user and machine registries and populate launch items // if there exists a launch entry with property enabled=='true', // set executable_will_launch_at_login to 'true'. boolean executable_will_launch_at_login = false; std::vector<Browser::LaunchItem> launch_items; base::win::RegistryValueIterator hkcu_iterator(HKEY_CURRENT_USER, keyPath.c_str()); base::win::RegistryValueIterator hklm_iterator(HKEY_LOCAL_MACHINE, keyPath.c_str()); launch_items = GetLoginItemSettingsHelper( &hkcu_iterator, &executable_will_launch_at_login, L"user", options); std::vector<Browser::LaunchItem> launch_items_hklm = GetLoginItemSettingsHelper(&hklm_iterator, &executable_will_launch_at_login, L"machine", options); launch_items.insert(launch_items.end(), launch_items_hklm.begin(), launch_items_hklm.end()); settings.executable_will_launch_at_login = executable_will_launch_at_login; settings.launch_items = launch_items; return settings; } PCWSTR Browser::GetAppUserModelID() { return GetRawAppUserModelID(); } std::string Browser::GetExecutableFileVersion() const { base::FilePath path; if (base::PathService::Get(base::FILE_EXE, &path)) { base::ThreadRestrictions::ScopedAllowIO allow_io; std::unique_ptr<FileVersionInfo> version_info = FetchFileVersionInfo(); return base::UTF16ToUTF8(version_info->product_version()); } return ELECTRON_VERSION_STRING; } std::string Browser::GetExecutableFileProductName() const { return GetApplicationName(); } bool Browser::IsEmojiPanelSupported() { // emoji picker is supported on Windows 10's Spring 2018 update & above. return base::win::GetVersion() >= base::win::Version::WIN10_RS4; } void Browser::ShowEmojiPanel() { // This sends Windows Key + '.' (both keydown and keyup events). // "SendInput" is used because Windows needs to receive these events and // open the Emoji picker. INPUT input[4] = {}; input[0].type = INPUT_KEYBOARD; input[0].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND); input[1].type = INPUT_KEYBOARD; input[1].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD); input[2].type = INPUT_KEYBOARD; input[2].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_COMMAND); input[2].ki.dwFlags |= KEYEVENTF_KEYUP; input[3].type = INPUT_KEYBOARD; input[3].ki.wVk = ui::WindowsKeyCodeForKeyboardCode(ui::VKEY_OEM_PERIOD); input[3].ki.dwFlags |= KEYEVENTF_KEYUP; ::SendInput(4, input, sizeof(INPUT)); } void Browser::ShowAboutPanel() { base::Value dict(base::Value::Type::DICTIONARY); std::string aboutMessage = ""; gfx::ImageSkia image; // grab defaults from Windows .EXE file std::unique_ptr<FileVersionInfo> exe_info = FetchFileVersionInfo(); dict.SetStringKey("applicationName", exe_info->file_description()); dict.SetStringKey("applicationVersion", exe_info->product_version()); if (about_panel_options_.is_dict()) { dict.MergeDictionary(&about_panel_options_); } std::vector<std::string> stringOptions = { "applicationName", "applicationVersion", "copyright", "credits"}; const std::string* str; for (std::string opt : stringOptions) { if ((str = dict.FindStringKey(opt))) { aboutMessage.append(*str).append("\r\n"); } } if ((str = dict.FindStringKey("iconPath"))) { base::FilePath path = base::FilePath::FromUTF8Unsafe(*str); electron::util::PopulateImageSkiaRepsFromPath(&image, path); } electron::MessageBoxSettings settings = {}; settings.message = aboutMessage; settings.icon = image; settings.type = electron::MessageBoxType::kInformation; electron::ShowMessageBoxSync(settings); } void Browser::SetAboutPanelOptions(base::DictionaryValue options) { about_panel_options_ = std::move(options); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,373
[Bug]: BrowserWindow.showInactive Will Restore Maximized Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-alpha.6 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `BrowserWindow.showInactive` should not restore a maximized window ### Actual Behavior `BrowserWindow.showInactive` does restore a maximized window ### Testcase Gist URL https://gist.github.com/9f2c69b089f2155859bb0b439aefb668 ### Additional Information The provided gist is a test so it should be runnable by `bugbot`. I've confirmed the behavior on Windows, macOS seems unaffected, I haven't tested Linux. ~@ckerr, could you test Linux? It might be similar to #32350 where it affects both Windows and Linux but not macOS.~ Root cause may be upstream in Chromium, `ShowInactive` in Electron just passes through to `ShowInactive` on the widget, there's really no logic present.
https://github.com/electron/electron/issues/32373
https://github.com/electron/electron/pull/32870
bdad6335c4e18aecbb3c4f3176fc100e542f0477
069cde09fbae94e18bb1e31ed6235c0761c08315
2022-01-06T22:48:21Z
c++
2022-02-21T09:23:55Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cfisobjc.patch mas-cgdisplayusesforcetogray.patch mas-audiodeviceduck.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_abort_report_np.patch mas_avoid_usage_of_pthread_fchdir_np.patch mas_avoid_usage_of_setapplicationisdaemon_and.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch put_back_deleted_colors_for_autofill.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch chore_use_electron_resources_not_chrome_for_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch ui_gtk_public_header.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch fix_use_electron_generated_resources.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch mas_gate_private_enterprise_APIs.patch load_v8_snapshot_in_browser_process.patch fix_patch_out_permissions_checks_in_exclusive_access.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch feat_add_data_transfer_to_requestsingleinstancelock.patch fix_crash_when_saving_edited_pdf_files.patch
closed
electron/electron
https://github.com/electron/electron
32,373
[Bug]: BrowserWindow.showInactive Will Restore Maximized Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-alpha.6 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `BrowserWindow.showInactive` should not restore a maximized window ### Actual Behavior `BrowserWindow.showInactive` does restore a maximized window ### Testcase Gist URL https://gist.github.com/9f2c69b089f2155859bb0b439aefb668 ### Additional Information The provided gist is a test so it should be runnable by `bugbot`. I've confirmed the behavior on Windows, macOS seems unaffected, I haven't tested Linux. ~@ckerr, could you test Linux? It might be similar to #32350 where it affects both Windows and Linux but not macOS.~ Root cause may be upstream in Chromium, `ShowInactive` in Electron just passes through to `ShowInactive` on the widget, there's really no logic present.
https://github.com/electron/electron/issues/32373
https://github.com/electron/electron/pull/32870
bdad6335c4e18aecbb3c4f3176fc100e542f0477
069cde09fbae94e18bb1e31ed6235c0761c08315
2022-01-06T22:48:21Z
c++
2022-02-21T09:23:55Z
patches/chromium/fix_don_t_restore_maximized_windows_when_calling_showinactive.patch
closed
electron/electron
https://github.com/electron/electron
32,373
[Bug]: BrowserWindow.showInactive Will Restore Maximized Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-alpha.6 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `BrowserWindow.showInactive` should not restore a maximized window ### Actual Behavior `BrowserWindow.showInactive` does restore a maximized window ### Testcase Gist URL https://gist.github.com/9f2c69b089f2155859bb0b439aefb668 ### Additional Information The provided gist is a test so it should be runnable by `bugbot`. I've confirmed the behavior on Windows, macOS seems unaffected, I haven't tested Linux. ~@ckerr, could you test Linux? It might be similar to #32350 where it affects both Windows and Linux but not macOS.~ Root cause may be upstream in Chromium, `ShowInactive` in Electron just passes through to `ShowInactive` on the widget, there's really no logic present.
https://github.com/electron/electron/issues/32373
https://github.com/electron/electron/pull/32870
bdad6335c4e18aecbb3c4f3176fc100e542f0477
069cde09fbae94e18bb1e31ed6235c0761c08315
2022-01-06T22:48:21Z
c++
2022-02-21T09:23:55Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,373
[Bug]: BrowserWindow.showInactive Will Restore Maximized Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-alpha.6 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `BrowserWindow.showInactive` should not restore a maximized window ### Actual Behavior `BrowserWindow.showInactive` does restore a maximized window ### Testcase Gist URL https://gist.github.com/9f2c69b089f2155859bb0b439aefb668 ### Additional Information The provided gist is a test so it should be runnable by `bugbot`. I've confirmed the behavior on Windows, macOS seems unaffected, I haven't tested Linux. ~@ckerr, could you test Linux? It might be similar to #32350 where it affects both Windows and Linux but not macOS.~ Root cause may be upstream in Chromium, `ShowInactive` in Electron just passes through to `ShowInactive` on the widget, there's really no logic present.
https://github.com/electron/electron/issues/32373
https://github.com/electron/electron/pull/32870
bdad6335c4e18aecbb3c4f3176fc100e542f0477
069cde09fbae94e18bb1e31ed6235c0761c08315
2022-01-06T22:48:21Z
c++
2022-02-21T09:23:55Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cfisobjc.patch mas-cgdisplayusesforcetogray.patch mas-audiodeviceduck.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_abort_report_np.patch mas_avoid_usage_of_pthread_fchdir_np.patch mas_avoid_usage_of_setapplicationisdaemon_and.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch put_back_deleted_colors_for_autofill.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch chore_use_electron_resources_not_chrome_for_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch ui_gtk_public_header.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch fix_use_electron_generated_resources.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch mas_gate_private_enterprise_APIs.patch load_v8_snapshot_in_browser_process.patch fix_patch_out_permissions_checks_in_exclusive_access.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch feat_add_data_transfer_to_requestsingleinstancelock.patch fix_crash_when_saving_edited_pdf_files.patch
closed
electron/electron
https://github.com/electron/electron
32,373
[Bug]: BrowserWindow.showInactive Will Restore Maximized Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-alpha.6 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `BrowserWindow.showInactive` should not restore a maximized window ### Actual Behavior `BrowserWindow.showInactive` does restore a maximized window ### Testcase Gist URL https://gist.github.com/9f2c69b089f2155859bb0b439aefb668 ### Additional Information The provided gist is a test so it should be runnable by `bugbot`. I've confirmed the behavior on Windows, macOS seems unaffected, I haven't tested Linux. ~@ckerr, could you test Linux? It might be similar to #32350 where it affects both Windows and Linux but not macOS.~ Root cause may be upstream in Chromium, `ShowInactive` in Electron just passes through to `ShowInactive` on the widget, there's really no logic present.
https://github.com/electron/electron/issues/32373
https://github.com/electron/electron/pull/32870
bdad6335c4e18aecbb3c4f3176fc100e542f0477
069cde09fbae94e18bb1e31ed6235c0761c08315
2022-01-06T22:48:21Z
c++
2022-02-21T09:23:55Z
patches/chromium/fix_don_t_restore_maximized_windows_when_calling_showinactive.patch
closed
electron/electron
https://github.com/electron/electron
32,373
[Bug]: BrowserWindow.showInactive Will Restore Maximized Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0-alpha.6 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior `BrowserWindow.showInactive` should not restore a maximized window ### Actual Behavior `BrowserWindow.showInactive` does restore a maximized window ### Testcase Gist URL https://gist.github.com/9f2c69b089f2155859bb0b439aefb668 ### Additional Information The provided gist is a test so it should be runnable by `bugbot`. I've confirmed the behavior on Windows, macOS seems unaffected, I haven't tested Linux. ~@ckerr, could you test Linux? It might be similar to #32350 where it affects both Windows and Linux but not macOS.~ Root cause may be upstream in Chromium, `ShowInactive` in Electron just passes through to `ShowInactive` on the widget, there's really no logic present.
https://github.com/electron/electron/issues/32373
https://github.com/electron/electron/pull/32870
bdad6335c4e18aecbb3c4f3176fc100e542f0477
069cde09fbae94e18bb1e31ed6235c0761c08315
2022-01-06T22:48:21Z
c++
2022-02-21T09:23:55Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); }); });
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
docs/api/window-open.md
# Opening windows from the renderer There are several ways to control how windows are created from trusted or untrusted content within a renderer. Windows can be created from the renderer in two ways: * clicking on links or submitting forms adorned with `target=_blank` * JavaScript calling `window.open()` For same-origin content, the new window is created within the same process, enabling the parent to access the child window directly. This can be very useful for app sub-windows that act as preference panels, or similar, as the parent can render to the sub-window directly, as if it were a `div` in the parent. This is the same behavior as in the browser. Electron pairs this native Chrome `Window` with a BrowserWindow under the hood. You can take advantage of all the customization available when creating a BrowserWindow in the main process by using `webContents.setWindowOpenHandler()` for renderer-created windows. BrowserWindow constructor options are set by, in increasing precedence order: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Note that `webContents.setWindowOpenHandler` has final say and full privilege because it is invoked in the main process. ### `window.open(url[, frameName][, features])` * `url` string * `frameName` string (optional) * `features` string (optional) Returns [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) | null `features` is a comma-separated key-value list, following the standard format of the browser. Electron will parse `BrowserWindowConstructorOptions` out of this list where possible, for convenience. For full control and better ergonomics, consider using `webContents.setWindowOpenHandler` to customize the BrowserWindow creation. A subset of `WebPreferences` can be set directly, unnested, from the features string: `zoomFactor`, `nodeIntegration`, `preload`, `javascript`, `contextIsolation`, and `webviewTag`. For example: ```js window.open('https://github.com', '_blank', 'top=500,left=200,frame=false,nodeIntegration=no') ``` **Notes:** * Node integration will always be disabled in the opened `window` if it is disabled on the parent window. * Context isolation will always be enabled in the opened `window` if it is enabled on the parent window. * JavaScript will always be disabled in the opened `window` if it is disabled on the parent window. * Non-standard features (that are not handled by Chromium or Electron) given in `features` will be passed to any registered `webContents`'s `did-create-window` event handler in the `options` argument. * `frameName` follows the specification of `windowName` located in the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters). * When opening `about:blank`, the child window's `WebPreferences` will be copied from the parent window, and there is no way to override it because Chromium skips browser side navigation in this case. To customize or cancel the creation of the window, you can optionally set an override handler with `webContents.setWindowOpenHandler()` from the main process. Returning `{ action: 'deny' }` cancels the window. Returning `{ action: 'allow', overrideBrowserWindowOptions: { ... } }` will allow opening the window and setting the `BrowserWindowConstructorOptions` to be used when creating the window. Note that this is more powerful than passing options through the feature string, as the renderer has more limited privileges in deciding security preferences than the main process. ### Native `Window` example ```javascript // main.js const mainWindow = new BrowserWindow() // In this example, only windows with the `about:blank` url will be created. // All other urls will be blocked. mainWindow.webContents.setWindowOpenHandler(({ url }) => { if (url === 'about:blank') { return { action: 'allow', overrideBrowserWindowOptions: { frame: false, fullscreenable: false, backgroundColor: 'black', webPreferences: { preload: 'my-child-window-preload-script.js' } } } } return { action: 'deny' } }) ``` ```javascript // renderer process (mainWindow) const childWindow = window.open('', 'modal') childWindow.document.write('<h1>Hello</h1>') ```
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
lib/browser/api/web-contents.ts
import { app, ipcMain, session, webFrameMain } from 'electron/main'; import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main'; import * as url from 'url'; import * as path from 'path'; import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'; import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils'; import { MessagePortMain } from '@electron/internal/browser/message-port-main'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; // session is not used here, the purpose is to make sure session is initalized // before the webContents module. // eslint-disable-next-line session let nextId = 0; const getNextId = function () { return ++nextId; }; type PostData = LoadURLOptions['postData'] // Stock page sizes const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { A5: { custom_display_name: 'A5', height_microns: 210000, name: 'ISO_A5', width_microns: 148000 }, A4: { custom_display_name: 'A4', height_microns: 297000, name: 'ISO_A4', is_default: 'true', width_microns: 210000 }, A3: { custom_display_name: 'A3', height_microns: 420000, name: 'ISO_A3', width_microns: 297000 }, Legal: { custom_display_name: 'Legal', height_microns: 355600, name: 'NA_LEGAL', width_microns: 215900 }, Letter: { custom_display_name: 'Letter', height_microns: 279400, name: 'NA_LETTER', width_microns: 215900 }, Tabloid: { height_microns: 431800, name: 'NA_LEDGER', width_microns: 279400, custom_display_name: 'Tabloid' } } as const; // The minimum micron size Chromium accepts is that where: // Per printing/units.h: // * kMicronsPerInch - Length of an inch in 0.001mm unit. // * kPointsPerInch - Length of an inch in CSS's 1pt unit. // // Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1 // // Practically, this means microns need to be > 352 microns. // We therefore need to verify this or it will silently fail. const isValidCustomPageSize = (width: number, height: number) => { return [width, height].every(x => x > 352); }; // Default printing setting const defaultPrintingSetting = { // Customizable. pageRange: [] as {from: number, to: number}[], mediaSize: {} as ElectronInternal.MediaSize, landscape: false, headerFooterEnabled: false, marginsType: 0, scaleFactor: 100, shouldPrintBackgrounds: false, shouldPrintSelectionOnly: false, // Non-customizable. printWithCloudPrint: false, printWithPrivet: false, printWithExtension: false, pagesPerSheet: 1, isFirstRequest: false, previewUIID: 0, // True, if the document source is modifiable. e.g. HTML and not PDF. previewModifiable: true, printToPDF: true, deviceName: 'Save as PDF', generateDraftData: true, dpiHorizontal: 72, dpiVertical: 72, rasterizePDF: false, duplex: 0, copies: 1, // 2 = color - see ColorModel in //printing/print_job_constants.h color: 2, collate: true, printerType: 2, title: undefined as string | undefined, url: undefined as string | undefined } as const; // JavaScript implementations of WebContents. const binding = process._linkedBinding('electron_browser_web_contents'); const printing = process._linkedBinding('electron_browser_printing'); const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } }; WebContents.prototype.postMessage = function (...args) { return this.mainFrame.postMessage(...args); }; WebContents.prototype.send = function (channel, ...args) { return this.mainFrame.send(channel, ...args); }; WebContents.prototype._sendInternal = function (channel, ...args) { return this.mainFrame._sendInternal(channel, ...args); }; function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) { if (typeof frame === 'number') { return webFrameMain.fromId(contents.mainFrame.processId, frame); } else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) { return webFrameMain.fromId(frame[0], frame[1]); } else { throw new Error('Missing required frame argument (must be number or [processId, frameId])'); } } WebContents.prototype.sendToFrame = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame.send(channel, ...args); return true; }; WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame._sendInternal(channel, ...args); return true; }; // Following methods are mapped to webFrame. const webFrameMethods = [ 'insertCSS', 'insertText', 'removeInsertedCSS', 'setVisualZoomLevelLimits' ] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[]; for (const method of webFrameMethods) { WebContents.prototype[method] = function (...args: any[]): Promise<any> { return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args); }; } const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => { if (webContents.getURL() && !webContents.isLoadingMainFrame()) return; return new Promise<void>((resolve) => { webContents.once('did-stop-loading', () => { resolve(); }); }); }; // Make sure WebContents::executeJavaScript would run the code only when the // WebContents has been loaded. WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture); }; WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture); }; // Translate the options of printToPDF. let pendingPromise: Promise<any> | undefined; WebContents.prototype.printToPDF = async function (options) { const printSettings: Record<string, any> = { ...defaultPrintingSetting, requestID: getNextId() }; if (options.landscape !== undefined) { if (typeof options.landscape !== 'boolean') { const error = new Error('landscape must be a Boolean'); return Promise.reject(error); } printSettings.landscape = options.landscape; } if (options.scaleFactor !== undefined) { if (typeof options.scaleFactor !== 'number') { const error = new Error('scaleFactor must be a Number'); return Promise.reject(error); } printSettings.scaleFactor = options.scaleFactor; } if (options.marginsType !== undefined) { if (typeof options.marginsType !== 'number') { const error = new Error('marginsType must be a Number'); return Promise.reject(error); } printSettings.marginsType = options.marginsType; } if (options.printSelectionOnly !== undefined) { if (typeof options.printSelectionOnly !== 'boolean') { const error = new Error('printSelectionOnly must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintSelectionOnly = options.printSelectionOnly; } if (options.printBackground !== undefined) { if (typeof options.printBackground !== 'boolean') { const error = new Error('printBackground must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintBackgrounds = options.printBackground; } if (options.pageRanges !== undefined) { const pageRanges = options.pageRanges; if (!Object.prototype.hasOwnProperty.call(pageRanges, 'from') || !Object.prototype.hasOwnProperty.call(pageRanges, 'to')) { const error = new Error('pageRanges must be an Object with \'from\' and \'to\' properties'); return Promise.reject(error); } if (typeof pageRanges.from !== 'number') { const error = new Error('pageRanges.from must be a Number'); return Promise.reject(error); } if (typeof pageRanges.to !== 'number') { const error = new Error('pageRanges.to must be a Number'); return Promise.reject(error); } // Chromium uses 1-based page ranges, so increment each by 1. printSettings.pageRange = [{ from: pageRanges.from + 1, to: pageRanges.to + 1 }]; } if (options.headerFooter !== undefined) { const headerFooter = options.headerFooter; printSettings.headerFooterEnabled = true; if (typeof headerFooter === 'object') { if (!headerFooter.url || !headerFooter.title) { const error = new Error('url and title properties are required for headerFooter'); return Promise.reject(error); } if (typeof headerFooter.title !== 'string') { const error = new Error('headerFooter.title must be a String'); return Promise.reject(error); } printSettings.title = headerFooter.title; if (typeof headerFooter.url !== 'string') { const error = new Error('headerFooter.url must be a String'); return Promise.reject(error); } printSettings.url = headerFooter.url; } else { const error = new Error('headerFooter must be an Object'); return Promise.reject(error); } } // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { const error = new Error('height and width properties are required for pageSize'); return Promise.reject(error); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { const error = new Error('height and width properties must be minimum 352 microns.'); return Promise.reject(error); } printSettings.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (Object.prototype.hasOwnProperty.call(PDFPageSizes, pageSize)) { printSettings.mediaSize = PDFPageSizes[pageSize]; } else { const error = new Error(`Unsupported pageSize: ${pageSize}`); return Promise.reject(error); } } else { printSettings.mediaSize = PDFPageSizes.A4; } // Chromium expects this in a 0-100 range number, not as float printSettings.scaleFactor = Math.ceil(printSettings.scaleFactor) % 100; // PrinterType enum from //printing/print_job_constants.h printSettings.printerType = 2; if (this._printToPDF) { if (pendingPromise) { pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings)); } else { pendingPromise = this._printToPDF(printSettings); } return pendingPromise; } else { const error = new Error('Printing feature is disabled'); return Promise.reject(error); } }; WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions = {}, callback) { // TODO(codebytere): deduplicate argument sanitization by moving rest of // print param logic into new file shared between printToPDF and print if (typeof options === 'object') { // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { throw new Error('height and width properties are required for pageSize'); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { throw new Error('height and width properties must be minimum 352 microns.'); } options.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (PDFPageSizes[pageSize]) { options.mediaSize = PDFPageSizes[pageSize]; } else { throw new Error(`Unsupported pageSize: ${pageSize}`); } } } if (this._print) { if (callback) { this._print(options, callback); } else { this._print(options); } } else { console.error('Error: Printing feature is disabled.'); } }; WebContents.prototype.getPrinters = function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterList) { return printing.getPrinterList(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.getPrintersAsync = async function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterListAsync) { return printing.getPrinterListAsync(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.loadFile = function (filePath, options = {}) { if (typeof filePath !== 'string') { throw new Error('Must pass filePath as a string'); } const { query, search, hash } = options; return this.loadURL(url.format({ protocol: 'file', slashes: true, pathname: path.resolve(app.getAppPath(), filePath), query, search, hash })); }; WebContents.prototype.loadURL = function (url, options) { if (!options) { options = {}; } const p = new Promise<void>((resolve, reject) => { const resolveAndCleanup = () => { removeListeners(); resolve(); }; const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => { const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`); Object.assign(err, { errno: errorCode, code: errorDescription, url }); removeListeners(); reject(err); }; const finishListener = () => { resolveAndCleanup(); }; const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => { if (isMainFrame) { rejectAndCleanup(errorCode, errorDescription, validatedURL); } }; let navigationStarted = false; const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => { if (isMainFrame) { if (navigationStarted && !isSameDocument) { // the webcontents has started another unrelated navigation in the // main frame (probably from the app calling `loadURL` again); reject // the promise // We should only consider the request aborted if the "navigation" is // actually navigating and not simply transitioning URL state in the // current context. E.g. pushState and `location.hash` changes are // considered navigation events but are triggered with isSameDocument. // We can ignore these to allow virtual routing on page load as long // as the routing does not leave the document return rejectAndCleanup(-3, 'ERR_ABORTED', url); } navigationStarted = true; } }; const stopLoadingListener = () => { // By the time we get here, either 'finish' or 'fail' should have fired // if the navigation occurred. However, in some situations (e.g. when // attempting to load a page with a bad scheme), loading will stop // without emitting finish or fail. In this case, we reject the promise // with a generic failure. // TODO(jeremy): enumerate all the cases in which this can happen. If // the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT // would be more appropriate. rejectAndCleanup(-2, 'ERR_FAILED', url); }; const removeListeners = () => { this.removeListener('did-finish-load', finishListener); this.removeListener('did-fail-load', failListener); this.removeListener('did-start-navigation', navigationListener); this.removeListener('did-stop-loading', stopLoadingListener); this.removeListener('destroyed', stopLoadingListener); }; this.on('did-finish-load', finishListener); this.on('did-fail-load', failListener); this.on('did-start-navigation', navigationListener); this.on('did-stop-loading', stopLoadingListener); this.on('destroyed', stopLoadingListener); }); // Add a no-op rejection handler to silence the unhandled rejection error. p.catch(() => {}); this._loadURL(url, options); this.emit('load-url', url, options); return p; }; WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'allow'} | {action: 'deny', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions})) { this._windowOpenHandler = handler; }; WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): BrowserWindowConstructorOptions | null { if (!this._windowOpenHandler) { return null; } const response = this._windowOpenHandler(details); if (typeof response !== 'object') { event.preventDefault(); console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`); return null; } if (response === null) { event.preventDefault(); console.error('The window open handler response must be an object, but was instead null.'); return null; } if (response.action === 'deny') { event.preventDefault(); return null; } else if (response.action === 'allow') { if (typeof response.overrideBrowserWindowOptions === 'object' && response.overrideBrowserWindowOptions !== null) { return response.overrideBrowserWindowOptions; } else { return {}; } } else { event.preventDefault(); console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.'); return null; } }; const addReplyToEvent = (event: Electron.IpcMainEvent) => { const { processId, frameId } = event; event.reply = (channel: string, ...args: any[]) => { event.sender.sendToFrame([processId, frameId], channel, ...args); }; }; const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => { const { processId, frameId } = event; Object.defineProperty(event, 'senderFrame', { get: () => webFrameMain.fromId(processId, frameId) }); }; const addReturnValueToEvent = (event: Electron.IpcMainEvent) => { Object.defineProperty(event, 'returnValue', { set: (value) => event.sendReply(value), get: () => {} }); }; const commandLine = process._linkedBinding('electron_common_command_line'); const environment = process._linkedBinding('electron_common_environment'); const loggingEnabled = () => { return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging'); }; // Add JavaScript wrappers for WebContents class. WebContents.prototype._init = function () { // Read off the ID at construction time, so that it's accessible even after // the underlying C++ WebContents is destroyed. const id = this.id; Object.defineProperty(this, 'id', { value: id, writable: false }); this._windowOpenHandler = null; // Dispatch IPC messages to the ipc module. this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); this.emit('ipc-message', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); event._reply = (result: any) => event.sendReply({ result }); event._throw = (error: Error) => { console.error(`Error occurred in handler for '${channel}':`, error); event.sendReply({ error: error.toString() }); }; const target = internal ? ipcMainInternal : ipcMain; if ((target as any)._invokeHandlers.has(channel)) { (target as any)._invokeHandlers.get(channel)(event, ...args); } else { event._throw(`No handler registered for '${channel}'`); } }); this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); addReturnValueToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); if (this.listenerCount('ipc-message-sync') === 0 && ipcMain.listenerCount(channel) === 0) { console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`); } this.emit('ipc-message-sync', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) { event.ports = ports.map(p => new MessagePortMain(p)); ipcMain.emit(channel, event, message); }); this.on('crashed', (event, ...args) => { app.emit('renderer-process-crashed', event, this, ...args); }); this.on('render-process-gone', (event, details) => { app.emit('render-process-gone', event, this, details); // Log out a hint to help users better debug renderer crashes. if (loggingEnabled()) { console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`); } }); // The devtools requests the webContents to reload. this.on('devtools-reload-page', function (this: Electron.WebContents) { this.reload(); }); if (this.getType() !== 'remote') { // Make new windows requested by links behave like "window.open". this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'], rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, referrer, postBody, disposition }; const options = this._callWindowOpenHandler(event, details); if (!event.defaultPrevented) { openGuestWindow({ event, embedder: event.sender, disposition, referrer, postData, overrideBrowserWindowOptions: options || {}, windowOpenArgs: details }); } }); let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null; this.on('-will-add-new-contents' as any, (event: ElectronInternal.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, disposition, referrer, postBody }; windowOpenOverriddenOptions = this._callWindowOpenHandler(event, details); if (!event.defaultPrevented) { const secureOverrideWebPreferences = windowOpenOverriddenOptions ? { // Allow setting of backgroundColor as a webPreference even though // it's technically a BrowserWindowConstructorOptions option because // we need to access it in the renderer at init time. backgroundColor: windowOpenOverriddenOptions.backgroundColor, transparent: windowOpenOverriddenOptions.transparent, ...windowOpenOverriddenOptions.webPreferences } : undefined; // TODO(zcbenz): The features string is parsed twice: here where it is // passed to C++, and in |makeBrowserWindowOptions| later where it is // not actually used since the WebContents is created here. // We should be able to remove the latter once the |new-window| event // is removed. const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures); // Parameters should keep same with |makeBrowserWindowOptions|. const webPreferences = makeWebPreferences({ embedder: event.sender, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences }); this._setNextChildWebPreferences(webPreferences); } }); // Create a new browser window for "window.open" this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string, _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string, referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => { const overriddenOptions = windowOpenOverriddenOptions || undefined; windowOpenOverriddenOptions = null; if ((disposition !== 'foreground-tab' && disposition !== 'new-window' && disposition !== 'background-tab')) { event.preventDefault(); return; } openGuestWindow({ event, embedder: event.sender, guest: webContents, overrideBrowserWindowOptions: overriddenOptions, disposition, referrer, postData, windowOpenArgs: { url, frameName, features: rawFeatures } }); }); } this.on('login', (event, ...args) => { app.emit('login', event, this, ...args); }); this.on('ready-to-show' as any, () => { const owner = this.getOwnerBrowserWindow(); if (owner && !owner.isDestroyed()) { process.nextTick(() => { owner.emit('ready-to-show'); }); } }); this.on('select-bluetooth-device', (event, devices, callback) => { if (this.listenerCount('select-bluetooth-device') === 1) { // Cancel it if there are no handlers event.preventDefault(); callback(''); } }); const event = process._linkedBinding('electron_browser_event').createEmpty(); app.emit('web-contents-created', event, this); // Properties Object.defineProperty(this, 'audioMuted', { get: () => this.isAudioMuted(), set: (muted) => this.setAudioMuted(muted) }); Object.defineProperty(this, 'userAgent', { get: () => this.getUserAgent(), set: (agent) => this.setUserAgent(agent) }); Object.defineProperty(this, 'zoomLevel', { get: () => this.getZoomLevel(), set: (level) => this.setZoomLevel(level) }); Object.defineProperty(this, 'zoomFactor', { get: () => this.getZoomFactor(), set: (factor) => this.setZoomFactor(factor) }); Object.defineProperty(this, 'frameRate', { get: () => this.getFrameRate(), set: (rate) => this.setFrameRate(rate) }); Object.defineProperty(this, 'backgroundThrottling', { get: () => this.getBackgroundThrottling(), set: (allowed) => this.setBackgroundThrottling(allowed) }); }; // Public APIs. export function create (options = {}): Electron.WebContents { return new (WebContents as any)(options); } export function fromId (id: string) { return binding.fromId(id); } export function fromDevToolsTargetId (targetId: string) { return binding.fromDevToolsTargetId(targetId); } export function getFocusedWebContents () { let focused = null; for (const contents of binding.getAllWebContents()) { if (!contents.isFocused()) continue; if (focused == null) focused = contents; // Return webview web contents which may be embedded inside another // web contents that is also reporting as focused if (contents.getType() === 'webview') return contents; } return focused; } export function getAllWebContents () { return binding.getAllWebContents(); }
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
lib/browser/guest-window-manager.ts
/** * Create and minimally track guest windows at the direction of the renderer * (via window.open). Here, "guest" roughly means "child" — it's not necessarily * emblematic of its process status; both in-process (same-origin) and * out-of-process (cross-origin) are created here. "Embedder" roughly means * "parent." */ import { BrowserWindow } from 'electron/main'; import type { BrowserWindowConstructorOptions, Referrer, WebContents, LoadURLOptions } from 'electron/main'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; type PostData = LoadURLOptions['postData'] export type WindowOpenArgs = { url: string, frameName: string, features: string, } const frameNamesToWindow = new Map<string, BrowserWindow>(); const registerFrameNameToGuestWindow = (name: string, win: BrowserWindow) => frameNamesToWindow.set(name, win); const unregisterFrameName = (name: string) => frameNamesToWindow.delete(name); const getGuestWindowByFrameName = (name: string) => frameNamesToWindow.get(name); /** * `openGuestWindow` is called to create and setup event handling for the new * window. * * Until its removal in 12.0.0, the `new-window` event is fired, allowing the * user to preventDefault() on the passed event (which ends up calling * DestroyWebContents). */ export function openGuestWindow ({ event, embedder, guest, referrer, disposition, postData, overrideBrowserWindowOptions, windowOpenArgs }: { event: { sender: WebContents, defaultPrevented: boolean }, embedder: WebContents, guest?: WebContents, referrer: Referrer, disposition: string, postData?: PostData, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, windowOpenArgs: WindowOpenArgs, }): BrowserWindow | undefined { const { url, frameName, features } = windowOpenArgs; const { options: browserWindowOptions } = makeBrowserWindowOptions({ embedder, features, overrideOptions: overrideBrowserWindowOptions }); const didCancelEvent = emitDeprecatedNewWindowEvent({ event, embedder, guest, browserWindowOptions, windowOpenArgs, disposition, postData, referrer }); if (didCancelEvent) return; // To spec, subsequent window.open calls with the same frame name (`target` in // spec parlance) will reuse the previous window. // https://html.spec.whatwg.org/multipage/window-object.html#apis-for-creating-and-navigating-browsing-contexts-by-name const existingWindow = getGuestWindowByFrameName(frameName); if (existingWindow) { if (existingWindow.isDestroyed() || existingWindow.webContents.isDestroyed()) { // FIXME(t57ser): The webContents is destroyed for some reason, unregister the frame name unregisterFrameName(frameName); } else { existingWindow.loadURL(url); return existingWindow; } } const window = new BrowserWindow({ webContents: guest, ...browserWindowOptions }); handleWindowLifecycleEvents({ embedder, frameName, guest: window }); embedder.emit('did-create-window', window, { url, frameName, options: browserWindowOptions, disposition, referrer, postData }); return window; } /** * Manage the relationship between embedder window and guest window. When the * guest is destroyed, notify the embedder. When the embedder is destroyed, so * too is the guest destroyed; this is Electron convention and isn't based in * browser behavior. */ const handleWindowLifecycleEvents = function ({ embedder, guest, frameName }: { embedder: WebContents, guest: BrowserWindow, frameName: string }) { const closedByEmbedder = function () { guest.removeListener('closed', closedByUser); guest.destroy(); }; const closedByUser = function () { embedder.removeListener('current-render-view-deleted' as any, closedByEmbedder); }; embedder.once('current-render-view-deleted' as any, closedByEmbedder); guest.once('closed', closedByUser); if (frameName) { registerFrameNameToGuestWindow(frameName, guest); guest.once('closed', function () { unregisterFrameName(frameName); }); } }; /** * Deprecated in favor of `webContents.setWindowOpenHandler` and * `did-create-window` in 11.0.0. Will be removed in 12.0.0. */ function emitDeprecatedNewWindowEvent ({ event, embedder, guest, windowOpenArgs, browserWindowOptions, disposition, referrer, postData }: { event: { sender: WebContents, defaultPrevented: boolean, newGuest?: BrowserWindow }, embedder: WebContents, guest?: WebContents, windowOpenArgs: WindowOpenArgs, browserWindowOptions: BrowserWindowConstructorOptions, disposition: string, referrer: Referrer, postData?: PostData, }): boolean { const { url, frameName } = windowOpenArgs; const isWebViewWithPopupsDisabled = embedder.getType() === 'webview' && embedder.getLastWebPreferences()!.disablePopups; const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : null; embedder.emit( 'new-window', event, url, frameName, disposition, { ...browserWindowOptions, webContents: guest }, [], // additionalFeatures referrer, postBody ); const { newGuest } = event; if (isWebViewWithPopupsDisabled) return true; if (event.defaultPrevented) { if (newGuest) { if (guest === newGuest.webContents) { // The webContents is not changed, so set defaultPrevented to false to // stop the callers of this event from destroying the webContents. event.defaultPrevented = false; } handleWindowLifecycleEvents({ embedder: event.sender, guest: newGuest, frameName }); } return true; } return false; } // Security options that child windows will always inherit from parent windows const securityWebPreferences: { [key: string]: boolean } = { contextIsolation: true, javascript: false, nodeIntegration: false, sandbox: true, webviewTag: false, nodeIntegrationInSubFrames: false, enableWebSQL: false }; function makeBrowserWindowOptions ({ embedder, features, overrideOptions }: { embedder: WebContents, features: string, overrideOptions?: BrowserWindowConstructorOptions, }) { const { options: parsedOptions, webPreferences: parsedWebPreferences } = parseFeatures(features); return { options: { show: true, width: 800, height: 600, ...parsedOptions, ...overrideOptions, // Note that for normal code path an existing WebContents created by // Chromium will be used, with web preferences parsed in the // |-will-add-new-contents| event. // The |webPreferences| here is only used by the |new-window| event. webPreferences: makeWebPreferences({ embedder, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences: overrideOptions && overrideOptions.webPreferences }) } as Electron.BrowserViewConstructorOptions }; } export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {}, insecureParsedWebPreferences: parsedWebPreferences = {} }: { embedder: WebContents, insecureParsedWebPreferences?: ReturnType<typeof parseFeatures>['webPreferences'], // Note that override preferences are considered elevated, and should only be // sourced from the main process, as they override security defaults. If you // have unvetted prefs, use parsedWebPreferences. secureOverrideWebPreferences?: BrowserWindowConstructorOptions['webPreferences'], }) { const parentWebPreferences = embedder.getLastWebPreferences()!; const securityWebPreferencesFromParent = (Object.keys(securityWebPreferences).reduce((map, key) => { if (securityWebPreferences[key] === parentWebPreferences[key as keyof Electron.WebPreferences]) { (map as any)[key] = parentWebPreferences[key as keyof Electron.WebPreferences]; } return map; }, {} as Electron.WebPreferences)); return { ...parsedWebPreferences, // Note that order is key here, we want to disallow the renderer's // ability to change important security options but allow main (via // setWindowOpenHandler) to change them. ...securityWebPreferencesFromParent, ...secureOverrideWebPreferences }; } const MULTIPART_CONTENT_TYPE = 'multipart/form-data'; const URL_ENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded'; // Figure out appropriate headers for post data. export const parseContentTypeFormat = function (postData: Exclude<PostData, undefined>) { if (postData.length) { if (postData[0].type === 'rawData') { // For multipart forms, the first element will start with the boundary // notice, which looks something like `------WebKitFormBoundary12345678` // Note, this regex would fail when submitting a urlencoded form with an // input attribute of name="--theKey", but, uhh, don't do that? const postDataFront = postData[0].bytes.toString(); const boundary = /^--.*[^-\r\n]/.exec(postDataFront); if (boundary) { return { boundary: boundary[0].substr(2), contentType: MULTIPART_CONTENT_TYPE }; } } } // Either the form submission didn't contain any inputs (the postData array // was empty), or we couldn't find the boundary and thus we can assume this is // a key=value style form. return { contentType: URL_ENCODED_CONTENT_TYPE }; };
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
typings/internal-electron.d.ts
/// <reference path="../electron.d.ts" /> /** * This file augments the Electron TS namespace with the internal APIs * that are not documented but are used by Electron internally */ declare namespace Electron { enum ProcessType { browser = 'browser', renderer = 'renderer', worker = 'worker' } interface App { setVersion(version: string): void; setDesktopName(name: string): void; setAppPath(path: string | null): void; } type TouchBarItemType = NonNullable<Electron.TouchBarConstructorOptions['items']>[0]; interface BaseWindow { _init(): void; } interface BrowserWindow { _init(): void; _touchBar: Electron.TouchBar | null; _setTouchBarItems: (items: TouchBarItemType[]) => void; _setEscapeTouchBarItem: (item: TouchBarItemType | {}) => void; _refreshTouchBarItem: (itemID: string) => void; _getWindowButtonVisibility: () => boolean; frameName: string; on(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this; removeListener(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this; } interface BrowserWindowConstructorOptions { webContents?: WebContents; } interface ContextBridge { internalContextBridge?: { contextIsolationEnabled: boolean; overrideGlobalValueFromIsolatedWorld(keys: string[], value: any): void; overrideGlobalValueWithDynamicPropsFromIsolatedWorld(keys: string[], value: any): void; overrideGlobalPropertyFromIsolatedWorld(keys: string[], getter: Function, setter?: Function): void; isInMainWorld(): boolean; } } interface TouchBar { _removeFromWindow: (win: BrowserWindow) => void; } interface WebContents { _loadURL(url: string, options: ElectronInternal.LoadURLOptions): void; getOwnerBrowserWindow(): Electron.BrowserWindow | null; getLastWebPreferences(): Electron.WebPreferences | null; _getProcessMemoryInfo(): Electron.ProcessMemoryInfo; _getPreloadPaths(): string[]; equal(other: WebContents): boolean; browserWindowOptions: BrowserWindowConstructorOptions; _windowOpenHandler: ((details: Electron.HandlerDetails) => any) | null; _callWindowOpenHandler(event: any, details: Electron.HandlerDetails): Electron.BrowserWindowConstructorOptions | null; _setNextChildWebPreferences(prefs: Partial<Electron.BrowserWindowConstructorOptions['webPreferences']> & Pick<Electron.BrowserWindowConstructorOptions, 'backgroundColor'>): void; _send(internal: boolean, channel: string, args: any): boolean; _sendToFrameInternal(frameId: number | [number, number], channel: string, ...args: any[]): boolean; _sendInternal(channel: string, ...args: any[]): void; _printToPDF(options: any): Promise<Buffer>; _print(options: any, callback?: (success: boolean, failureReason: string) => void): void; _getPrinters(): Electron.PrinterInfo[]; _getPrintersAsync(): Promise<Electron.PrinterInfo[]>; _init(): void; canGoToIndex(index: number): boolean; getActiveIndex(): number; length(): number; destroy(): void; // <webview> attachToIframe(embedderWebContents: Electron.WebContents, embedderFrameId: number): void; detachFromOuterFrame(): void; setEmbedder(embedder: Electron.WebContents): void; attachParams?: { instanceId: number; src: string, opts: LoadURLOptions }; viewInstanceId: number; } interface WebFrameMain { _send(internal: boolean, channel: string, args: any): void; _sendInternal(channel: string, ...args: any[]): void; _postMessage(channel: string, message: any, transfer?: any[]): void; } interface WebFrame { _isEvalAllowed(): boolean; } interface WebPreferences { disablePopups?: boolean; preloadURL?: string; embedder?: Electron.WebContents; type?: 'backgroundPage' | 'window' | 'browserView' | 'remote' | 'webview' | 'offscreen'; } interface Menu { _init(): void; _isCommandIdChecked(id: string): boolean; _isCommandIdEnabled(id: string): boolean; _shouldCommandIdWorkWhenHidden(id: string): boolean; _isCommandIdVisible(id: string): boolean; _getAcceleratorForCommandId(id: string, useDefaultAccelerator: boolean): Accelerator | undefined; _shouldRegisterAcceleratorForCommandId(id: string): boolean; _getSharingItemForCommandId(id: string): SharingItem | null; _callMenuWillShow(): void; _executeCommand(event: any, id: number): void; _menuWillShow(): void; commandsMap: Record<string, MenuItem>; groupsMap: Record<string, MenuItem[]>; getItemCount(): number; popupAt(window: BaseWindow, x: number, y: number, positioning: number, callback: () => void): void; closePopupAt(id: number): void; setSublabel(index: number, label: string): void; setToolTip(index: number, tooltip: string): void; setIcon(index: number, image: string | NativeImage): void; setRole(index: number, role: string): void; insertItem(index: number, commandId: number, label: string): void; insertCheckItem(index: number, commandId: number, label: string): void; insertRadioItem(index: number, commandId: number, label: string, groupId: number): void; insertSeparator(index: number): void; insertSubMenu(index: number, commandId: number, label: string, submenu?: Menu): void; delegate?: any; _getAcceleratorTextAt(index: number): string; } interface MenuItem { overrideReadOnlyProperty(property: string, value: any): void; groupId: number; getDefaultRoleAccelerator(): Accelerator | undefined; getCheckStatus(): boolean; acceleratorWorksWhenHidden?: boolean; } interface IpcMainEvent { sendReply(value: any): void; } interface IpcMainInvokeEvent { sendReply(value: any): void; _reply(value: any): void; _throw(error: Error | string): void; } const deprecate: ElectronInternal.DeprecationUtil; namespace Main { const deprecate: ElectronInternal.DeprecationUtil; } class View {} // Experimental views API class BaseWindow { constructor(args: {show: boolean}) setContentView(view: View): void static fromId(id: number): BaseWindow; static getAllWindows(): BaseWindow[]; isFocused(): boolean; static getFocusedWindow(): BaseWindow | undefined; setMenu(menu: Menu): void; } class WebContentsView { constructor(options: BrowserWindowConstructorOptions) } // Deprecated / undocumented BrowserWindow methods interface BrowserWindow { getURL(): string; send(channel: string, ...args: any[]): void; openDevTools(options?: Electron.OpenDevToolsOptions): void; closeDevTools(): void; isDevToolsOpened(): void; isDevToolsFocused(): void; toggleDevTools(): void; inspectElement(x: number, y: number): void; inspectSharedWorker(): void; inspectServiceWorker(): void; getBackgroundThrottling(): void; setBackgroundThrottling(allowed: boolean): void; } namespace Main { class BaseWindow extends Electron.BaseWindow {} class View extends Electron.View {} class WebContentsView extends Electron.WebContentsView {} } } declare namespace ElectronInternal { type DeprecationHandler = (message: string) => void; interface DeprecationUtil { warnOnce(oldName: string, newName?: string): () => void; setHandler(handler: DeprecationHandler | null): void; getHandler(): DeprecationHandler | null; warn(oldName: string, newName: string): void; log(message: string): void; removeFunction<T extends Function>(fn: T, removedName: string): T; renameFunction<T extends Function>(fn: T, newName: string): T; event(emitter: NodeJS.EventEmitter, oldName: string, newName: string): void; removeProperty<T, K extends (keyof T & string)>(object: T, propertyName: K, onlyForValues?: any[]): T; renameProperty<T, K extends (keyof T & string)>(object: T, oldName: string, newName: K): T; moveAPI<T extends Function>(fn: T, oldUsage: string, newUsage: string): T; } interface DesktopCapturer { startHandling(captureWindow: boolean, captureScreen: boolean, thumbnailSize: Electron.Size, fetchWindowIcons: boolean): void; _onerror?: (error: string) => void; _onfinished?: (sources: Electron.DesktopCapturerSource[], fetchWindowIcons: boolean) => void; } interface GetSourcesOptions { captureWindow: boolean; captureScreen: boolean; thumbnailSize: Electron.Size; fetchWindowIcons: boolean; } interface GetSourcesResult { id: string; name: string; thumbnail: Electron.NativeImage; display_id: string; appIcon: Electron.NativeImage | null; } interface IpcRendererInternal extends NodeJS.EventEmitter, Pick<Electron.IpcRenderer, 'send' | 'sendSync' | 'invoke'> { invoke<T>(channel: string, ...args: any[]): Promise<T>; } interface IpcMainInternalEvent extends Omit<Electron.IpcMainEvent, 'reply'> { } interface IpcMainInternal extends NodeJS.EventEmitter { handle(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any): void; on(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this; once(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this; } interface Event extends Electron.Event { sender: WebContents; } interface LoadURLOptions extends Electron.LoadURLOptions { reloadIgnoringCache?: boolean; } interface WebContentsPrintOptions extends Electron.WebContentsPrintOptions { mediaSize?: MediaSize; } type MediaSize = { name: string, custom_display_name: string, height_microns: number, width_microns: number, is_default?: 'true', } type ModuleLoader = () => any; interface ModuleEntry { name: string; private?: boolean; loader: ModuleLoader; } class WebViewElement extends HTMLElement { static observedAttributes: Array<string>; public contentWindow: Window; public connectedCallback?(): void; public attributeChangedCallback?(): void; public disconnectedCallback?(): void; // Created in web-view-impl public getWebContentsId(): number; public capturePage(rect?: Electron.Rectangle): Promise<Electron.NativeImage>; } class WebContents extends Electron.WebContents { static create(opts: Electron.WebPreferences): Electron.WebContents; } } declare namespace Chrome { namespace Tabs { // https://developer.chrome.com/docs/extensions/tabs#method-executeScript interface ExecuteScriptDetails { code?: string; file?: string; allFrames?: boolean; frameId?: number; matchAboutBlank?: boolean; runAt?: 'document-start' | 'document-end' | 'document_idle'; cssOrigin: 'author' | 'user'; } type ExecuteScriptCallback = (result: Array<any>) => void; // https://developer.chrome.com/docs/extensions/tabs#method-sendMessage interface SendMessageDetails { frameId?: number; } type SendMessageCallback = (result: any) => void; } } interface Global extends NodeJS.Global { require: NodeRequire; module: NodeModule; __filename: string; __dirname: string; }
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
docs/api/window-open.md
# Opening windows from the renderer There are several ways to control how windows are created from trusted or untrusted content within a renderer. Windows can be created from the renderer in two ways: * clicking on links or submitting forms adorned with `target=_blank` * JavaScript calling `window.open()` For same-origin content, the new window is created within the same process, enabling the parent to access the child window directly. This can be very useful for app sub-windows that act as preference panels, or similar, as the parent can render to the sub-window directly, as if it were a `div` in the parent. This is the same behavior as in the browser. Electron pairs this native Chrome `Window` with a BrowserWindow under the hood. You can take advantage of all the customization available when creating a BrowserWindow in the main process by using `webContents.setWindowOpenHandler()` for renderer-created windows. BrowserWindow constructor options are set by, in increasing precedence order: parsed options from the `features` string from `window.open()`, security-related webPreferences inherited from the parent, and options given by [`webContents.setWindowOpenHandler`](web-contents.md#contentssetwindowopenhandlerhandler). Note that `webContents.setWindowOpenHandler` has final say and full privilege because it is invoked in the main process. ### `window.open(url[, frameName][, features])` * `url` string * `frameName` string (optional) * `features` string (optional) Returns [`Window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) | null `features` is a comma-separated key-value list, following the standard format of the browser. Electron will parse `BrowserWindowConstructorOptions` out of this list where possible, for convenience. For full control and better ergonomics, consider using `webContents.setWindowOpenHandler` to customize the BrowserWindow creation. A subset of `WebPreferences` can be set directly, unnested, from the features string: `zoomFactor`, `nodeIntegration`, `preload`, `javascript`, `contextIsolation`, and `webviewTag`. For example: ```js window.open('https://github.com', '_blank', 'top=500,left=200,frame=false,nodeIntegration=no') ``` **Notes:** * Node integration will always be disabled in the opened `window` if it is disabled on the parent window. * Context isolation will always be enabled in the opened `window` if it is enabled on the parent window. * JavaScript will always be disabled in the opened `window` if it is disabled on the parent window. * Non-standard features (that are not handled by Chromium or Electron) given in `features` will be passed to any registered `webContents`'s `did-create-window` event handler in the `options` argument. * `frameName` follows the specification of `windowName` located in the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters). * When opening `about:blank`, the child window's `WebPreferences` will be copied from the parent window, and there is no way to override it because Chromium skips browser side navigation in this case. To customize or cancel the creation of the window, you can optionally set an override handler with `webContents.setWindowOpenHandler()` from the main process. Returning `{ action: 'deny' }` cancels the window. Returning `{ action: 'allow', overrideBrowserWindowOptions: { ... } }` will allow opening the window and setting the `BrowserWindowConstructorOptions` to be used when creating the window. Note that this is more powerful than passing options through the feature string, as the renderer has more limited privileges in deciding security preferences than the main process. ### Native `Window` example ```javascript // main.js const mainWindow = new BrowserWindow() // In this example, only windows with the `about:blank` url will be created. // All other urls will be blocked. mainWindow.webContents.setWindowOpenHandler(({ url }) => { if (url === 'about:blank') { return { action: 'allow', overrideBrowserWindowOptions: { frame: false, fullscreenable: false, backgroundColor: 'black', webPreferences: { preload: 'my-child-window-preload-script.js' } } } } return { action: 'deny' } }) ``` ```javascript // renderer process (mainWindow) const childWindow = window.open('', 'modal') childWindow.document.write('<h1>Hello</h1>') ```
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
lib/browser/api/web-contents.ts
import { app, ipcMain, session, webFrameMain } from 'electron/main'; import type { BrowserWindowConstructorOptions, LoadURLOptions } from 'electron/main'; import * as url from 'url'; import * as path from 'path'; import { openGuestWindow, makeWebPreferences, parseContentTypeFormat } from '@electron/internal/browser/guest-window-manager'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal'; import * as ipcMainUtils from '@electron/internal/browser/ipc-main-internal-utils'; import { MessagePortMain } from '@electron/internal/browser/message-port-main'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; // session is not used here, the purpose is to make sure session is initalized // before the webContents module. // eslint-disable-next-line session let nextId = 0; const getNextId = function () { return ++nextId; }; type PostData = LoadURLOptions['postData'] // Stock page sizes const PDFPageSizes: Record<string, ElectronInternal.MediaSize> = { A5: { custom_display_name: 'A5', height_microns: 210000, name: 'ISO_A5', width_microns: 148000 }, A4: { custom_display_name: 'A4', height_microns: 297000, name: 'ISO_A4', is_default: 'true', width_microns: 210000 }, A3: { custom_display_name: 'A3', height_microns: 420000, name: 'ISO_A3', width_microns: 297000 }, Legal: { custom_display_name: 'Legal', height_microns: 355600, name: 'NA_LEGAL', width_microns: 215900 }, Letter: { custom_display_name: 'Letter', height_microns: 279400, name: 'NA_LETTER', width_microns: 215900 }, Tabloid: { height_microns: 431800, name: 'NA_LEDGER', width_microns: 279400, custom_display_name: 'Tabloid' } } as const; // The minimum micron size Chromium accepts is that where: // Per printing/units.h: // * kMicronsPerInch - Length of an inch in 0.001mm unit. // * kPointsPerInch - Length of an inch in CSS's 1pt unit. // // Formula: (kPointsPerInch / kMicronsPerInch) * size >= 1 // // Practically, this means microns need to be > 352 microns. // We therefore need to verify this or it will silently fail. const isValidCustomPageSize = (width: number, height: number) => { return [width, height].every(x => x > 352); }; // Default printing setting const defaultPrintingSetting = { // Customizable. pageRange: [] as {from: number, to: number}[], mediaSize: {} as ElectronInternal.MediaSize, landscape: false, headerFooterEnabled: false, marginsType: 0, scaleFactor: 100, shouldPrintBackgrounds: false, shouldPrintSelectionOnly: false, // Non-customizable. printWithCloudPrint: false, printWithPrivet: false, printWithExtension: false, pagesPerSheet: 1, isFirstRequest: false, previewUIID: 0, // True, if the document source is modifiable. e.g. HTML and not PDF. previewModifiable: true, printToPDF: true, deviceName: 'Save as PDF', generateDraftData: true, dpiHorizontal: 72, dpiVertical: 72, rasterizePDF: false, duplex: 0, copies: 1, // 2 = color - see ColorModel in //printing/print_job_constants.h color: 2, collate: true, printerType: 2, title: undefined as string | undefined, url: undefined as string | undefined } as const; // JavaScript implementations of WebContents. const binding = process._linkedBinding('electron_browser_web_contents'); const printing = process._linkedBinding('electron_browser_printing'); const { WebContents } = binding as { WebContents: { prototype: Electron.WebContents } }; WebContents.prototype.postMessage = function (...args) { return this.mainFrame.postMessage(...args); }; WebContents.prototype.send = function (channel, ...args) { return this.mainFrame.send(channel, ...args); }; WebContents.prototype._sendInternal = function (channel, ...args) { return this.mainFrame._sendInternal(channel, ...args); }; function getWebFrame (contents: Electron.WebContents, frame: number | [number, number]) { if (typeof frame === 'number') { return webFrameMain.fromId(contents.mainFrame.processId, frame); } else if (Array.isArray(frame) && frame.length === 2 && frame.every(value => typeof value === 'number')) { return webFrameMain.fromId(frame[0], frame[1]); } else { throw new Error('Missing required frame argument (must be number or [processId, frameId])'); } } WebContents.prototype.sendToFrame = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame.send(channel, ...args); return true; }; WebContents.prototype._sendToFrameInternal = function (frameId, channel, ...args) { const frame = getWebFrame(this, frameId); if (!frame) return false; frame._sendInternal(channel, ...args); return true; }; // Following methods are mapped to webFrame. const webFrameMethods = [ 'insertCSS', 'insertText', 'removeInsertedCSS', 'setVisualZoomLevelLimits' ] as ('insertCSS' | 'insertText' | 'removeInsertedCSS' | 'setVisualZoomLevelLimits')[]; for (const method of webFrameMethods) { WebContents.prototype[method] = function (...args: any[]): Promise<any> { return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, method, ...args); }; } const waitTillCanExecuteJavaScript = async (webContents: Electron.WebContents) => { if (webContents.getURL() && !webContents.isLoadingMainFrame()) return; return new Promise<void>((resolve) => { webContents.once('did-stop-loading', () => { resolve(); }); }); }; // Make sure WebContents::executeJavaScript would run the code only when the // WebContents has been loaded. WebContents.prototype.executeJavaScript = async function (code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScript', String(code), !!hasUserGesture); }; WebContents.prototype.executeJavaScriptInIsolatedWorld = async function (worldId, code, hasUserGesture) { await waitTillCanExecuteJavaScript(this); return ipcMainUtils.invokeInWebContents(this, IPC_MESSAGES.RENDERER_WEB_FRAME_METHOD, 'executeJavaScriptInIsolatedWorld', worldId, code, !!hasUserGesture); }; // Translate the options of printToPDF. let pendingPromise: Promise<any> | undefined; WebContents.prototype.printToPDF = async function (options) { const printSettings: Record<string, any> = { ...defaultPrintingSetting, requestID: getNextId() }; if (options.landscape !== undefined) { if (typeof options.landscape !== 'boolean') { const error = new Error('landscape must be a Boolean'); return Promise.reject(error); } printSettings.landscape = options.landscape; } if (options.scaleFactor !== undefined) { if (typeof options.scaleFactor !== 'number') { const error = new Error('scaleFactor must be a Number'); return Promise.reject(error); } printSettings.scaleFactor = options.scaleFactor; } if (options.marginsType !== undefined) { if (typeof options.marginsType !== 'number') { const error = new Error('marginsType must be a Number'); return Promise.reject(error); } printSettings.marginsType = options.marginsType; } if (options.printSelectionOnly !== undefined) { if (typeof options.printSelectionOnly !== 'boolean') { const error = new Error('printSelectionOnly must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintSelectionOnly = options.printSelectionOnly; } if (options.printBackground !== undefined) { if (typeof options.printBackground !== 'boolean') { const error = new Error('printBackground must be a Boolean'); return Promise.reject(error); } printSettings.shouldPrintBackgrounds = options.printBackground; } if (options.pageRanges !== undefined) { const pageRanges = options.pageRanges; if (!Object.prototype.hasOwnProperty.call(pageRanges, 'from') || !Object.prototype.hasOwnProperty.call(pageRanges, 'to')) { const error = new Error('pageRanges must be an Object with \'from\' and \'to\' properties'); return Promise.reject(error); } if (typeof pageRanges.from !== 'number') { const error = new Error('pageRanges.from must be a Number'); return Promise.reject(error); } if (typeof pageRanges.to !== 'number') { const error = new Error('pageRanges.to must be a Number'); return Promise.reject(error); } // Chromium uses 1-based page ranges, so increment each by 1. printSettings.pageRange = [{ from: pageRanges.from + 1, to: pageRanges.to + 1 }]; } if (options.headerFooter !== undefined) { const headerFooter = options.headerFooter; printSettings.headerFooterEnabled = true; if (typeof headerFooter === 'object') { if (!headerFooter.url || !headerFooter.title) { const error = new Error('url and title properties are required for headerFooter'); return Promise.reject(error); } if (typeof headerFooter.title !== 'string') { const error = new Error('headerFooter.title must be a String'); return Promise.reject(error); } printSettings.title = headerFooter.title; if (typeof headerFooter.url !== 'string') { const error = new Error('headerFooter.url must be a String'); return Promise.reject(error); } printSettings.url = headerFooter.url; } else { const error = new Error('headerFooter must be an Object'); return Promise.reject(error); } } // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { const error = new Error('height and width properties are required for pageSize'); return Promise.reject(error); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { const error = new Error('height and width properties must be minimum 352 microns.'); return Promise.reject(error); } printSettings.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (Object.prototype.hasOwnProperty.call(PDFPageSizes, pageSize)) { printSettings.mediaSize = PDFPageSizes[pageSize]; } else { const error = new Error(`Unsupported pageSize: ${pageSize}`); return Promise.reject(error); } } else { printSettings.mediaSize = PDFPageSizes.A4; } // Chromium expects this in a 0-100 range number, not as float printSettings.scaleFactor = Math.ceil(printSettings.scaleFactor) % 100; // PrinterType enum from //printing/print_job_constants.h printSettings.printerType = 2; if (this._printToPDF) { if (pendingPromise) { pendingPromise = pendingPromise.then(() => this._printToPDF(printSettings)); } else { pendingPromise = this._printToPDF(printSettings); } return pendingPromise; } else { const error = new Error('Printing feature is disabled'); return Promise.reject(error); } }; WebContents.prototype.print = function (options: ElectronInternal.WebContentsPrintOptions = {}, callback) { // TODO(codebytere): deduplicate argument sanitization by moving rest of // print param logic into new file shared between printToPDF and print if (typeof options === 'object') { // Optionally set size for PDF. if (options.pageSize !== undefined) { const pageSize = options.pageSize; if (typeof pageSize === 'object') { if (!pageSize.height || !pageSize.width) { throw new Error('height and width properties are required for pageSize'); } // Dimensions in Microns - 1 meter = 10^6 microns const height = Math.ceil(pageSize.height); const width = Math.ceil(pageSize.width); if (!isValidCustomPageSize(width, height)) { throw new Error('height and width properties must be minimum 352 microns.'); } options.mediaSize = { name: 'CUSTOM', custom_display_name: 'Custom', height_microns: height, width_microns: width }; } else if (PDFPageSizes[pageSize]) { options.mediaSize = PDFPageSizes[pageSize]; } else { throw new Error(`Unsupported pageSize: ${pageSize}`); } } } if (this._print) { if (callback) { this._print(options, callback); } else { this._print(options); } } else { console.error('Error: Printing feature is disabled.'); } }; WebContents.prototype.getPrinters = function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterList) { return printing.getPrinterList(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.getPrintersAsync = async function () { // TODO(nornagon): this API has nothing to do with WebContents and should be // moved. if (printing.getPrinterListAsync) { return printing.getPrinterListAsync(); } else { console.error('Error: Printing feature is disabled.'); return []; } }; WebContents.prototype.loadFile = function (filePath, options = {}) { if (typeof filePath !== 'string') { throw new Error('Must pass filePath as a string'); } const { query, search, hash } = options; return this.loadURL(url.format({ protocol: 'file', slashes: true, pathname: path.resolve(app.getAppPath(), filePath), query, search, hash })); }; WebContents.prototype.loadURL = function (url, options) { if (!options) { options = {}; } const p = new Promise<void>((resolve, reject) => { const resolveAndCleanup = () => { removeListeners(); resolve(); }; const rejectAndCleanup = (errorCode: number, errorDescription: string, url: string) => { const err = new Error(`${errorDescription} (${errorCode}) loading '${typeof url === 'string' ? url.substr(0, 2048) : url}'`); Object.assign(err, { errno: errorCode, code: errorDescription, url }); removeListeners(); reject(err); }; const finishListener = () => { resolveAndCleanup(); }; const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => { if (isMainFrame) { rejectAndCleanup(errorCode, errorDescription, validatedURL); } }; let navigationStarted = false; const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => { if (isMainFrame) { if (navigationStarted && !isSameDocument) { // the webcontents has started another unrelated navigation in the // main frame (probably from the app calling `loadURL` again); reject // the promise // We should only consider the request aborted if the "navigation" is // actually navigating and not simply transitioning URL state in the // current context. E.g. pushState and `location.hash` changes are // considered navigation events but are triggered with isSameDocument. // We can ignore these to allow virtual routing on page load as long // as the routing does not leave the document return rejectAndCleanup(-3, 'ERR_ABORTED', url); } navigationStarted = true; } }; const stopLoadingListener = () => { // By the time we get here, either 'finish' or 'fail' should have fired // if the navigation occurred. However, in some situations (e.g. when // attempting to load a page with a bad scheme), loading will stop // without emitting finish or fail. In this case, we reject the promise // with a generic failure. // TODO(jeremy): enumerate all the cases in which this can happen. If // the only one is with a bad scheme, perhaps ERR_INVALID_ARGUMENT // would be more appropriate. rejectAndCleanup(-2, 'ERR_FAILED', url); }; const removeListeners = () => { this.removeListener('did-finish-load', finishListener); this.removeListener('did-fail-load', failListener); this.removeListener('did-start-navigation', navigationListener); this.removeListener('did-stop-loading', stopLoadingListener); this.removeListener('destroyed', stopLoadingListener); }; this.on('did-finish-load', finishListener); this.on('did-fail-load', failListener); this.on('did-start-navigation', navigationListener); this.on('did-stop-loading', stopLoadingListener); this.on('destroyed', stopLoadingListener); }); // Add a no-op rejection handler to silence the unhandled rejection error. p.catch(() => {}); this._loadURL(url, options); this.emit('load-url', url, options); return p; }; WebContents.prototype.setWindowOpenHandler = function (handler: (details: Electron.HandlerDetails) => ({action: 'allow'} | {action: 'deny', overrideBrowserWindowOptions?: BrowserWindowConstructorOptions})) { this._windowOpenHandler = handler; }; WebContents.prototype._callWindowOpenHandler = function (event: Electron.Event, details: Electron.HandlerDetails): BrowserWindowConstructorOptions | null { if (!this._windowOpenHandler) { return null; } const response = this._windowOpenHandler(details); if (typeof response !== 'object') { event.preventDefault(); console.error(`The window open handler response must be an object, but was instead of type '${typeof response}'.`); return null; } if (response === null) { event.preventDefault(); console.error('The window open handler response must be an object, but was instead null.'); return null; } if (response.action === 'deny') { event.preventDefault(); return null; } else if (response.action === 'allow') { if (typeof response.overrideBrowserWindowOptions === 'object' && response.overrideBrowserWindowOptions !== null) { return response.overrideBrowserWindowOptions; } else { return {}; } } else { event.preventDefault(); console.error('The window open handler response must be an object with an \'action\' property of \'allow\' or \'deny\'.'); return null; } }; const addReplyToEvent = (event: Electron.IpcMainEvent) => { const { processId, frameId } = event; event.reply = (channel: string, ...args: any[]) => { event.sender.sendToFrame([processId, frameId], channel, ...args); }; }; const addSenderFrameToEvent = (event: Electron.IpcMainEvent | Electron.IpcMainInvokeEvent) => { const { processId, frameId } = event; Object.defineProperty(event, 'senderFrame', { get: () => webFrameMain.fromId(processId, frameId) }); }; const addReturnValueToEvent = (event: Electron.IpcMainEvent) => { Object.defineProperty(event, 'returnValue', { set: (value) => event.sendReply(value), get: () => {} }); }; const commandLine = process._linkedBinding('electron_common_command_line'); const environment = process._linkedBinding('electron_common_environment'); const loggingEnabled = () => { return environment.hasVar('ELECTRON_ENABLE_LOGGING') || commandLine.hasSwitch('enable-logging'); }; // Add JavaScript wrappers for WebContents class. WebContents.prototype._init = function () { // Read off the ID at construction time, so that it's accessible even after // the underlying C++ WebContents is destroyed. const id = this.id; Object.defineProperty(this, 'id', { value: id, writable: false }); this._windowOpenHandler = null; // Dispatch IPC messages to the ipc module. this.on('-ipc-message' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); this.emit('ipc-message', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-invoke' as any, function (event: Electron.IpcMainInvokeEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); event._reply = (result: any) => event.sendReply({ result }); event._throw = (error: Error) => { console.error(`Error occurred in handler for '${channel}':`, error); event.sendReply({ error: error.toString() }); }; const target = internal ? ipcMainInternal : ipcMain; if ((target as any)._invokeHandlers.has(channel)) { (target as any)._invokeHandlers.get(channel)(event, ...args); } else { event._throw(`No handler registered for '${channel}'`); } }); this.on('-ipc-message-sync' as any, function (this: Electron.WebContents, event: Electron.IpcMainEvent, internal: boolean, channel: string, args: any[]) { addSenderFrameToEvent(event); addReturnValueToEvent(event); if (internal) { ipcMainInternal.emit(channel, event, ...args); } else { addReplyToEvent(event); if (this.listenerCount('ipc-message-sync') === 0 && ipcMain.listenerCount(channel) === 0) { console.warn(`WebContents #${this.id} called ipcRenderer.sendSync() with '${channel}' channel without listeners.`); } this.emit('ipc-message-sync', event, channel, ...args); ipcMain.emit(channel, event, ...args); } }); this.on('-ipc-ports' as any, function (event: Electron.IpcMainEvent, internal: boolean, channel: string, message: any, ports: any[]) { event.ports = ports.map(p => new MessagePortMain(p)); ipcMain.emit(channel, event, message); }); this.on('crashed', (event, ...args) => { app.emit('renderer-process-crashed', event, this, ...args); }); this.on('render-process-gone', (event, details) => { app.emit('render-process-gone', event, this, details); // Log out a hint to help users better debug renderer crashes. if (loggingEnabled()) { console.info(`Renderer process ${details.reason} - see https://www.electronjs.org/docs/tutorial/application-debugging for potential debugging information.`); } }); // The devtools requests the webContents to reload. this.on('devtools-reload-page', function (this: Electron.WebContents) { this.reload(); }); if (this.getType() !== 'remote') { // Make new windows requested by links behave like "window.open". this.on('-new-window' as any, (event: ElectronInternal.Event, url: string, frameName: string, disposition: Electron.HandlerDetails['disposition'], rawFeatures: string, referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, referrer, postBody, disposition }; const options = this._callWindowOpenHandler(event, details); if (!event.defaultPrevented) { openGuestWindow({ event, embedder: event.sender, disposition, referrer, postData, overrideBrowserWindowOptions: options || {}, windowOpenArgs: details }); } }); let windowOpenOverriddenOptions: BrowserWindowConstructorOptions | null = null; this.on('-will-add-new-contents' as any, (event: ElectronInternal.Event, url: string, frameName: string, rawFeatures: string, disposition: Electron.HandlerDetails['disposition'], referrer: Electron.Referrer, postData: PostData) => { const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : undefined; const details: Electron.HandlerDetails = { url, frameName, features: rawFeatures, disposition, referrer, postBody }; windowOpenOverriddenOptions = this._callWindowOpenHandler(event, details); if (!event.defaultPrevented) { const secureOverrideWebPreferences = windowOpenOverriddenOptions ? { // Allow setting of backgroundColor as a webPreference even though // it's technically a BrowserWindowConstructorOptions option because // we need to access it in the renderer at init time. backgroundColor: windowOpenOverriddenOptions.backgroundColor, transparent: windowOpenOverriddenOptions.transparent, ...windowOpenOverriddenOptions.webPreferences } : undefined; // TODO(zcbenz): The features string is parsed twice: here where it is // passed to C++, and in |makeBrowserWindowOptions| later where it is // not actually used since the WebContents is created here. // We should be able to remove the latter once the |new-window| event // is removed. const { webPreferences: parsedWebPreferences } = parseFeatures(rawFeatures); // Parameters should keep same with |makeBrowserWindowOptions|. const webPreferences = makeWebPreferences({ embedder: event.sender, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences }); this._setNextChildWebPreferences(webPreferences); } }); // Create a new browser window for "window.open" this.on('-add-new-contents' as any, (event: ElectronInternal.Event, webContents: Electron.WebContents, disposition: string, _userGesture: boolean, _left: number, _top: number, _width: number, _height: number, url: string, frameName: string, referrer: Electron.Referrer, rawFeatures: string, postData: PostData) => { const overriddenOptions = windowOpenOverriddenOptions || undefined; windowOpenOverriddenOptions = null; if ((disposition !== 'foreground-tab' && disposition !== 'new-window' && disposition !== 'background-tab')) { event.preventDefault(); return; } openGuestWindow({ event, embedder: event.sender, guest: webContents, overrideBrowserWindowOptions: overriddenOptions, disposition, referrer, postData, windowOpenArgs: { url, frameName, features: rawFeatures } }); }); } this.on('login', (event, ...args) => { app.emit('login', event, this, ...args); }); this.on('ready-to-show' as any, () => { const owner = this.getOwnerBrowserWindow(); if (owner && !owner.isDestroyed()) { process.nextTick(() => { owner.emit('ready-to-show'); }); } }); this.on('select-bluetooth-device', (event, devices, callback) => { if (this.listenerCount('select-bluetooth-device') === 1) { // Cancel it if there are no handlers event.preventDefault(); callback(''); } }); const event = process._linkedBinding('electron_browser_event').createEmpty(); app.emit('web-contents-created', event, this); // Properties Object.defineProperty(this, 'audioMuted', { get: () => this.isAudioMuted(), set: (muted) => this.setAudioMuted(muted) }); Object.defineProperty(this, 'userAgent', { get: () => this.getUserAgent(), set: (agent) => this.setUserAgent(agent) }); Object.defineProperty(this, 'zoomLevel', { get: () => this.getZoomLevel(), set: (level) => this.setZoomLevel(level) }); Object.defineProperty(this, 'zoomFactor', { get: () => this.getZoomFactor(), set: (factor) => this.setZoomFactor(factor) }); Object.defineProperty(this, 'frameRate', { get: () => this.getFrameRate(), set: (rate) => this.setFrameRate(rate) }); Object.defineProperty(this, 'backgroundThrottling', { get: () => this.getBackgroundThrottling(), set: (allowed) => this.setBackgroundThrottling(allowed) }); }; // Public APIs. export function create (options = {}): Electron.WebContents { return new (WebContents as any)(options); } export function fromId (id: string) { return binding.fromId(id); } export function fromDevToolsTargetId (targetId: string) { return binding.fromDevToolsTargetId(targetId); } export function getFocusedWebContents () { let focused = null; for (const contents of binding.getAllWebContents()) { if (!contents.isFocused()) continue; if (focused == null) focused = contents; // Return webview web contents which may be embedded inside another // web contents that is also reporting as focused if (contents.getType() === 'webview') return contents; } return focused; } export function getAllWebContents () { return binding.getAllWebContents(); }
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
lib/browser/guest-window-manager.ts
/** * Create and minimally track guest windows at the direction of the renderer * (via window.open). Here, "guest" roughly means "child" — it's not necessarily * emblematic of its process status; both in-process (same-origin) and * out-of-process (cross-origin) are created here. "Embedder" roughly means * "parent." */ import { BrowserWindow } from 'electron/main'; import type { BrowserWindowConstructorOptions, Referrer, WebContents, LoadURLOptions } from 'electron/main'; import { parseFeatures } from '@electron/internal/browser/parse-features-string'; type PostData = LoadURLOptions['postData'] export type WindowOpenArgs = { url: string, frameName: string, features: string, } const frameNamesToWindow = new Map<string, BrowserWindow>(); const registerFrameNameToGuestWindow = (name: string, win: BrowserWindow) => frameNamesToWindow.set(name, win); const unregisterFrameName = (name: string) => frameNamesToWindow.delete(name); const getGuestWindowByFrameName = (name: string) => frameNamesToWindow.get(name); /** * `openGuestWindow` is called to create and setup event handling for the new * window. * * Until its removal in 12.0.0, the `new-window` event is fired, allowing the * user to preventDefault() on the passed event (which ends up calling * DestroyWebContents). */ export function openGuestWindow ({ event, embedder, guest, referrer, disposition, postData, overrideBrowserWindowOptions, windowOpenArgs }: { event: { sender: WebContents, defaultPrevented: boolean }, embedder: WebContents, guest?: WebContents, referrer: Referrer, disposition: string, postData?: PostData, overrideBrowserWindowOptions?: BrowserWindowConstructorOptions, windowOpenArgs: WindowOpenArgs, }): BrowserWindow | undefined { const { url, frameName, features } = windowOpenArgs; const { options: browserWindowOptions } = makeBrowserWindowOptions({ embedder, features, overrideOptions: overrideBrowserWindowOptions }); const didCancelEvent = emitDeprecatedNewWindowEvent({ event, embedder, guest, browserWindowOptions, windowOpenArgs, disposition, postData, referrer }); if (didCancelEvent) return; // To spec, subsequent window.open calls with the same frame name (`target` in // spec parlance) will reuse the previous window. // https://html.spec.whatwg.org/multipage/window-object.html#apis-for-creating-and-navigating-browsing-contexts-by-name const existingWindow = getGuestWindowByFrameName(frameName); if (existingWindow) { if (existingWindow.isDestroyed() || existingWindow.webContents.isDestroyed()) { // FIXME(t57ser): The webContents is destroyed for some reason, unregister the frame name unregisterFrameName(frameName); } else { existingWindow.loadURL(url); return existingWindow; } } const window = new BrowserWindow({ webContents: guest, ...browserWindowOptions }); handleWindowLifecycleEvents({ embedder, frameName, guest: window }); embedder.emit('did-create-window', window, { url, frameName, options: browserWindowOptions, disposition, referrer, postData }); return window; } /** * Manage the relationship between embedder window and guest window. When the * guest is destroyed, notify the embedder. When the embedder is destroyed, so * too is the guest destroyed; this is Electron convention and isn't based in * browser behavior. */ const handleWindowLifecycleEvents = function ({ embedder, guest, frameName }: { embedder: WebContents, guest: BrowserWindow, frameName: string }) { const closedByEmbedder = function () { guest.removeListener('closed', closedByUser); guest.destroy(); }; const closedByUser = function () { embedder.removeListener('current-render-view-deleted' as any, closedByEmbedder); }; embedder.once('current-render-view-deleted' as any, closedByEmbedder); guest.once('closed', closedByUser); if (frameName) { registerFrameNameToGuestWindow(frameName, guest); guest.once('closed', function () { unregisterFrameName(frameName); }); } }; /** * Deprecated in favor of `webContents.setWindowOpenHandler` and * `did-create-window` in 11.0.0. Will be removed in 12.0.0. */ function emitDeprecatedNewWindowEvent ({ event, embedder, guest, windowOpenArgs, browserWindowOptions, disposition, referrer, postData }: { event: { sender: WebContents, defaultPrevented: boolean, newGuest?: BrowserWindow }, embedder: WebContents, guest?: WebContents, windowOpenArgs: WindowOpenArgs, browserWindowOptions: BrowserWindowConstructorOptions, disposition: string, referrer: Referrer, postData?: PostData, }): boolean { const { url, frameName } = windowOpenArgs; const isWebViewWithPopupsDisabled = embedder.getType() === 'webview' && embedder.getLastWebPreferences()!.disablePopups; const postBody = postData ? { data: postData, ...parseContentTypeFormat(postData) } : null; embedder.emit( 'new-window', event, url, frameName, disposition, { ...browserWindowOptions, webContents: guest }, [], // additionalFeatures referrer, postBody ); const { newGuest } = event; if (isWebViewWithPopupsDisabled) return true; if (event.defaultPrevented) { if (newGuest) { if (guest === newGuest.webContents) { // The webContents is not changed, so set defaultPrevented to false to // stop the callers of this event from destroying the webContents. event.defaultPrevented = false; } handleWindowLifecycleEvents({ embedder: event.sender, guest: newGuest, frameName }); } return true; } return false; } // Security options that child windows will always inherit from parent windows const securityWebPreferences: { [key: string]: boolean } = { contextIsolation: true, javascript: false, nodeIntegration: false, sandbox: true, webviewTag: false, nodeIntegrationInSubFrames: false, enableWebSQL: false }; function makeBrowserWindowOptions ({ embedder, features, overrideOptions }: { embedder: WebContents, features: string, overrideOptions?: BrowserWindowConstructorOptions, }) { const { options: parsedOptions, webPreferences: parsedWebPreferences } = parseFeatures(features); return { options: { show: true, width: 800, height: 600, ...parsedOptions, ...overrideOptions, // Note that for normal code path an existing WebContents created by // Chromium will be used, with web preferences parsed in the // |-will-add-new-contents| event. // The |webPreferences| here is only used by the |new-window| event. webPreferences: makeWebPreferences({ embedder, insecureParsedWebPreferences: parsedWebPreferences, secureOverrideWebPreferences: overrideOptions && overrideOptions.webPreferences }) } as Electron.BrowserViewConstructorOptions }; } export function makeWebPreferences ({ embedder, secureOverrideWebPreferences = {}, insecureParsedWebPreferences: parsedWebPreferences = {} }: { embedder: WebContents, insecureParsedWebPreferences?: ReturnType<typeof parseFeatures>['webPreferences'], // Note that override preferences are considered elevated, and should only be // sourced from the main process, as they override security defaults. If you // have unvetted prefs, use parsedWebPreferences. secureOverrideWebPreferences?: BrowserWindowConstructorOptions['webPreferences'], }) { const parentWebPreferences = embedder.getLastWebPreferences()!; const securityWebPreferencesFromParent = (Object.keys(securityWebPreferences).reduce((map, key) => { if (securityWebPreferences[key] === parentWebPreferences[key as keyof Electron.WebPreferences]) { (map as any)[key] = parentWebPreferences[key as keyof Electron.WebPreferences]; } return map; }, {} as Electron.WebPreferences)); return { ...parsedWebPreferences, // Note that order is key here, we want to disallow the renderer's // ability to change important security options but allow main (via // setWindowOpenHandler) to change them. ...securityWebPreferencesFromParent, ...secureOverrideWebPreferences }; } const MULTIPART_CONTENT_TYPE = 'multipart/form-data'; const URL_ENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded'; // Figure out appropriate headers for post data. export const parseContentTypeFormat = function (postData: Exclude<PostData, undefined>) { if (postData.length) { if (postData[0].type === 'rawData') { // For multipart forms, the first element will start with the boundary // notice, which looks something like `------WebKitFormBoundary12345678` // Note, this regex would fail when submitting a urlencoded form with an // input attribute of name="--theKey", but, uhh, don't do that? const postDataFront = postData[0].bytes.toString(); const boundary = /^--.*[^-\r\n]/.exec(postDataFront); if (boundary) { return { boundary: boundary[0].substr(2), contentType: MULTIPART_CONTENT_TYPE }; } } } // Either the form submission didn't contain any inputs (the postData array // was empty), or we couldn't find the boundary and thus we can assume this is // a key=value style form. return { contentType: URL_ENCODED_CONTENT_TYPE }; };
closed
electron/electron
https://github.com/electron/electron
11,128
Opened windows will be closed when the opener window closes.
* Electron version: 1.7.5, 1.7.9 * Operating system: Windows 10 x64, Windows 7 x86 ### Expected behavior Opened windows will remain open when closing the opener window. ### Actual behavior Opened windows will automatically close when the opener window is closed. ### How to reproduce 1. Open an electron instance with a BrowserWindow (window A). 2. Navigate to https://www.w3schools.com/jsref/met_win_open.asp (or similar pages) 3. Open a new window (window B) by clicking the "Try It Yourself" button. 4. Open a new window (window C) by clicking the "Try It" button in Window B. 4. Close window B (opener window of window C) Result: Window C closes. This only closes the opened windows (and the opened windows in the opened window, eg.) when closing the opener window. All other windows remain unaffected: Closing window A results in the closing of window B and window C.
https://github.com/electron/electron/issues/11128
https://github.com/electron/electron/pull/31314
bcf060fab67fe1912d03ad253de98b3091b2a61b
41b2945ced7f93568fb3771ab6989d490214ab91
2017-11-15T16:01:05Z
c++
2022-02-23T07:59:50Z
typings/internal-electron.d.ts
/// <reference path="../electron.d.ts" /> /** * This file augments the Electron TS namespace with the internal APIs * that are not documented but are used by Electron internally */ declare namespace Electron { enum ProcessType { browser = 'browser', renderer = 'renderer', worker = 'worker' } interface App { setVersion(version: string): void; setDesktopName(name: string): void; setAppPath(path: string | null): void; } type TouchBarItemType = NonNullable<Electron.TouchBarConstructorOptions['items']>[0]; interface BaseWindow { _init(): void; } interface BrowserWindow { _init(): void; _touchBar: Electron.TouchBar | null; _setTouchBarItems: (items: TouchBarItemType[]) => void; _setEscapeTouchBarItem: (item: TouchBarItemType | {}) => void; _refreshTouchBarItem: (itemID: string) => void; _getWindowButtonVisibility: () => boolean; frameName: string; on(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this; removeListener(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this; } interface BrowserWindowConstructorOptions { webContents?: WebContents; } interface ContextBridge { internalContextBridge?: { contextIsolationEnabled: boolean; overrideGlobalValueFromIsolatedWorld(keys: string[], value: any): void; overrideGlobalValueWithDynamicPropsFromIsolatedWorld(keys: string[], value: any): void; overrideGlobalPropertyFromIsolatedWorld(keys: string[], getter: Function, setter?: Function): void; isInMainWorld(): boolean; } } interface TouchBar { _removeFromWindow: (win: BrowserWindow) => void; } interface WebContents { _loadURL(url: string, options: ElectronInternal.LoadURLOptions): void; getOwnerBrowserWindow(): Electron.BrowserWindow | null; getLastWebPreferences(): Electron.WebPreferences | null; _getProcessMemoryInfo(): Electron.ProcessMemoryInfo; _getPreloadPaths(): string[]; equal(other: WebContents): boolean; browserWindowOptions: BrowserWindowConstructorOptions; _windowOpenHandler: ((details: Electron.HandlerDetails) => any) | null; _callWindowOpenHandler(event: any, details: Electron.HandlerDetails): Electron.BrowserWindowConstructorOptions | null; _setNextChildWebPreferences(prefs: Partial<Electron.BrowserWindowConstructorOptions['webPreferences']> & Pick<Electron.BrowserWindowConstructorOptions, 'backgroundColor'>): void; _send(internal: boolean, channel: string, args: any): boolean; _sendToFrameInternal(frameId: number | [number, number], channel: string, ...args: any[]): boolean; _sendInternal(channel: string, ...args: any[]): void; _printToPDF(options: any): Promise<Buffer>; _print(options: any, callback?: (success: boolean, failureReason: string) => void): void; _getPrinters(): Electron.PrinterInfo[]; _getPrintersAsync(): Promise<Electron.PrinterInfo[]>; _init(): void; canGoToIndex(index: number): boolean; getActiveIndex(): number; length(): number; destroy(): void; // <webview> attachToIframe(embedderWebContents: Electron.WebContents, embedderFrameId: number): void; detachFromOuterFrame(): void; setEmbedder(embedder: Electron.WebContents): void; attachParams?: { instanceId: number; src: string, opts: LoadURLOptions }; viewInstanceId: number; } interface WebFrameMain { _send(internal: boolean, channel: string, args: any): void; _sendInternal(channel: string, ...args: any[]): void; _postMessage(channel: string, message: any, transfer?: any[]): void; } interface WebFrame { _isEvalAllowed(): boolean; } interface WebPreferences { disablePopups?: boolean; preloadURL?: string; embedder?: Electron.WebContents; type?: 'backgroundPage' | 'window' | 'browserView' | 'remote' | 'webview' | 'offscreen'; } interface Menu { _init(): void; _isCommandIdChecked(id: string): boolean; _isCommandIdEnabled(id: string): boolean; _shouldCommandIdWorkWhenHidden(id: string): boolean; _isCommandIdVisible(id: string): boolean; _getAcceleratorForCommandId(id: string, useDefaultAccelerator: boolean): Accelerator | undefined; _shouldRegisterAcceleratorForCommandId(id: string): boolean; _getSharingItemForCommandId(id: string): SharingItem | null; _callMenuWillShow(): void; _executeCommand(event: any, id: number): void; _menuWillShow(): void; commandsMap: Record<string, MenuItem>; groupsMap: Record<string, MenuItem[]>; getItemCount(): number; popupAt(window: BaseWindow, x: number, y: number, positioning: number, callback: () => void): void; closePopupAt(id: number): void; setSublabel(index: number, label: string): void; setToolTip(index: number, tooltip: string): void; setIcon(index: number, image: string | NativeImage): void; setRole(index: number, role: string): void; insertItem(index: number, commandId: number, label: string): void; insertCheckItem(index: number, commandId: number, label: string): void; insertRadioItem(index: number, commandId: number, label: string, groupId: number): void; insertSeparator(index: number): void; insertSubMenu(index: number, commandId: number, label: string, submenu?: Menu): void; delegate?: any; _getAcceleratorTextAt(index: number): string; } interface MenuItem { overrideReadOnlyProperty(property: string, value: any): void; groupId: number; getDefaultRoleAccelerator(): Accelerator | undefined; getCheckStatus(): boolean; acceleratorWorksWhenHidden?: boolean; } interface IpcMainEvent { sendReply(value: any): void; } interface IpcMainInvokeEvent { sendReply(value: any): void; _reply(value: any): void; _throw(error: Error | string): void; } const deprecate: ElectronInternal.DeprecationUtil; namespace Main { const deprecate: ElectronInternal.DeprecationUtil; } class View {} // Experimental views API class BaseWindow { constructor(args: {show: boolean}) setContentView(view: View): void static fromId(id: number): BaseWindow; static getAllWindows(): BaseWindow[]; isFocused(): boolean; static getFocusedWindow(): BaseWindow | undefined; setMenu(menu: Menu): void; } class WebContentsView { constructor(options: BrowserWindowConstructorOptions) } // Deprecated / undocumented BrowserWindow methods interface BrowserWindow { getURL(): string; send(channel: string, ...args: any[]): void; openDevTools(options?: Electron.OpenDevToolsOptions): void; closeDevTools(): void; isDevToolsOpened(): void; isDevToolsFocused(): void; toggleDevTools(): void; inspectElement(x: number, y: number): void; inspectSharedWorker(): void; inspectServiceWorker(): void; getBackgroundThrottling(): void; setBackgroundThrottling(allowed: boolean): void; } namespace Main { class BaseWindow extends Electron.BaseWindow {} class View extends Electron.View {} class WebContentsView extends Electron.WebContentsView {} } } declare namespace ElectronInternal { type DeprecationHandler = (message: string) => void; interface DeprecationUtil { warnOnce(oldName: string, newName?: string): () => void; setHandler(handler: DeprecationHandler | null): void; getHandler(): DeprecationHandler | null; warn(oldName: string, newName: string): void; log(message: string): void; removeFunction<T extends Function>(fn: T, removedName: string): T; renameFunction<T extends Function>(fn: T, newName: string): T; event(emitter: NodeJS.EventEmitter, oldName: string, newName: string): void; removeProperty<T, K extends (keyof T & string)>(object: T, propertyName: K, onlyForValues?: any[]): T; renameProperty<T, K extends (keyof T & string)>(object: T, oldName: string, newName: K): T; moveAPI<T extends Function>(fn: T, oldUsage: string, newUsage: string): T; } interface DesktopCapturer { startHandling(captureWindow: boolean, captureScreen: boolean, thumbnailSize: Electron.Size, fetchWindowIcons: boolean): void; _onerror?: (error: string) => void; _onfinished?: (sources: Electron.DesktopCapturerSource[], fetchWindowIcons: boolean) => void; } interface GetSourcesOptions { captureWindow: boolean; captureScreen: boolean; thumbnailSize: Electron.Size; fetchWindowIcons: boolean; } interface GetSourcesResult { id: string; name: string; thumbnail: Electron.NativeImage; display_id: string; appIcon: Electron.NativeImage | null; } interface IpcRendererInternal extends NodeJS.EventEmitter, Pick<Electron.IpcRenderer, 'send' | 'sendSync' | 'invoke'> { invoke<T>(channel: string, ...args: any[]): Promise<T>; } interface IpcMainInternalEvent extends Omit<Electron.IpcMainEvent, 'reply'> { } interface IpcMainInternal extends NodeJS.EventEmitter { handle(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any): void; on(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this; once(channel: string, listener: (event: IpcMainInternalEvent, ...args: any[]) => void): this; } interface Event extends Electron.Event { sender: WebContents; } interface LoadURLOptions extends Electron.LoadURLOptions { reloadIgnoringCache?: boolean; } interface WebContentsPrintOptions extends Electron.WebContentsPrintOptions { mediaSize?: MediaSize; } type MediaSize = { name: string, custom_display_name: string, height_microns: number, width_microns: number, is_default?: 'true', } type ModuleLoader = () => any; interface ModuleEntry { name: string; private?: boolean; loader: ModuleLoader; } class WebViewElement extends HTMLElement { static observedAttributes: Array<string>; public contentWindow: Window; public connectedCallback?(): void; public attributeChangedCallback?(): void; public disconnectedCallback?(): void; // Created in web-view-impl public getWebContentsId(): number; public capturePage(rect?: Electron.Rectangle): Promise<Electron.NativeImage>; } class WebContents extends Electron.WebContents { static create(opts: Electron.WebPreferences): Electron.WebContents; } } declare namespace Chrome { namespace Tabs { // https://developer.chrome.com/docs/extensions/tabs#method-executeScript interface ExecuteScriptDetails { code?: string; file?: string; allFrames?: boolean; frameId?: number; matchAboutBlank?: boolean; runAt?: 'document-start' | 'document-end' | 'document_idle'; cssOrigin: 'author' | 'user'; } type ExecuteScriptCallback = (result: Array<any>) => void; // https://developer.chrome.com/docs/extensions/tabs#method-sendMessage interface SendMessageDetails { frameId?: number; } type SendMessageCallback = (result: any) => void; } } interface Global extends NodeJS.Global { require: NodeRequire; module: NodeModule; __filename: string; __dirname: string; }
closed
electron/electron
https://github.com/electron/electron
32,846
[Bug]: offscreen render set background transparent does not work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Version 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.2.3 ### Expected Behavior background should transparent if background is #00000000 ### Actual Behavior has a white background ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32846
https://github.com/electron/electron/pull/32885
41b2945ced7f93568fb3771ab6989d490214ab91
08e26175fdc8b7fb033e55c408181f2c0fa2940e
2022-02-10T03:25:59Z
c++
2022-02-23T10:33:42Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) base::TimeDelta interval; if (ui::TextInsertionCaretBlinkPeriod(&interval)) return interval; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif BUILDFLAG(IS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { bool transparent = false; options.Get(options::kTransparent, &transparent); content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionId& partition_id, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { bool guest = IsGuest() || type_ == Type::kBrowserView; absl::optional<SkColor> color = guest ? SK_ColorTRANSPARENT : web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(color); SetBackgroundColor(rwhv, color.value_or(SK_ColorWHITE)); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetList().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents()->IncrementCapturerCount(size, stay_hidden, stay_awake); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronBrowser::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents, const viz::SurfaceId& surface_id, const gfx::Size& natural_size) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance()->EnterPictureInPicture( web_contents, surface_id, natural_size); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetList()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
32,846
[Bug]: offscreen render set background transparent does not work
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 Version 21H1 ### What arch are you using? x64 ### Last Known Working Electron version 14.2.3 ### Expected Behavior background should transparent if background is #00000000 ### Actual Behavior has a white background ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32846
https://github.com/electron/electron/pull/32885
41b2945ced7f93568fb3771ab6989d490214ab91
08e26175fdc8b7fb033e55c408181f2c0fa2940e
2022-02-10T03:25:59Z
c++
2022-02-23T10:33:42Z
shell/browser/api/electron_api_web_contents.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/desktop_media_id.h" #include "content/public/browser/desktop_streams_registry.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "printing/print_job_constants.h" #include "services/resource_coordinator/public/cpp/memory_instrumentation/memory_instrumentation.h" #include "services/service_manager/public/cpp/interface_provider.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/file_select_helper.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/browser/web_view_manager.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if BUILDFLAG(IS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "extensions/common/mojom/view_type.mojom.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" #include "shell/browser/printing/print_preview_message_handler.h" #include "shell/browser/printing/print_view_manager_electron.h" #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } absl::optional<base::TimeDelta> GetCursorBlinkInterval() { #if BUILDFLAG(IS_MAC) base::TimeDelta interval; if (ui::TextInsertionCaretBlinkPeriod(&interval)) return interval; #elif BUILDFLAG(IS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif BUILDFLAG(IS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::Milliseconds(system_msec); } #endif return absl::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const std::u16string& device_name) { #if BUILDFLAG(IS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif BUILDFLAG(IS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(base::as_wcstr(device_name)); #else return true; #endif } std::pair<std::string, std::u16string> GetDefaultPrinterAsync() { #if BUILDFLAG(IS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name; printing::mojom::ResultCode code = print_backend->GetDefaultPrinterName(printer_name); // We don't want to return if this fails since some devices won't have a // default printer. if (code != printing::mojom::ResultCode::kSuccess) LOG(ERROR) << "Failed to get default printer name"; // Check for existing printers and pick the first one should it exist. if (printer_name.empty()) { printing::PrinterList printers; if (print_backend->EnumeratePrinters(&printers) != printing::mojom::ResultCode::kSuccess) return std::make_pair("Failed to enumerate printers", std::u16string()); if (!printers.empty()) printer_name = printers.front().printer_name; } return std::make_pair(std::string(), base::UTF8ToUTF16(printer_name)); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !BUILDFLAG(IS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif BUILDFLAG(IS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().DeprecatedGetOriginAsURL(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { auto file_system_value = std::make_unique<base::DictionaryValue>(); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::Value* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { const base::DictionaryValue* file_system_paths_dict; file_system_paths_value->GetAsDictionary(&file_system_paths_dict); for (auto it : file_system_paths_dict->DictItems()) { std::string type = it.second.is_string() ? it.second.GetString() : std::string(); result[it.first] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } void SetBackgroundColor(content::RenderWidgetHostView* rwhv, SkColor color) { rwhv->SetBackgroundColor(color); static_cast<content::RenderWidgetHostViewBase*>(rwhv) ->SetContentBackgroundColor(color); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::mojom::ViewType view_type) { switch (view_type) { case extensions::mojom::ViewType::kExtensionBackgroundPage: return WebContents::Type::kBackgroundPage; case extensions::mojom::ViewType::kAppWindow: case extensions::mojom::ViewType::kComponent: case extensions::mojom::ViewType::kExtensionDialog: case extensions::mojom::ViewType::kExtensionPopup: case extensions::mojom::ViewType::kBackgroundContents: case extensions::mojom::ViewType::kExtensionGuest: case extensions::mojom::ViewType::kTabContents: case extensions::mojom::ViewType::kInvalid: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::mojom::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::mojom::ViewType::kInvalid) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_( base::MakeRefCounted<DevToolsFileSystemIndexer>()), exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) #endif { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 bool initially_shown = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { bool transparent = false; options.Get(options::kTransparent, &transparent); content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN) // Update font settings. static const gfx::FontRenderParams params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params.antialiasing; prefs->use_subpixel_positioning = params.subpixel_positioning; prefs->hinting = params.hinting; prefs->use_autohinter = params.autohinter; prefs->use_bitmaps = params.use_bitmaps; prefs->subpixel_rendering = params.subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_ = std::make_unique<extensions::ScriptExecutor>(web_contents()); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::mojom::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (type_ == Type::kRemote) return; if (type_ == Type::kBackgroundPage) // non-background-page WebContents are retained by other classes. We need // to pin here to prevent background-page WebContents from being GC'd. // The background page api::WebContents will live until the underlying // content::WebContents is destroyed. Pin(isolate); // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif void WebContents::InitWithWebContents( std::unique_ptr<content::WebContents> web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents.get()); PrintViewManagerElectron::CreateForWebContents(web_contents.get()); printing::CreateCompositeClientIfNeeded(web_contents.get(), browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents.get(), std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents.get()); offscreen_ = web_preferences && web_preferences->IsOffscreen(); // Create InspectableWebContents. inspectable_web_contents_ = std::make_unique<InspectableWebContents>( std::move(web_contents), browser_context->prefs(), is_guest); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { // clear out objects that have been granted permissions so that when // WebContents::RenderFrameDeleted is called as a result of WebContents // destruction it doesn't try to clear out a granted_devices_ // on a destructed object. granted_devices_.clear(); if (!inspectable_web_contents_) { WebContentsDestroyed(); return; } inspectable_web_contents_->GetView()->SetDelegate(nullptr); // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. bool not_owned_by_this = IsGuest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) not_owned_by_this = true; #endif if (not_owned_by_this) { inspectable_web_contents_->ReleaseWebContents(); WebContentsDestroyed(); } // InspectableWebContents will be automatically destroyed. } void WebContents::DeleteThisIfAlive() { // It is possible that the FirstWeakCallback has been called but the // SecondWeakCallback has not, in this case the garbage collection of // WebContents has already started and we should not |delete this|. // Calling |GetWrapper| can detect this corner case. auto* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; delete this; } void WebContents::Destroy() { // The content::WebContents should be destroyed asyncronously when possible // as user may choose to destroy WebContents during an event of it. if (Browser::Get()->is_shutting_down() || IsGuest()) { DeleteThisIfAlive(); } else { base::PostTask(FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( [](base::WeakPtr<WebContents> contents) { if (contents) contents->DeleteThisIfAlive(); }, GetWeakPtr())); } } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const std::u16string& message, int32_t line_no, const std::u16string& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit( "-will-add-new-contents", params.target_url, params.frame_name, params.raw_features, params.disposition, *params.referrer, params.body); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const content::StoragePartitionId& partition_id, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); // We call RenderFrameCreated here as at this point the empty "about:blank" // render frame has already been created. If the window never navigates again // RenderFrameCreated won't be called and certain prefs like // "kBackgroundColor" will not be applied. auto* frame = api_web_contents->MainFrame(); if (frame) { api_web_contents->HandleNewRenderFrame(frame); } if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->Destroy(); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this || !web_contents()) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen || type_ == Type::kBrowserView) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !BUILDFLAG(IS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->ShouldIgnoreMenuShortcuts()) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (exclusive_access_manager_->HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } Profile* WebContents::GetProfile() { return nullptr; } bool WebContents::IsFullscreen() const { return owner_window_ && owner_window_->IsFullscreen(); } void WebContents::EnterFullscreen(const GURL& url, ExclusiveAccessBubbleType bubble_type, const int64_t display_id) {} void WebContents::ExitFullscreen() {} void WebContents::UpdateExclusiveAccessExitBubbleContent( const GURL& url, ExclusiveAccessBubbleType bubble_type, ExclusiveAccessBubbleHideCallback bubble_first_hide_callback, bool force_update) {} void WebContents::OnExclusiveAccessUserInput() {} content::WebContents* WebContents::GetActiveWebContents() { return web_contents(); } bool WebContents::CanUserExitFullscreen() const { return true; } bool WebContents::IsExclusiveAccessBubbleDisplayed() const { return false; } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed || !owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; SetHtmlApiFullscreen(false); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( source); } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost& render_frame_host, const content::ContextMenuParams& params) { Emit("context-menu", std::make_pair(params, &render_frame_host)); return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } void WebContents::RequestExclusivePointerAccess( content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target, bool allowed) { if (allowed) { exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( blink::mojom::PointerLockResult::kPermissionDenied); } } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission( user_gesture, last_unlocked_by_target, base::BindOnce(&WebContents::RequestExclusivePointerAccess, base::Unretained(this))); } void WebContents::LostMouseLock() { exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { exclusive_access_manager_->keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::HandleNewRenderFrame( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; // Set the background color of RenderWidgetHostView. auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences) { bool guest = IsGuest() || type_ == Type::kBrowserView; absl::optional<SkColor> color = guest ? SK_ColorTRANSPARENT : web_preferences->GetBackgroundColor(); web_contents()->SetPageBaseBackgroundColor(color); SetBackgroundColor(rwhv, color.value_or(SK_ColorWHITE)); } if (!background_throttling_) render_frame_host->GetRenderViewHost()->SetSchedulerThrottling(false); auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->Connect(); } void WebContents::OnBackgroundColorChanged() { absl::optional<SkColor> color = web_contents()->GetBackgroundColor(); if (color.has_value()) { auto* const view = web_contents()->GetRenderWidgetHostView(); static_cast<content::RenderWidgetHostViewBase*>(view) ->SetContentBackgroundColor(color.value()); } } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { HandleNewRenderFrame(render_frame_host); // RenderFrameCreated is called for speculative frames which may not be // used in certain cross-origin navigations. Invoking // RenderFrameHost::GetLifecycleState currently crashes when called for // speculative frames so we need to filter it out for now. Check // https://crbug.com/1183639 for details on when this can be removed. auto* rfh_impl = static_cast<content::RenderFrameHostImpl*>(render_frame_host); if (rfh_impl->lifecycle_state() == content::RenderFrameHostImpl::LifecycleStateImpl::kSpeculative) { return; } content::RenderFrameHost::LifecycleState lifecycle_state = render_frame_host->GetLifecycleState(); if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.SetGetter("frame", render_frame_host); Emit("frame-created", details); } } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A RenderFrameHost can be deleted when: // - A WebContents is removed and its containing frames are disposed. // - An <iframe> is removed from the DOM. // - Cross-origin navigation creates a new RFH in a separate process which // is swapped by content::RenderFrameHostManager. // // clear out objects that have been granted permissions if (!granted_devices_.empty()) { granted_devices_.erase(render_frame_host->GetFrameTreeNodeId()); } // WebFrameMain::FromRenderFrameHost(rfh) will use the RFH's FrameTreeNode ID // to find an existing instance of WebFrameMain. During a cross-origin // navigation, the deleted RFH will be the old host which was swapped out. In // this special case, we need to also ensure that WebFrameMain's internal RFH // matches before marking it as disposed. auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame && web_frame->render_frame_host() == render_frame_host) web_frame->MarkRenderFrameDisposed(); } void WebContents::RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { // During cross-origin navigation, a FrameTreeNode will swap out its RFH. // If an instance of WebFrameMain exists, it will need to have its RFH // swapped as well. // // |old_host| can be a nullptr so we use |new_host| for looking up the // WebFrameMain instance. auto* web_frame = WebFrameMain::FromFrameTreeNodeId(new_host->GetFrameTreeNodeId()); if (web_frame) { web_frame->UpdateRenderFrameHost(new_host); } } void WebContents::FrameDeleted(int frame_tree_node_id) { auto* web_frame = WebFrameMain::FromFrameTreeNodeId(frame_tree_node_id); if (web_frame) web_frame->Destroyed(); } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::PrimaryMainFrameRenderProcessGone( base::TerminationStatus status) { auto weak_this = GetWeakPtr(); Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); // User might destroy WebContents in the crashed event. if (!weak_this || !web_contents()) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); details.Set("exitCode", web_contents()->GetCrashedErrorCode()); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { Emit("focus"); } void WebContents::OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) { Emit("blur"); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); if (web_frame) web_frame->DOMContentLoaded(); if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this && web_contents()) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->ShouldUsePreferredSizeMode()) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* target_web_contents = FromID(web_contents_id); if (target_web_contents) { content::RenderFrameHost* frame = target_web_contents->MainFrame(); DCHECK(frame); v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate()); gin::Handle<WebFrameMain> web_frame_main = WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame); if (!web_frame_main->CheckRenderFrame()) return; int32_t sender_id = ID(); web_frame_main->GetRendererApi()->Message(false /* internal */, channel, std::move(arguments), sender_id); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { // Don't focus content in an inactive window. if (!owner_window()) return; #if BUILDFLAG(IS_MAC) if (!owner_window()->IsActive()) return; #else if (!owner_window()->widget()->IsActive()) return; #endif // Don't focus content after subframe navigations. if (!navigation_handle->IsInMainFrame()) return; // Only focus for top-level contents. if (type_ != Type::kBrowserWindow) return; web_contents()->SetInitialFocus(); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (owner_window_) { owner_window_->NotifyLayoutWindowControlsOverlay(); } if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } content::NavigationEntry* entry = navigation_handle->GetNavigationEntry(); // This check is needed due to an issue in Chromium // Check the Chromium issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=1178663 // If a history entry has been made and the forward/back call has been made, // proceed with setting the new title if (entry && (entry->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK)) WebContents::TitleWasSet(entry); } void WebContents::TitleWasSet(content::NavigationEntry* entry) { std::u16string final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } else { final_title = web_contents()->GetTitle(); } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); DCHECK(inspectable_web_contents_->GetDevToolsWebContents()); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::WebContentsDestroyed() { // Clear the pointer stored in wrapper. if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); // Tell WebViewGuestDelegate that the WebContents has been destroyed. if (guest_delegate_) guest_delegate_->WillDestroy(); Observe(nullptr); Emit("destroyed"); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } GURL WebContents::GetURL() const { return web_contents()->GetLastCommittedURL(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); params.transition_type = ui::PageTransitionFromInt( ui::PAGE_TRANSITION_TYPED | ui::PAGE_TRANSITION_FROM_ADDRESS_BAR); params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this || !web_contents()) return; // Required to make beforeunload handler work. NotifyUserActivation(); } // TODO(MarshallOfSound): Figure out what we need to do with post data here, I // believe the default behavior when we pass "true" is to phone out to the // delegate and then the controller expects this method to be called again with // "false" if the user approves the reload. For now this would result in // ".reload()" calls on POST data domains failing silently. Passing false would // result in them succeeding, but reposting which although more correct could be // considering a breaking change. void WebContents::Reload() { web_contents()->GetController().Reload(content::ReloadType::NORMAL, /* check_for_repost */ true); } void WebContents::ReloadIgnoringCache() { web_contents()->GetController().Reload(content::ReloadType::BYPASSING_CACHE, /* check_for_repost */ true); } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = browser_context->GetDownloadManager(); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } std::u16string WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->ShouldShowLoadingUI(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } bool WebContents::CanGoBack() const { return web_contents()->GetController().CanGoBack(); } void WebContents::GoBack() { if (CanGoBack()) web_contents()->GetController().GoBack(); } bool WebContents::CanGoForward() const { return web_contents()->GetController().CanGoForward(); } void WebContents::GoForward() { if (CanGoForward()) web_contents()->GetController().GoForward(); } bool WebContents::CanGoToOffset(int offset) const { return web_contents()->GetController().CanGoToOffset(offset); } void WebContents::GoToOffset(int offset) { if (CanGoToOffset(offset)) web_contents()->GetController().GoToOffset(offset); } bool WebContents::CanGoToIndex(int index) const { return index >= 0 && index < GetHistoryLength(); } void WebContents::GoToIndex(int index) { if (CanGoToIndex(index)) web_contents()->GetController().GoToIndex(index); } int WebContents::GetActiveIndex() const { return web_contents()->GetController().GetCurrentEntryIndex(); } void WebContents::ClearHistory() { // In some rare cases (normally while there is no real history) we are in a // state where we can't prune navigation entries if (web_contents()->GetController().CanPruneAllButLastCommitted()) { web_contents()->GetController().PruneAllButLastCommitted(); } } int WebContents::GetHistoryLength() const { return web_contents()->GetController().GetEntryCount(); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) return std::string(); content::DesktopMediaID media_id( content::DesktopMediaID::TYPE_WEB_CONTENTS, content::DesktopMediaID::kNullId, content::WebContentsMediaCaptureId(frame_host->GetProcess()->GetID(), frame_host->GetRoutingID())); auto* request_frame_host = request_web_contents->GetMainFrame(); if (!request_frame_host) return std::string(); std::string id = content::DesktopStreamsRegistry::GetInstance()->RegisterStream( request_frame_host->GetProcess()->GetID(), request_frame_host->GetRoutingID(), url::Origin::Create(request_frame_host->GetLastCommittedURL() .DeprecatedGetOriginAsURL()), media_id, "", content::kRegistryStreamTypeTab); return id; } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); if (!full_file_path.IsAbsolute()) { promise.RejectWithErrorMessage("Path must be absolute"); return handle; } auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()); if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->SetIgnoreMenuShortcuts(ignore); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, std::u16string device_name, bool silent, // <error, default_printer> std::pair<std::string, std::u16string> info) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerElectron class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } if (!info.first.empty()) { if (print_callback) std::move(print_callback).Run(false, info.first); return; } // If the user has passed a deviceName use it, otherwise use default printer. std::u16string printer_name = device_name.empty() ? info.second : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = PrintViewManagerElectron::FromWebContents(web_contents()); if (!print_view_manager) return; auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. std::u16string device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::mojom::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetList().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const std::u16string& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const std::u16string& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { std::u16string search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if BUILDFLAG(IS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !BUILDFLAG(IS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } #if !BUILDFLAG(IS_MAC) // If the view's renderer is suspended this may fail on Windows/Linux - // bail if so. See CopyFromSurface in // content/public/browser/render_widget_host_view.h. auto* rfh = web_contents()->GetMainFrame(); if (rfh && rfh->GetVisibilityState() == blink::mojom::PageVisibilityState::kHidden) { promise.Resolve(gfx::Image()); return handle; } #endif // BUILDFLAG(IS_MAC) // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; bool stay_awake = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); std::ignore = web_contents()->IncrementCapturerCount(size, stay_hidden, stay_awake); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; bool stay_awake = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); // get stayAwake arguments if they exist args->GetNext(&stay_awake); web_contents()->DecrementCapturerCount(stay_hidden, stay_awake); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronBrowser::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::NotifyUserActivation() { content::RenderFrameHost* frame = web_contents()->GetMainFrame(); if (frame) frame->NotifyUserActivation( blink::mojom::UserActivationNotificationType::kInteraction); } void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { auto* web_preferences = WebContentsPreferences::From(web_contents()); web_preferences->SetImageAnimationPolicy(new_policy); web_contents()->OnWebPreferencesChanged(); } v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("Failed to create memory dump"); return handle; } auto pid = frame_host->GetProcess()->GetProcess().Pid(); v8::Global<v8::Context> context(isolate, isolate->GetCurrentContext()); memory_instrumentation::MemoryInstrumentation::GetInstance() ->RequestGlobalDumpForPid( pid, std::vector<std::string>(), base::BindOnce(&ElectronBindings::DidReceiveMemoryDump, std::move(context), std::move(promise), pid)); return handle; } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } if (!frame_host->IsRenderFrameCreated()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::Remote<mojom::ElectronRenderer>>(); frame_host->GetRemoteInterfaces()->GetInterface( electron_renderer->BindNewPipeAndPassReceiver()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::Remote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::GrantDevicePermission( const url::Origin& origin, const base::Value* device, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { granted_devices_[render_frame_host->GetFrameTreeNodeId()][permissionType] [origin] .push_back( std::make_unique<base::Value>(device->Clone())); } std::vector<base::Value> WebContents::GetGrantedDevices( const url::Origin& origin, content::PermissionType permissionType, content::RenderFrameHost* render_frame_host) { const auto& devices_for_frame_host_it = granted_devices_.find(render_frame_host->GetFrameTreeNodeId()); if (devices_for_frame_host_it == granted_devices_.end()) return {}; const auto& current_devices_it = devices_for_frame_host_it->second.find(permissionType); if (current_devices_it == devices_for_frame_host_it->second.end()) return {}; const auto& origin_devices_it = current_devices_it->second.find(origin); if (origin_devices_it == current_devices_it->second.end()) return {}; std::vector<base::Value> results; for (const auto& object : origin_devices_it->second) results.push_back(object->Clone()); return results; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { FileSelectHelper::RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* web_contents, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents, const viz::SurfaceId& surface_id, const gfx::Size& natural_size) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance()->EnterPictureInPicture( web_contents, surface_id, natural_size); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetKey(path.AsUTF8Unsafe(), base::Value(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveKey(path); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetList()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } void WebContents::DevToolsSetEyeDropperActive(bool active) { auto* web_contents = GetWebContents(); if (!web_contents) return; if (active) { eye_dropper_ = std::make_unique<DevToolsEyeDropper>( web_contents, base::BindRepeating(&WebContents::ColorPickedInEyeDropper, base::Unretained(this))); } else { eye_dropper_.reset(); } } void WebContents::ColorPickedInEyeDropper(int r, int g, int b, int a) { base::DictionaryValue color; color.SetInteger("r", r); color.SetInteger("g", g); color.SetInteger("b", b); color.SetInteger("a", a); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.eyeDropperPickedColor", &color, nullptr, nullptr); } #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) ui::ImageModel WebContents::GetDevToolsWindowIcon() { return owner_window() ? owner_window()->GetWindowAppIcon() : ui::ImageModel{}; } #endif #if BUILDFLAG(IS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.Append(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; UpdateHtmlApiFullscreen(true); return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { UpdateHtmlApiFullscreen(false); return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->ShouldDisableHtmlFullscreenWindowResize() : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } UpdateHtmlApiFullscreen(enter_fullscreen); native_fullscreen_ = false; } void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { if (fullscreen == is_html_fullscreen()) return; html_fullscreen_ = fullscreen; // Notify renderer of the html fullscreen change. web_contents() ->GetRenderViewHost() ->GetWidget() ->SynchronizeVisualProperties(); // The embedder WebContents is separated from the frame tree of webview, so // we must manually sync their fullscreen states. if (embedder_) embedder_->SetHtmlApiFullscreen(fullscreen); if (fullscreen) { Emit("enter-html-full-screen"); owner_window_->NotifyWindowEnterHtmlFullScreen(); } else { Emit("leave-html-full-screen"); owner_window_->NotifyWindowLeaveHtmlFullScreen(); } // Make sure all child webviews quit html fullscreen. if (!fullscreen && !IsGuest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest( web_contents(), base::BindRepeating([](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); api_web_contents->SetHtmlApiFullscreen(false); return false; })); } } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("destroy", &WebContents::Destroy) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("reload", &WebContents::Reload) .SetMethod("reloadIgnoringCache", &WebContents::ReloadIgnoringCache) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("stop", &WebContents::Stop) .SetMethod("canGoBack", &WebContents::CanGoBack) .SetMethod("goBack", &WebContents::GoBack) .SetMethod("canGoForward", &WebContents::CanGoForward) .SetMethod("goForward", &WebContents::GoForward) .SetMethod("canGoToOffset", &WebContents::CanGoToOffset) .SetMethod("goToOffset", &WebContents::GoToOffset) .SetMethod("canGoToIndex", &WebContents::CanGoToIndex) .SetMethod("goToIndex", &WebContents::GoToIndex) .SetMethod("getActiveIndex", &WebContents::GetActiveIndex) .SetMethod("clearHistory", &WebContents::ClearHistory) .SetMethod("length", &WebContents::GetHistoryLength) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) .SetMethod("_getProcessMemoryInfo", &WebContents::GetProcessMemoryInfo) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, handle.get(), "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); v8::TryCatch try_catch(isolate); gin_helper::CallMethod(isolate, api_web_contents, "_init"); if (try_catch.HasCaught()) { node::errors::TriggerUncaughtException(isolate, try_catch); } } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); gin_helper::Dictionary web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->SetFromDictionary(web_preferences_dict); absl::optional<SkColor> color = existing_preferences->GetBackgroundColor(); web_contents->web_contents()->SetPageBaseBackgroundColor(color); // Because web preferences don't recognize transparency, // only set rwhv background color if a color exists auto* rwhv = web_contents->web_contents()->GetRenderWidgetHostView(); if (rwhv && color.has_value()) SetBackgroundColor(rwhv, color.value()); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } gin::Handle<WebContents> WebContentsFromDevToolsTargetID( v8::Isolate* isolate, std::string target_id) { auto agent_host = content::DevToolsAgentHost::GetForId(target_id); WebContents* contents = agent_host ? WebContents::From(agent_host->GetWebContents()) : nullptr; return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("fromDevToolsTargetId", &WebContentsFromDevToolsTargetID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
closed
electron/electron
https://github.com/electron/electron
33,034
DCHECK when calling `app.exit()` with closed windows
Discovered while triaging https://github.com/electron/electron/issues/29260 - `app.quit()` checks for closed windows but `app.exit()` doesn't, leading to a potential DCHECK. <details><summary>Stacktrace</summary> ``` [54299:0222/114036.228945:FATAL:native_window_mac.mm(1694)] Check failed: !IsClosed(). 0 Electron Framework 0x00000001230a8c99 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x0000000122fbc3d3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x0000000122fd5f3f logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x0000000122fd6f9e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000011eb85848 electron::NativeWindowMac::Cleanup() + 72 5 Electron Framework 0x000000011eb8f954 -[ElectronNSWindowDelegate windowWillClose:] + 36 6 CoreFoundation 0x00007ff80ce90f23 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12 7 CoreFoundation 0x00007ff80cf2e3f9 ___CFXRegistrationPost_block_invoke + 49 8 CoreFoundation 0x00007ff80cf2e376 _CFXRegistrationPost + 496 9 CoreFoundation 0x00007ff80ce62836 _CFXNotificationPost + 733 10 Foundation 0x00007ff80dcaa1be -[NSNotificationCenter postNotificationName:object:userInfo:] + 82 11 AppKit 0x00007ff81015602f -[NSWindow _finishClosingWindow] + 120 12 AppKit 0x00007ff80fbe248f -[NSWindow _close] + 336 13 Electron Framework 0x000000011eb80dcb electron::NativeWindowMac::CloseImmediately() + 59 14 Electron Framework 0x000000011eafb0aa electron::WindowList::DestroyAllWindows() + 282 15 Electron Framework 0x000000011ea67ce3 electron::Browser::Exit(gin::Arguments*) + 675 16 Electron Framework 0x000000011e9858d4 gin::internal::Dispatcher<void (gin::Arguments*)>::DispatchToCallbackImpl(gin::Arguments*) + 276 17 Electron Framework 0x000000011e985739 gin::internal::Dispatcher<void (gin::Arguments*)>::DispatchToCallback(v8::FunctionCallbackInfo<v8::Value> const&) + 57 18 Electron Framework 0x0000000120369278 v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) + 296 19 Electron Framework 0x0000000120367684 v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) + 1748 20 Electron Framework 0x0000000120365603 v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) + 483 21 Electron Framework 0x000000012036518d v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) + 109 22 ??? 0x0000001d07ee23f8 0x0 + 124687098872 Task trace: 0 Electron Framework 0x000000011ea18ec8 electron::api::WebContents::Destroy() + 168 1 Electron Framework 0x0000000123767802 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 994 2 Electron Framework 0x000000012348f5bc mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 428 Crash keys: "ui_scheduler_async_stack" = "0x11EA18EC8 0x123767802" "io_scheduler_async_stack" = "0x12348F5BC 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/33034
https://github.com/electron/electron/pull/33035
5b2d3910c1749f5faaeaec15d1051a2582c32596
268cd31e38f4d8b0ba81de27c73b7b1424ec9157
2022-02-22T10:40:58Z
c++
2022-02-23T15:27:54Z
shell/browser/window_list.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/window_list.h" #include <algorithm> #include "base/logging.h" #include "shell/browser/native_window.h" #include "shell/browser/window_list_observer.h" namespace { template <typename T> std::vector<base::WeakPtr<T>> ConvertToWeakPtrVector(std::vector<T*> raw_ptrs) { std::vector<base::WeakPtr<T>> converted_to_weak; converted_to_weak.reserve(raw_ptrs.size()); for (auto* raw_ptr : raw_ptrs) { converted_to_weak.push_back(raw_ptr->GetWeakPtr()); } return converted_to_weak; } } // namespace namespace electron { // static base::LazyInstance<base::ObserverList<WindowListObserver>>::Leaky WindowList::observers_ = LAZY_INSTANCE_INITIALIZER; // static WindowList* WindowList::instance_ = nullptr; // static WindowList* WindowList::GetInstance() { if (!instance_) instance_ = new WindowList; return instance_; } // static WindowList::WindowVector WindowList::GetWindows() { return GetInstance()->windows_; } // static bool WindowList::IsEmpty() { return GetInstance()->windows_.empty(); } // static void WindowList::AddWindow(NativeWindow* window) { DCHECK(window); // Push |window| on the appropriate list instance. WindowVector& windows = GetInstance()->windows_; windows.push_back(window); for (WindowListObserver& observer : observers_.Get()) observer.OnWindowAdded(window); } // static void WindowList::RemoveWindow(NativeWindow* window) { WindowVector& windows = GetInstance()->windows_; windows.erase(std::remove(windows.begin(), windows.end(), window), windows.end()); for (WindowListObserver& observer : observers_.Get()) observer.OnWindowRemoved(window); if (windows.empty()) { for (WindowListObserver& observer : observers_.Get()) observer.OnWindowAllClosed(); } } // static void WindowList::WindowCloseCancelled(NativeWindow* window) { for (WindowListObserver& observer : observers_.Get()) observer.OnWindowCloseCancelled(window); } // static void WindowList::AddObserver(WindowListObserver* observer) { observers_.Get().AddObserver(observer); } // static void WindowList::RemoveObserver(WindowListObserver* observer) { observers_.Get().RemoveObserver(observer); } // static void WindowList::CloseAllWindows() { std::vector<base::WeakPtr<NativeWindow>> weak_windows = ConvertToWeakPtrVector(GetInstance()->windows_); #if BUILDFLAG(IS_MAC) std::reverse(weak_windows.begin(), weak_windows.end()); #endif for (const auto& window : weak_windows) { if (window && !window->IsClosed()) window->Close(); } } // static void WindowList::DestroyAllWindows() { std::vector<base::WeakPtr<NativeWindow>> weak_windows = ConvertToWeakPtrVector(GetInstance()->windows_); for (const auto& window : weak_windows) { if (window) window->CloseImmediately(); } } WindowList::WindowList() = default; WindowList::~WindowList() = default; } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,034
DCHECK when calling `app.exit()` with closed windows
Discovered while triaging https://github.com/electron/electron/issues/29260 - `app.quit()` checks for closed windows but `app.exit()` doesn't, leading to a potential DCHECK. <details><summary>Stacktrace</summary> ``` [54299:0222/114036.228945:FATAL:native_window_mac.mm(1694)] Check failed: !IsClosed(). 0 Electron Framework 0x00000001230a8c99 base::debug::CollectStackTrace(void**, unsigned long) + 9 1 Electron Framework 0x0000000122fbc3d3 base::debug::StackTrace::StackTrace() + 19 2 Electron Framework 0x0000000122fd5f3f logging::LogMessage::~LogMessage() + 175 3 Electron Framework 0x0000000122fd6f9e logging::LogMessage::~LogMessage() + 14 4 Electron Framework 0x000000011eb85848 electron::NativeWindowMac::Cleanup() + 72 5 Electron Framework 0x000000011eb8f954 -[ElectronNSWindowDelegate windowWillClose:] + 36 6 CoreFoundation 0x00007ff80ce90f23 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12 7 CoreFoundation 0x00007ff80cf2e3f9 ___CFXRegistrationPost_block_invoke + 49 8 CoreFoundation 0x00007ff80cf2e376 _CFXRegistrationPost + 496 9 CoreFoundation 0x00007ff80ce62836 _CFXNotificationPost + 733 10 Foundation 0x00007ff80dcaa1be -[NSNotificationCenter postNotificationName:object:userInfo:] + 82 11 AppKit 0x00007ff81015602f -[NSWindow _finishClosingWindow] + 120 12 AppKit 0x00007ff80fbe248f -[NSWindow _close] + 336 13 Electron Framework 0x000000011eb80dcb electron::NativeWindowMac::CloseImmediately() + 59 14 Electron Framework 0x000000011eafb0aa electron::WindowList::DestroyAllWindows() + 282 15 Electron Framework 0x000000011ea67ce3 electron::Browser::Exit(gin::Arguments*) + 675 16 Electron Framework 0x000000011e9858d4 gin::internal::Dispatcher<void (gin::Arguments*)>::DispatchToCallbackImpl(gin::Arguments*) + 276 17 Electron Framework 0x000000011e985739 gin::internal::Dispatcher<void (gin::Arguments*)>::DispatchToCallback(v8::FunctionCallbackInfo<v8::Value> const&) + 57 18 Electron Framework 0x0000000120369278 v8::internal::FunctionCallbackArguments::Call(v8::internal::CallHandlerInfo) + 296 19 Electron Framework 0x0000000120367684 v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::HeapObject>, v8::internal::Handle<v8::internal::FunctionTemplateInfo>, v8::internal::Handle<v8::internal::Object>, v8::internal::BuiltinArguments) + 1748 20 Electron Framework 0x0000000120365603 v8::internal::Builtin_Impl_HandleApiCall(v8::internal::BuiltinArguments, v8::internal::Isolate*) + 483 21 Electron Framework 0x000000012036518d v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) + 109 22 ??? 0x0000001d07ee23f8 0x0 + 124687098872 Task trace: 0 Electron Framework 0x000000011ea18ec8 electron::api::WebContents::Destroy() + 168 1 Electron Framework 0x0000000123767802 IPC::(anonymous namespace)::ChannelAssociatedGroupController::Accept(mojo::Message*) + 994 2 Electron Framework 0x000000012348f5bc mojo::SimpleWatcher::Context::Notify(unsigned int, MojoHandleSignalsState, unsigned int) + 428 Crash keys: "ui_scheduler_async_stack" = "0x11EA18EC8 0x123767802" "io_scheduler_async_stack" = "0x12348F5BC 0x0" "platform" = "darwin" "process_type" = "browser" ``` </details>
https://github.com/electron/electron/issues/33034
https://github.com/electron/electron/pull/33035
5b2d3910c1749f5faaeaec15d1051a2582c32596
268cd31e38f4d8b0ba81de27c73b7b1424ec9157
2022-02-22T10:40:58Z
c++
2022-02-23T15:27:54Z
shell/browser/window_list.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/window_list.h" #include <algorithm> #include "base/logging.h" #include "shell/browser/native_window.h" #include "shell/browser/window_list_observer.h" namespace { template <typename T> std::vector<base::WeakPtr<T>> ConvertToWeakPtrVector(std::vector<T*> raw_ptrs) { std::vector<base::WeakPtr<T>> converted_to_weak; converted_to_weak.reserve(raw_ptrs.size()); for (auto* raw_ptr : raw_ptrs) { converted_to_weak.push_back(raw_ptr->GetWeakPtr()); } return converted_to_weak; } } // namespace namespace electron { // static base::LazyInstance<base::ObserverList<WindowListObserver>>::Leaky WindowList::observers_ = LAZY_INSTANCE_INITIALIZER; // static WindowList* WindowList::instance_ = nullptr; // static WindowList* WindowList::GetInstance() { if (!instance_) instance_ = new WindowList; return instance_; } // static WindowList::WindowVector WindowList::GetWindows() { return GetInstance()->windows_; } // static bool WindowList::IsEmpty() { return GetInstance()->windows_.empty(); } // static void WindowList::AddWindow(NativeWindow* window) { DCHECK(window); // Push |window| on the appropriate list instance. WindowVector& windows = GetInstance()->windows_; windows.push_back(window); for (WindowListObserver& observer : observers_.Get()) observer.OnWindowAdded(window); } // static void WindowList::RemoveWindow(NativeWindow* window) { WindowVector& windows = GetInstance()->windows_; windows.erase(std::remove(windows.begin(), windows.end(), window), windows.end()); for (WindowListObserver& observer : observers_.Get()) observer.OnWindowRemoved(window); if (windows.empty()) { for (WindowListObserver& observer : observers_.Get()) observer.OnWindowAllClosed(); } } // static void WindowList::WindowCloseCancelled(NativeWindow* window) { for (WindowListObserver& observer : observers_.Get()) observer.OnWindowCloseCancelled(window); } // static void WindowList::AddObserver(WindowListObserver* observer) { observers_.Get().AddObserver(observer); } // static void WindowList::RemoveObserver(WindowListObserver* observer) { observers_.Get().RemoveObserver(observer); } // static void WindowList::CloseAllWindows() { std::vector<base::WeakPtr<NativeWindow>> weak_windows = ConvertToWeakPtrVector(GetInstance()->windows_); #if BUILDFLAG(IS_MAC) std::reverse(weak_windows.begin(), weak_windows.end()); #endif for (const auto& window : weak_windows) { if (window && !window->IsClosed()) window->Close(); } } // static void WindowList::DestroyAllWindows() { std::vector<base::WeakPtr<NativeWindow>> weak_windows = ConvertToWeakPtrVector(GetInstance()->windows_); for (const auto& window : weak_windows) { if (window) window->CloseImmediately(); } } WindowList::WindowList() = default; WindowList::~WindowList() = default; } // namespace electron
closed
electron/electron
https://github.com/electron/electron
31,564
[Bug]: tray icon disappears after several seconds even if I declare `tray` to be global.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Big Sur 11.6 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Tray Icon would stay in the tray. ### Actual Behavior Tray Icon disappears after several seconds. ### Testcase Gist URL _No response_ ### Additional Information ```js const { app, Tray, nativeImage } = require('electron'); const path = require('path'); let tray = null; app.whenReady().then(() => { const icon = nativeImage.createFromPath( path.join(__dirname, './assets/icon.png') ); tray = new Tray('src/assets/icon.png'); tray.setTitle('Attention App'); }); ```
https://github.com/electron/electron/issues/31564
https://github.com/electron/electron/pull/33040
8cf345660c35d88bfad0b9fff25f3974482df2f2
c5a2af7811e35acf67651725d1099b15de0c6ee4
2021-10-24T11:00:04Z
c++
2022-02-24T19:03:59Z
shell/browser/api/electron_api_tray.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_tray.h" #include <string> #include "base/threading/thread_task_runner_handle.h" #include "gin/dictionary.h" #include "gin/object_template_builder.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/ui_event.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/guid_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/function_template_extensions.h" #include "shell/common/node_includes.h" #include "ui/gfx/image/image.h" namespace gin { template <> struct Converter<electron::TrayIcon::IconType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::TrayIcon::IconType* out) { using IconType = electron::TrayIcon::IconType; std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "none") { *out = IconType::kNone; return true; } else if (mode == "info") { *out = IconType::kInfo; return true; } else if (mode == "warning") { *out = IconType::kWarning; return true; } else if (mode == "error") { *out = IconType::kError; return true; } else if (mode == "custom") { *out = IconType::kCustom; return true; } } return false; } }; } // namespace gin namespace electron { namespace api { gin::WrapperInfo Tray::kWrapperInfo = {gin::kEmbedderNativeGin}; Tray::Tray(v8::Isolate* isolate, v8::Local<v8::Value> image, absl::optional<UUID> guid) : tray_icon_(TrayIcon::Create(guid)) { SetImage(isolate, image); tray_icon_->AddObserver(this); } Tray::~Tray() = default; // static gin::Handle<Tray> Tray::New(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> image, absl::optional<UUID> guid, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create Tray before app is ready"); return gin::Handle<Tray>(); } #if BUILDFLAG(IS_WIN) if (!guid.has_value() && args->Length() > 1) { thrower.ThrowError("Invalid GUID format"); return gin::Handle<Tray>(); } #endif return gin::CreateHandle(thrower.isolate(), new Tray(args->isolate(), image, guid)); } void Tray::OnClicked(const gfx::Rect& bounds, const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("click", CreateEventFromFlags(modifiers), bounds, location); } void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("double-click", CreateEventFromFlags(modifiers), bounds); } void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("right-click", CreateEventFromFlags(modifiers), bounds); } void Tray::OnBalloonShow() { Emit("balloon-show"); } void Tray::OnBalloonClicked() { Emit("balloon-click"); } void Tray::OnBalloonClosed() { Emit("balloon-closed"); } void Tray::OnDrop() { Emit("drop"); } void Tray::OnDropFiles(const std::vector<std::string>& files) { Emit("drop-files", files); } void Tray::OnDropText(const std::string& text) { Emit("drop-text", text); } void Tray::OnMouseEntered(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-enter", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseExited(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-leave", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseMoved(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-move", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseUp(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-up", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseDown(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-down", CreateEventFromFlags(modifiers), location); } void Tray::OnDragEntered() { Emit("drag-enter"); } void Tray::OnDragExited() { Emit("drag-leave"); } void Tray::OnDragEnded() { Emit("drag-end"); } void Tray::Destroy() { menu_.Reset(); tray_icon_.reset(); } bool Tray::IsDestroyed() { return !tray_icon_; } void Tray::SetImage(v8::Isolate* isolate, v8::Local<v8::Value> image) { if (!CheckAlive()) return; NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, image, &native_image)) return; #if BUILDFLAG(IS_WIN) tray_icon_->SetImage(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON))); #else tray_icon_->SetImage(native_image->image()); #endif } void Tray::SetPressedImage(v8::Isolate* isolate, v8::Local<v8::Value> image) { if (!CheckAlive()) return; NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, image, &native_image)) return; #if BUILDFLAG(IS_WIN) tray_icon_->SetPressedImage( native_image->GetHICON(GetSystemMetrics(SM_CXSMICON))); #else tray_icon_->SetPressedImage(native_image->image()); #endif } void Tray::SetToolTip(const std::string& tool_tip) { if (!CheckAlive()) return; tray_icon_->SetToolTip(tool_tip); } void Tray::SetTitle(const std::string& title, const absl::optional<gin_helper::Dictionary>& options, gin::Arguments* args) { if (!CheckAlive()) return; #if BUILDFLAG(IS_MAC) TrayIcon::TitleOptions title_options; if (options) { if (options->Get("fontType", &title_options.font_type)) { // Validate the font type if it's passed in if (title_options.font_type != "monospaced" && title_options.font_type != "monospacedDigit") { args->ThrowTypeError( "fontType must be one of 'monospaced' or 'monospacedDigit'"); return; } } else if (options->Has("fontType")) { args->ThrowTypeError( "fontType must be one of 'monospaced' or 'monospacedDigit'"); return; } } else if (args->Length() >= 2) { args->ThrowTypeError("setTitle options must be an object"); return; } tray_icon_->SetTitle(title, title_options); #endif } std::string Tray::GetTitle() { if (!CheckAlive()) return std::string(); #if BUILDFLAG(IS_MAC) return tray_icon_->GetTitle(); #else return ""; #endif } void Tray::SetIgnoreDoubleClickEvents(bool ignore) { if (!CheckAlive()) return; #if BUILDFLAG(IS_MAC) tray_icon_->SetIgnoreDoubleClickEvents(ignore); #endif } bool Tray::GetIgnoreDoubleClickEvents() { if (!CheckAlive()) return false; #if BUILDFLAG(IS_MAC) return tray_icon_->GetIgnoreDoubleClickEvents(); #else return false; #endif } void Tray::DisplayBalloon(gin_helper::ErrorThrower thrower, const gin_helper::Dictionary& options) { if (!CheckAlive()) return; TrayIcon::BalloonOptions balloon_options; if (!options.Get("title", &balloon_options.title) || !options.Get("content", &balloon_options.content)) { thrower.ThrowError("'title' and 'content' must be defined"); return; } v8::Local<v8::Value> icon_value; NativeImage* icon = nullptr; if (options.Get("icon", &icon_value) && !NativeImage::TryConvertNativeImage(thrower.isolate(), icon_value, &icon)) { return; } options.Get("iconType", &balloon_options.icon_type); options.Get("largeIcon", &balloon_options.large_icon); options.Get("noSound", &balloon_options.no_sound); options.Get("respectQuietTime", &balloon_options.respect_quiet_time); if (icon) { #if BUILDFLAG(IS_WIN) balloon_options.icon = icon->GetHICON( GetSystemMetrics(balloon_options.large_icon ? SM_CXICON : SM_CXSMICON)); #else balloon_options.icon = icon->image(); #endif } tray_icon_->DisplayBalloon(balloon_options); } void Tray::RemoveBalloon() { if (!CheckAlive()) return; tray_icon_->RemoveBalloon(); } void Tray::Focus() { if (!CheckAlive()) return; tray_icon_->Focus(); } void Tray::PopUpContextMenu(gin::Arguments* args) { if (!CheckAlive()) return; gin::Handle<Menu> menu; gfx::Point pos; v8::Local<v8::Value> first_arg; if (args->GetNext(&first_arg)) { if (!gin::ConvertFromV8(args->isolate(), first_arg, &menu)) { if (!gin::ConvertFromV8(args->isolate(), first_arg, &pos)) { args->ThrowError(); return; } } else if (args->Length() >= 2) { if (!args->GetNext(&pos)) { args->ThrowError(); return; } } } tray_icon_->PopUpContextMenu(pos, menu.IsEmpty() ? nullptr : menu->model()); } void Tray::CloseContextMenu() { if (!CheckAlive()) return; tray_icon_->CloseContextMenu(); } void Tray::SetContextMenu(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> arg) { if (!CheckAlive()) return; gin::Handle<Menu> menu; if (arg->IsNull()) { menu_.Reset(); tray_icon_->SetContextMenu(nullptr); } else if (gin::ConvertFromV8(thrower.isolate(), arg, &menu)) { menu_.Reset(thrower.isolate(), menu.ToV8()); tray_icon_->SetContextMenu(menu->model()); } else { thrower.ThrowTypeError("Must pass Menu or null"); } } gfx::Rect Tray::GetBounds() { if (!CheckAlive()) return gfx::Rect(); return tray_icon_->GetBounds(); } bool Tray::CheckAlive() { if (!tray_icon_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope scope(isolate); gin_helper::ErrorThrower(isolate).ThrowError("Tray is destroyed"); return false; } return true; } // static v8::Local<v8::ObjectTemplate> Tray::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { return gin::ObjectTemplateBuilder(isolate, "Tray", templ) .SetMethod("destroy", &Tray::Destroy) .SetMethod("isDestroyed", &Tray::IsDestroyed) .SetMethod("setImage", &Tray::SetImage) .SetMethod("setPressedImage", &Tray::SetPressedImage) .SetMethod("setToolTip", &Tray::SetToolTip) .SetMethod("setTitle", &Tray::SetTitle) .SetMethod("getTitle", &Tray::GetTitle) .SetMethod("setIgnoreDoubleClickEvents", &Tray::SetIgnoreDoubleClickEvents) .SetMethod("getIgnoreDoubleClickEvents", &Tray::GetIgnoreDoubleClickEvents) .SetMethod("displayBalloon", &Tray::DisplayBalloon) .SetMethod("removeBalloon", &Tray::RemoveBalloon) .SetMethod("focus", &Tray::Focus) .SetMethod("popUpContextMenu", &Tray::PopUpContextMenu) .SetMethod("closeContextMenu", &Tray::CloseContextMenu) .SetMethod("setContextMenu", &Tray::SetContextMenu) .SetMethod("getBounds", &Tray::GetBounds) .Build(); } } // namespace api } // namespace electron namespace { using electron::api::Tray; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin::Dictionary dict(isolate, exports); dict.Set("Tray", Tray::GetConstructor(context)); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_tray, Initialize)
closed
electron/electron
https://github.com/electron/electron
31,564
[Bug]: tray icon disappears after several seconds even if I declare `tray` to be global.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Big Sur 11.6 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Tray Icon would stay in the tray. ### Actual Behavior Tray Icon disappears after several seconds. ### Testcase Gist URL _No response_ ### Additional Information ```js const { app, Tray, nativeImage } = require('electron'); const path = require('path'); let tray = null; app.whenReady().then(() => { const icon = nativeImage.createFromPath( path.join(__dirname, './assets/icon.png') ); tray = new Tray('src/assets/icon.png'); tray.setTitle('Attention App'); }); ```
https://github.com/electron/electron/issues/31564
https://github.com/electron/electron/pull/33040
8cf345660c35d88bfad0b9fff25f3974482df2f2
c5a2af7811e35acf67651725d1099b15de0c6ee4
2021-10-24T11:00:04Z
c++
2022-02-24T19:03:59Z
shell/browser/api/electron_api_tray.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_TRAY_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_TRAY_H_ #include <memory> #include <string> #include <vector> #include "gin/handle.h" #include "gin/wrappable.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/ui/tray_icon.h" #include "shell/browser/ui/tray_icon_observer.h" #include "shell/common/gin_converters/guid_converter.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" namespace gfx { class Image; } namespace gin_helper { class Dictionary; } namespace electron { namespace api { class Menu; class Tray : public gin::Wrappable<Tray>, public gin_helper::EventEmitterMixin<Tray>, public gin_helper::Constructible<Tray>, public gin_helper::CleanedUpAtExit, public TrayIconObserver { public: // gin_helper::Constructible static gin::Handle<Tray> New(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> image, absl::optional<UUID> guid, gin::Arguments* args); static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; // disable copy Tray(const Tray&) = delete; Tray& operator=(const Tray&) = delete; private: Tray(v8::Isolate* isolate, v8::Local<v8::Value> image, absl::optional<UUID> guid); ~Tray() override; // TrayIconObserver: void OnClicked(const gfx::Rect& bounds, const gfx::Point& location, int modifiers) override; void OnDoubleClicked(const gfx::Rect& bounds, int modifiers) override; void OnRightClicked(const gfx::Rect& bounds, int modifiers) override; void OnBalloonShow() override; void OnBalloonClicked() override; void OnBalloonClosed() override; void OnDrop() override; void OnDropFiles(const std::vector<std::string>& files) override; void OnDropText(const std::string& text) override; void OnDragEntered() override; void OnDragExited() override; void OnDragEnded() override; void OnMouseUp(const gfx::Point& location, int modifiers) override; void OnMouseDown(const gfx::Point& location, int modifiers) override; void OnMouseEntered(const gfx::Point& location, int modifiers) override; void OnMouseExited(const gfx::Point& location, int modifiers) override; void OnMouseMoved(const gfx::Point& location, int modifiers) override; // JS API: void Destroy(); bool IsDestroyed(); void SetImage(v8::Isolate* isolate, v8::Local<v8::Value> image); void SetPressedImage(v8::Isolate* isolate, v8::Local<v8::Value> image); void SetToolTip(const std::string& tool_tip); void SetTitle(const std::string& title, const absl::optional<gin_helper::Dictionary>& options, gin::Arguments* args); std::string GetTitle(); void SetIgnoreDoubleClickEvents(bool ignore); bool GetIgnoreDoubleClickEvents(); void DisplayBalloon(gin_helper::ErrorThrower thrower, const gin_helper::Dictionary& options); void RemoveBalloon(); void Focus(); void PopUpContextMenu(gin::Arguments* args); void CloseContextMenu(); void SetContextMenu(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> arg); gfx::Rect GetBounds(); bool CheckAlive(); v8::Global<v8::Value> menu_; std::unique_ptr<TrayIcon> tray_icon_; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_TRAY_H_
closed
electron/electron
https://github.com/electron/electron
31,564
[Bug]: tray icon disappears after several seconds even if I declare `tray` to be global.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Big Sur 11.6 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Tray Icon would stay in the tray. ### Actual Behavior Tray Icon disappears after several seconds. ### Testcase Gist URL _No response_ ### Additional Information ```js const { app, Tray, nativeImage } = require('electron'); const path = require('path'); let tray = null; app.whenReady().then(() => { const icon = nativeImage.createFromPath( path.join(__dirname, './assets/icon.png') ); tray = new Tray('src/assets/icon.png'); tray.setTitle('Attention App'); }); ```
https://github.com/electron/electron/issues/31564
https://github.com/electron/electron/pull/33040
8cf345660c35d88bfad0b9fff25f3974482df2f2
c5a2af7811e35acf67651725d1099b15de0c6ee4
2021-10-24T11:00:04Z
c++
2022-02-24T19:03:59Z
shell/browser/api/electron_api_tray.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_tray.h" #include <string> #include "base/threading/thread_task_runner_handle.h" #include "gin/dictionary.h" #include "gin/object_template_builder.h" #include "shell/browser/api/electron_api_menu.h" #include "shell/browser/api/ui_event.h" #include "shell/browser/browser.h" #include "shell/browser/javascript_environment.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/guid_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/function_template_extensions.h" #include "shell/common/node_includes.h" #include "ui/gfx/image/image.h" namespace gin { template <> struct Converter<electron::TrayIcon::IconType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::TrayIcon::IconType* out) { using IconType = electron::TrayIcon::IconType; std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "none") { *out = IconType::kNone; return true; } else if (mode == "info") { *out = IconType::kInfo; return true; } else if (mode == "warning") { *out = IconType::kWarning; return true; } else if (mode == "error") { *out = IconType::kError; return true; } else if (mode == "custom") { *out = IconType::kCustom; return true; } } return false; } }; } // namespace gin namespace electron { namespace api { gin::WrapperInfo Tray::kWrapperInfo = {gin::kEmbedderNativeGin}; Tray::Tray(v8::Isolate* isolate, v8::Local<v8::Value> image, absl::optional<UUID> guid) : tray_icon_(TrayIcon::Create(guid)) { SetImage(isolate, image); tray_icon_->AddObserver(this); } Tray::~Tray() = default; // static gin::Handle<Tray> Tray::New(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> image, absl::optional<UUID> guid, gin::Arguments* args) { if (!Browser::Get()->is_ready()) { thrower.ThrowError("Cannot create Tray before app is ready"); return gin::Handle<Tray>(); } #if BUILDFLAG(IS_WIN) if (!guid.has_value() && args->Length() > 1) { thrower.ThrowError("Invalid GUID format"); return gin::Handle<Tray>(); } #endif return gin::CreateHandle(thrower.isolate(), new Tray(args->isolate(), image, guid)); } void Tray::OnClicked(const gfx::Rect& bounds, const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("click", CreateEventFromFlags(modifiers), bounds, location); } void Tray::OnDoubleClicked(const gfx::Rect& bounds, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("double-click", CreateEventFromFlags(modifiers), bounds); } void Tray::OnRightClicked(const gfx::Rect& bounds, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("right-click", CreateEventFromFlags(modifiers), bounds); } void Tray::OnBalloonShow() { Emit("balloon-show"); } void Tray::OnBalloonClicked() { Emit("balloon-click"); } void Tray::OnBalloonClosed() { Emit("balloon-closed"); } void Tray::OnDrop() { Emit("drop"); } void Tray::OnDropFiles(const std::vector<std::string>& files) { Emit("drop-files", files); } void Tray::OnDropText(const std::string& text) { Emit("drop-text", text); } void Tray::OnMouseEntered(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-enter", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseExited(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-leave", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseMoved(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-move", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseUp(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-up", CreateEventFromFlags(modifiers), location); } void Tray::OnMouseDown(const gfx::Point& location, int modifiers) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); EmitCustomEvent("mouse-down", CreateEventFromFlags(modifiers), location); } void Tray::OnDragEntered() { Emit("drag-enter"); } void Tray::OnDragExited() { Emit("drag-leave"); } void Tray::OnDragEnded() { Emit("drag-end"); } void Tray::Destroy() { menu_.Reset(); tray_icon_.reset(); } bool Tray::IsDestroyed() { return !tray_icon_; } void Tray::SetImage(v8::Isolate* isolate, v8::Local<v8::Value> image) { if (!CheckAlive()) return; NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, image, &native_image)) return; #if BUILDFLAG(IS_WIN) tray_icon_->SetImage(native_image->GetHICON(GetSystemMetrics(SM_CXSMICON))); #else tray_icon_->SetImage(native_image->image()); #endif } void Tray::SetPressedImage(v8::Isolate* isolate, v8::Local<v8::Value> image) { if (!CheckAlive()) return; NativeImage* native_image = nullptr; if (!NativeImage::TryConvertNativeImage(isolate, image, &native_image)) return; #if BUILDFLAG(IS_WIN) tray_icon_->SetPressedImage( native_image->GetHICON(GetSystemMetrics(SM_CXSMICON))); #else tray_icon_->SetPressedImage(native_image->image()); #endif } void Tray::SetToolTip(const std::string& tool_tip) { if (!CheckAlive()) return; tray_icon_->SetToolTip(tool_tip); } void Tray::SetTitle(const std::string& title, const absl::optional<gin_helper::Dictionary>& options, gin::Arguments* args) { if (!CheckAlive()) return; #if BUILDFLAG(IS_MAC) TrayIcon::TitleOptions title_options; if (options) { if (options->Get("fontType", &title_options.font_type)) { // Validate the font type if it's passed in if (title_options.font_type != "monospaced" && title_options.font_type != "monospacedDigit") { args->ThrowTypeError( "fontType must be one of 'monospaced' or 'monospacedDigit'"); return; } } else if (options->Has("fontType")) { args->ThrowTypeError( "fontType must be one of 'monospaced' or 'monospacedDigit'"); return; } } else if (args->Length() >= 2) { args->ThrowTypeError("setTitle options must be an object"); return; } tray_icon_->SetTitle(title, title_options); #endif } std::string Tray::GetTitle() { if (!CheckAlive()) return std::string(); #if BUILDFLAG(IS_MAC) return tray_icon_->GetTitle(); #else return ""; #endif } void Tray::SetIgnoreDoubleClickEvents(bool ignore) { if (!CheckAlive()) return; #if BUILDFLAG(IS_MAC) tray_icon_->SetIgnoreDoubleClickEvents(ignore); #endif } bool Tray::GetIgnoreDoubleClickEvents() { if (!CheckAlive()) return false; #if BUILDFLAG(IS_MAC) return tray_icon_->GetIgnoreDoubleClickEvents(); #else return false; #endif } void Tray::DisplayBalloon(gin_helper::ErrorThrower thrower, const gin_helper::Dictionary& options) { if (!CheckAlive()) return; TrayIcon::BalloonOptions balloon_options; if (!options.Get("title", &balloon_options.title) || !options.Get("content", &balloon_options.content)) { thrower.ThrowError("'title' and 'content' must be defined"); return; } v8::Local<v8::Value> icon_value; NativeImage* icon = nullptr; if (options.Get("icon", &icon_value) && !NativeImage::TryConvertNativeImage(thrower.isolate(), icon_value, &icon)) { return; } options.Get("iconType", &balloon_options.icon_type); options.Get("largeIcon", &balloon_options.large_icon); options.Get("noSound", &balloon_options.no_sound); options.Get("respectQuietTime", &balloon_options.respect_quiet_time); if (icon) { #if BUILDFLAG(IS_WIN) balloon_options.icon = icon->GetHICON( GetSystemMetrics(balloon_options.large_icon ? SM_CXICON : SM_CXSMICON)); #else balloon_options.icon = icon->image(); #endif } tray_icon_->DisplayBalloon(balloon_options); } void Tray::RemoveBalloon() { if (!CheckAlive()) return; tray_icon_->RemoveBalloon(); } void Tray::Focus() { if (!CheckAlive()) return; tray_icon_->Focus(); } void Tray::PopUpContextMenu(gin::Arguments* args) { if (!CheckAlive()) return; gin::Handle<Menu> menu; gfx::Point pos; v8::Local<v8::Value> first_arg; if (args->GetNext(&first_arg)) { if (!gin::ConvertFromV8(args->isolate(), first_arg, &menu)) { if (!gin::ConvertFromV8(args->isolate(), first_arg, &pos)) { args->ThrowError(); return; } } else if (args->Length() >= 2) { if (!args->GetNext(&pos)) { args->ThrowError(); return; } } } tray_icon_->PopUpContextMenu(pos, menu.IsEmpty() ? nullptr : menu->model()); } void Tray::CloseContextMenu() { if (!CheckAlive()) return; tray_icon_->CloseContextMenu(); } void Tray::SetContextMenu(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> arg) { if (!CheckAlive()) return; gin::Handle<Menu> menu; if (arg->IsNull()) { menu_.Reset(); tray_icon_->SetContextMenu(nullptr); } else if (gin::ConvertFromV8(thrower.isolate(), arg, &menu)) { menu_.Reset(thrower.isolate(), menu.ToV8()); tray_icon_->SetContextMenu(menu->model()); } else { thrower.ThrowTypeError("Must pass Menu or null"); } } gfx::Rect Tray::GetBounds() { if (!CheckAlive()) return gfx::Rect(); return tray_icon_->GetBounds(); } bool Tray::CheckAlive() { if (!tray_icon_) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope scope(isolate); gin_helper::ErrorThrower(isolate).ThrowError("Tray is destroyed"); return false; } return true; } // static v8::Local<v8::ObjectTemplate> Tray::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { return gin::ObjectTemplateBuilder(isolate, "Tray", templ) .SetMethod("destroy", &Tray::Destroy) .SetMethod("isDestroyed", &Tray::IsDestroyed) .SetMethod("setImage", &Tray::SetImage) .SetMethod("setPressedImage", &Tray::SetPressedImage) .SetMethod("setToolTip", &Tray::SetToolTip) .SetMethod("setTitle", &Tray::SetTitle) .SetMethod("getTitle", &Tray::GetTitle) .SetMethod("setIgnoreDoubleClickEvents", &Tray::SetIgnoreDoubleClickEvents) .SetMethod("getIgnoreDoubleClickEvents", &Tray::GetIgnoreDoubleClickEvents) .SetMethod("displayBalloon", &Tray::DisplayBalloon) .SetMethod("removeBalloon", &Tray::RemoveBalloon) .SetMethod("focus", &Tray::Focus) .SetMethod("popUpContextMenu", &Tray::PopUpContextMenu) .SetMethod("closeContextMenu", &Tray::CloseContextMenu) .SetMethod("setContextMenu", &Tray::SetContextMenu) .SetMethod("getBounds", &Tray::GetBounds) .Build(); } } // namespace api } // namespace electron namespace { using electron::api::Tray; void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin::Dictionary dict(isolate, exports); dict.Set("Tray", Tray::GetConstructor(context)); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_tray, Initialize)
closed
electron/electron
https://github.com/electron/electron
31,564
[Bug]: tray icon disappears after several seconds even if I declare `tray` to be global.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.3.0 ### What operating system are you using? macOS ### Operating System Version macOS Big Sur 11.6 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior Tray Icon would stay in the tray. ### Actual Behavior Tray Icon disappears after several seconds. ### Testcase Gist URL _No response_ ### Additional Information ```js const { app, Tray, nativeImage } = require('electron'); const path = require('path'); let tray = null; app.whenReady().then(() => { const icon = nativeImage.createFromPath( path.join(__dirname, './assets/icon.png') ); tray = new Tray('src/assets/icon.png'); tray.setTitle('Attention App'); }); ```
https://github.com/electron/electron/issues/31564
https://github.com/electron/electron/pull/33040
8cf345660c35d88bfad0b9fff25f3974482df2f2
c5a2af7811e35acf67651725d1099b15de0c6ee4
2021-10-24T11:00:04Z
c++
2022-02-24T19:03:59Z
shell/browser/api/electron_api_tray.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_TRAY_H_ #define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_TRAY_H_ #include <memory> #include <string> #include <vector> #include "gin/handle.h" #include "gin/wrappable.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/ui/tray_icon.h" #include "shell/browser/ui/tray_icon_observer.h" #include "shell/common/gin_converters/guid_converter.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/error_thrower.h" namespace gfx { class Image; } namespace gin_helper { class Dictionary; } namespace electron { namespace api { class Menu; class Tray : public gin::Wrappable<Tray>, public gin_helper::EventEmitterMixin<Tray>, public gin_helper::Constructible<Tray>, public gin_helper::CleanedUpAtExit, public TrayIconObserver { public: // gin_helper::Constructible static gin::Handle<Tray> New(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> image, absl::optional<UUID> guid, gin::Arguments* args); static v8::Local<v8::ObjectTemplate> FillObjectTemplate( v8::Isolate*, v8::Local<v8::ObjectTemplate>); // gin::Wrappable static gin::WrapperInfo kWrapperInfo; // disable copy Tray(const Tray&) = delete; Tray& operator=(const Tray&) = delete; private: Tray(v8::Isolate* isolate, v8::Local<v8::Value> image, absl::optional<UUID> guid); ~Tray() override; // TrayIconObserver: void OnClicked(const gfx::Rect& bounds, const gfx::Point& location, int modifiers) override; void OnDoubleClicked(const gfx::Rect& bounds, int modifiers) override; void OnRightClicked(const gfx::Rect& bounds, int modifiers) override; void OnBalloonShow() override; void OnBalloonClicked() override; void OnBalloonClosed() override; void OnDrop() override; void OnDropFiles(const std::vector<std::string>& files) override; void OnDropText(const std::string& text) override; void OnDragEntered() override; void OnDragExited() override; void OnDragEnded() override; void OnMouseUp(const gfx::Point& location, int modifiers) override; void OnMouseDown(const gfx::Point& location, int modifiers) override; void OnMouseEntered(const gfx::Point& location, int modifiers) override; void OnMouseExited(const gfx::Point& location, int modifiers) override; void OnMouseMoved(const gfx::Point& location, int modifiers) override; // JS API: void Destroy(); bool IsDestroyed(); void SetImage(v8::Isolate* isolate, v8::Local<v8::Value> image); void SetPressedImage(v8::Isolate* isolate, v8::Local<v8::Value> image); void SetToolTip(const std::string& tool_tip); void SetTitle(const std::string& title, const absl::optional<gin_helper::Dictionary>& options, gin::Arguments* args); std::string GetTitle(); void SetIgnoreDoubleClickEvents(bool ignore); bool GetIgnoreDoubleClickEvents(); void DisplayBalloon(gin_helper::ErrorThrower thrower, const gin_helper::Dictionary& options); void RemoveBalloon(); void Focus(); void PopUpContextMenu(gin::Arguments* args); void CloseContextMenu(); void SetContextMenu(gin_helper::ErrorThrower thrower, v8::Local<v8::Value> arg); gfx::Rect GetBounds(); bool CheckAlive(); v8::Global<v8::Value> menu_; std::unique_ptr<TrayIcon> tray_icon_; }; } // namespace api } // namespace electron #endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_TRAY_H_
closed
electron/electron
https://github.com/electron/electron
33,008
[Bug]: electron17 tray.setPressedImage invalid
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.1 ### What operating system are you using? macOS ### Operating System Version Big Sur 11.2.3 ### What arch are you using? x64 ### Last Known Working Electron version 2.0.7 ### Expected Behavior Click the tray menu to change icons ### Actual Behavior No change on tray icon click ### Testcase Gist URL _No response_ ### Additional Information ``` function buildTray() { let icon = null let iconDark = null if (process.platform == 'darwin') { let { nativeTheme } = require('electron') let iconLight = nativeImage.createFromPath(path.resolve(__dirname, '../assets/img/light/icon_light.png')) iconDark = nativeImage.createFromPath(path.resolve(__dirname, '../assets/img/dark/icon_dark.png')) if (nativeTheme.shouldUseDarkColors) { //dark icon = iconDark console.log("dark") } else { //light icon = iconLight console.log("light") } } else { icon = nativeImage.createFromPath(path.resolve(__dirname, '../assets/img/icon_win.png')); } if (null == tray) { tray = new Tray(icon) } else { tray.setImage(icon) } if (process.platform == 'darwin') { console.log("setPressedImage.iconDark") tray.setPressedImage(iconDark) } } ```
https://github.com/electron/electron/issues/33008
https://github.com/electron/electron/pull/33026
1e50f7d2b64832aa98e5adcddd9af20d7ed72783
283fa2b79d44cd18b9d4865edaf65a3e107207ce
2022-02-21T03:07:33Z
c++
2022-02-28T22:59:27Z
shell/browser/ui/tray_icon_cocoa.mm
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/tray_icon_cocoa.h" #include <string> #include <vector> #include "base/message_loop/message_pump_mac.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "shell/browser/ui/cocoa/NSString+ANSI.h" #include "shell/browser/ui/cocoa/electron_menu_controller.h" #include "ui/events/cocoa/cocoa_event_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/native_theme/native_theme.h" @interface StatusItemView : NSView { electron::TrayIconCocoa* trayIcon_; // weak ElectronMenuController* menuController_; // weak BOOL ignoreDoubleClickEvents_; base::scoped_nsobject<NSStatusItem> statusItem_; base::scoped_nsobject<NSTrackingArea> trackingArea_; } @end // @interface StatusItemView @implementation StatusItemView - (void)dealloc { trayIcon_ = nil; menuController_ = nil; [super dealloc]; } - (id)initWithIcon:(electron::TrayIconCocoa*)icon { trayIcon_ = icon; menuController_ = nil; ignoreDoubleClickEvents_ = NO; if ((self = [super initWithFrame:CGRectZero])) { [self registerForDraggedTypes:@[ NSFilenamesPboardType, NSStringPboardType, ]]; // Create the status item. NSStatusItem* item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; statusItem_.reset([item retain]); [[statusItem_ button] addSubview:self]; // inject custom view [self updateDimensions]; } return self; } - (void)updateDimensions { [self setFrame:[statusItem_ button].frame]; } - (void)updateTrackingAreas { // Use NSTrackingArea for listening to mouseEnter, mouseExit, and mouseMove // events. [self removeTrackingArea:trackingArea_]; trackingArea_.reset([[NSTrackingArea alloc] initWithRect:[self bounds] options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways owner:self userInfo:nil]); [self addTrackingArea:trackingArea_]; } - (void)removeItem { // Turn off tracking events to prevent crash. if (trackingArea_) { [self removeTrackingArea:trackingArea_]; trackingArea_.reset(); } [[NSStatusBar systemStatusBar] removeStatusItem:statusItem_]; [self removeFromSuperview]; statusItem_.reset(); } - (void)setImage:(NSImage*)image { [[statusItem_ button] setImage:image]; [self updateDimensions]; } - (void)setAlternateImage:(NSImage*)image { [[statusItem_ button] setAlternateImage:image]; } - (void)setIgnoreDoubleClickEvents:(BOOL)ignore { ignoreDoubleClickEvents_ = ignore; } - (BOOL)getIgnoreDoubleClickEvents { return ignoreDoubleClickEvents_; } - (void)setTitle:(NSString*)title font_type:(NSString*)font_type { NSMutableAttributedString* attributed_title = [[NSMutableAttributedString alloc] initWithString:title]; if ([title containsANSICodes]) { attributed_title = [title attributedStringParsingANSICodes]; } // Change font type, if specified CGFloat existing_size = [[[statusItem_ button] font] pointSize]; if ([font_type isEqualToString:@"monospaced"]) { if (@available(macOS 10.15, *)) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } } else if ([font_type isEqualToString:@"monospacedDigit"]) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedDigitSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } // Set title [[statusItem_ button] setAttributedTitle:attributed_title]; // Fix icon margins. if (title.length > 0) { [[statusItem_ button] setImagePosition:NSImageLeft]; } else { [[statusItem_ button] setImagePosition:NSImageOnly]; } [self updateDimensions]; } - (NSString*)title { return [statusItem_ button].title; } - (void)setMenuController:(ElectronMenuController*)menu { menuController_ = menu; [statusItem_ setMenu:[menuController_ menu]]; } - (void)handleClickNotifications:(NSEvent*)event { // If we are ignoring double click events, we should ignore the `clickCount` // value and immediately emit a click event. BOOL shouldBeHandledAsASingleClick = (event.clickCount == 1) || ignoreDoubleClickEvents_; if (shouldBeHandledAsASingleClick) trayIcon_->NotifyClicked( gfx::ScreenRectFromNSRect(event.window.frame), gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Double click event. BOOL shouldBeHandledAsADoubleClick = (event.clickCount == 2) && !ignoreDoubleClickEvents_; if (shouldBeHandledAsADoubleClick) trayIcon_->NotifyDoubleClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseDown:(NSEvent*)event { trayIcon_->NotifyMouseDown( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Pass click to superclass to show menu. Custom mouseUp handler won't be // invoked. if (menuController_) { [self handleClickNotifications:event]; [super mouseDown:event]; } else { [[statusItem_ button] highlight:YES]; } } - (void)mouseUp:(NSEvent*)event { [[statusItem_ button] highlight:NO]; trayIcon_->NotifyMouseUp( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); [self handleClickNotifications:event]; } - (void)popUpContextMenu:(electron::ElectronMenuModel*)menu_model { // Make sure events can be pumped while the menu is up. base::CurrentThread::ScopedNestableTaskAllower allow; // Show a custom menu. if (menu_model) { base::scoped_nsobject<ElectronMenuController> menuController( [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); // Hacky way to mimic design of ordinary tray menu. [statusItem_ setMenu:[menuController menu]]; // -performClick: is a blocking call, which will run the task loop inside // itself. This can potentially include running JS, which can result in // this object being released. We take a temporary reference here to make // sure we stay alive long enough to successfully return from this // function. // TODO(nornagon/codebytere): Avoid nesting task loops here. [self retain]; [[statusItem_ button] performClick:self]; [statusItem_ setMenu:[menuController_ menu]]; [self release]; return; } if (menuController_ && ![menuController_ isMenuOpen]) { // Ensure the UI can update while the menu is fading out. base::ScopedPumpMessagesInPrivateModes pump_private; [[statusItem_ button] performClick:self]; } } - (void)closeContextMenu { if (menuController_) { [menuController_ cancel]; } } - (void)rightMouseUp:(NSEvent*)event { trayIcon_->NotifyRightClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEntered(); return NSDragOperationCopy; } - (void)mouseExited:(NSEvent*)event { trayIcon_->NotifyMouseExited( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseEntered:(NSEvent*)event { trayIcon_->NotifyMouseEntered( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseMoved:(NSEvent*)event { trayIcon_->NotifyMouseMoved( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)draggingExited:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragExited(); } - (void)draggingEnded:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEnded(); if (NSPointInRect([sender draggingLocation], self.frame)) { trayIcon_->NotifyDrop(); } } - (BOOL)handleDrop:(id<NSDraggingInfo>)sender { NSPasteboard* pboard = [sender draggingPasteboard]; if ([[pboard types] containsObject:NSFilenamesPboardType]) { std::vector<std::string> dropFiles; NSArray* files = [pboard propertyListForType:NSFilenamesPboardType]; for (NSString* file in files) dropFiles.push_back(base::SysNSStringToUTF8(file)); trayIcon_->NotifyDropFiles(dropFiles); return YES; } else if ([[pboard types] containsObject:NSStringPboardType]) { NSString* dropText = [pboard stringForType:NSStringPboardType]; trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText)); return YES; } return NO; } - (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender { return YES; } - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender { [self handleDrop:sender]; return YES; } @end namespace electron { TrayIconCocoa::TrayIconCocoa() { status_item_view_.reset([[StatusItemView alloc] initWithIcon:this]); } TrayIconCocoa::~TrayIconCocoa() { [status_item_view_ removeItem]; } void TrayIconCocoa::SetImage(const gfx::Image& image) { [status_item_view_ setImage:image.AsNSImage()]; } void TrayIconCocoa::SetPressedImage(const gfx::Image& image) { [status_item_view_ setAlternateImage:image.AsNSImage()]; } void TrayIconCocoa::SetToolTip(const std::string& tool_tip) { [status_item_view_ setToolTip:base::SysUTF8ToNSString(tool_tip)]; } void TrayIconCocoa::SetTitle(const std::string& title, const TitleOptions& options) { [status_item_view_ setTitle:base::SysUTF8ToNSString(title) font_type:base::SysUTF8ToNSString(options.font_type)]; } std::string TrayIconCocoa::GetTitle() { return base::SysNSStringToUTF8([status_item_view_ title]); } void TrayIconCocoa::SetIgnoreDoubleClickEvents(bool ignore) { [status_item_view_ setIgnoreDoubleClickEvents:ignore]; } bool TrayIconCocoa::GetIgnoreDoubleClickEvents() { return [status_item_view_ getIgnoreDoubleClickEvents]; } void TrayIconCocoa::PopUpOnUI(ElectronMenuModel* menu_model) { [status_item_view_ popUpContextMenu:menu_model]; } void TrayIconCocoa::PopUpContextMenu(const gfx::Point& pos, ElectronMenuModel* menu_model) { base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TrayIconCocoa::PopUpOnUI, weak_factory_.GetWeakPtr(), base::Unretained(menu_model))); } void TrayIconCocoa::CloseContextMenu() { [status_item_view_ closeContextMenu]; } void TrayIconCocoa::SetContextMenu(ElectronMenuModel* menu_model) { if (menu_model) { // Create native menu. menu_.reset([[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); } else { menu_.reset(); } [status_item_view_ setMenuController:menu_.get()]; } gfx::Rect TrayIconCocoa::GetBounds() { return gfx::ScreenRectFromNSRect([status_item_view_ window].frame); } // static TrayIcon* TrayIcon::Create(absl::optional<UUID> guid) { return new TrayIconCocoa; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,008
[Bug]: electron17 tray.setPressedImage invalid
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.1 ### What operating system are you using? macOS ### Operating System Version Big Sur 11.2.3 ### What arch are you using? x64 ### Last Known Working Electron version 2.0.7 ### Expected Behavior Click the tray menu to change icons ### Actual Behavior No change on tray icon click ### Testcase Gist URL _No response_ ### Additional Information ``` function buildTray() { let icon = null let iconDark = null if (process.platform == 'darwin') { let { nativeTheme } = require('electron') let iconLight = nativeImage.createFromPath(path.resolve(__dirname, '../assets/img/light/icon_light.png')) iconDark = nativeImage.createFromPath(path.resolve(__dirname, '../assets/img/dark/icon_dark.png')) if (nativeTheme.shouldUseDarkColors) { //dark icon = iconDark console.log("dark") } else { //light icon = iconLight console.log("light") } } else { icon = nativeImage.createFromPath(path.resolve(__dirname, '../assets/img/icon_win.png')); } if (null == tray) { tray = new Tray(icon) } else { tray.setImage(icon) } if (process.platform == 'darwin') { console.log("setPressedImage.iconDark") tray.setPressedImage(iconDark) } } ```
https://github.com/electron/electron/issues/33008
https://github.com/electron/electron/pull/33026
1e50f7d2b64832aa98e5adcddd9af20d7ed72783
283fa2b79d44cd18b9d4865edaf65a3e107207ce
2022-02-21T03:07:33Z
c++
2022-02-28T22:59:27Z
shell/browser/ui/tray_icon_cocoa.mm
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/tray_icon_cocoa.h" #include <string> #include <vector> #include "base/message_loop/message_pump_mac.h" #include "base/strings/sys_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "shell/browser/ui/cocoa/NSString+ANSI.h" #include "shell/browser/ui/cocoa/electron_menu_controller.h" #include "ui/events/cocoa/cocoa_event_utils.h" #include "ui/gfx/mac/coordinate_conversion.h" #include "ui/native_theme/native_theme.h" @interface StatusItemView : NSView { electron::TrayIconCocoa* trayIcon_; // weak ElectronMenuController* menuController_; // weak BOOL ignoreDoubleClickEvents_; base::scoped_nsobject<NSStatusItem> statusItem_; base::scoped_nsobject<NSTrackingArea> trackingArea_; } @end // @interface StatusItemView @implementation StatusItemView - (void)dealloc { trayIcon_ = nil; menuController_ = nil; [super dealloc]; } - (id)initWithIcon:(electron::TrayIconCocoa*)icon { trayIcon_ = icon; menuController_ = nil; ignoreDoubleClickEvents_ = NO; if ((self = [super initWithFrame:CGRectZero])) { [self registerForDraggedTypes:@[ NSFilenamesPboardType, NSStringPboardType, ]]; // Create the status item. NSStatusItem* item = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; statusItem_.reset([item retain]); [[statusItem_ button] addSubview:self]; // inject custom view [self updateDimensions]; } return self; } - (void)updateDimensions { [self setFrame:[statusItem_ button].frame]; } - (void)updateTrackingAreas { // Use NSTrackingArea for listening to mouseEnter, mouseExit, and mouseMove // events. [self removeTrackingArea:trackingArea_]; trackingArea_.reset([[NSTrackingArea alloc] initWithRect:[self bounds] options:NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways owner:self userInfo:nil]); [self addTrackingArea:trackingArea_]; } - (void)removeItem { // Turn off tracking events to prevent crash. if (trackingArea_) { [self removeTrackingArea:trackingArea_]; trackingArea_.reset(); } [[NSStatusBar systemStatusBar] removeStatusItem:statusItem_]; [self removeFromSuperview]; statusItem_.reset(); } - (void)setImage:(NSImage*)image { [[statusItem_ button] setImage:image]; [self updateDimensions]; } - (void)setAlternateImage:(NSImage*)image { [[statusItem_ button] setAlternateImage:image]; } - (void)setIgnoreDoubleClickEvents:(BOOL)ignore { ignoreDoubleClickEvents_ = ignore; } - (BOOL)getIgnoreDoubleClickEvents { return ignoreDoubleClickEvents_; } - (void)setTitle:(NSString*)title font_type:(NSString*)font_type { NSMutableAttributedString* attributed_title = [[NSMutableAttributedString alloc] initWithString:title]; if ([title containsANSICodes]) { attributed_title = [title attributedStringParsingANSICodes]; } // Change font type, if specified CGFloat existing_size = [[[statusItem_ button] font] pointSize]; if ([font_type isEqualToString:@"monospaced"]) { if (@available(macOS 10.15, *)) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } } else if ([font_type isEqualToString:@"monospacedDigit"]) { NSDictionary* attributes = @{ NSFontAttributeName : [NSFont monospacedDigitSystemFontOfSize:existing_size weight:NSFontWeightRegular] }; [attributed_title addAttributes:attributes range:NSMakeRange(0, [attributed_title length])]; } // Set title [[statusItem_ button] setAttributedTitle:attributed_title]; // Fix icon margins. if (title.length > 0) { [[statusItem_ button] setImagePosition:NSImageLeft]; } else { [[statusItem_ button] setImagePosition:NSImageOnly]; } [self updateDimensions]; } - (NSString*)title { return [statusItem_ button].title; } - (void)setMenuController:(ElectronMenuController*)menu { menuController_ = menu; [statusItem_ setMenu:[menuController_ menu]]; } - (void)handleClickNotifications:(NSEvent*)event { // If we are ignoring double click events, we should ignore the `clickCount` // value and immediately emit a click event. BOOL shouldBeHandledAsASingleClick = (event.clickCount == 1) || ignoreDoubleClickEvents_; if (shouldBeHandledAsASingleClick) trayIcon_->NotifyClicked( gfx::ScreenRectFromNSRect(event.window.frame), gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Double click event. BOOL shouldBeHandledAsADoubleClick = (event.clickCount == 2) && !ignoreDoubleClickEvents_; if (shouldBeHandledAsADoubleClick) trayIcon_->NotifyDoubleClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseDown:(NSEvent*)event { trayIcon_->NotifyMouseDown( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); // Pass click to superclass to show menu. Custom mouseUp handler won't be // invoked. if (menuController_) { [self handleClickNotifications:event]; [super mouseDown:event]; } else { [[statusItem_ button] highlight:YES]; } } - (void)mouseUp:(NSEvent*)event { [[statusItem_ button] highlight:NO]; trayIcon_->NotifyMouseUp( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); [self handleClickNotifications:event]; } - (void)popUpContextMenu:(electron::ElectronMenuModel*)menu_model { // Make sure events can be pumped while the menu is up. base::CurrentThread::ScopedNestableTaskAllower allow; // Show a custom menu. if (menu_model) { base::scoped_nsobject<ElectronMenuController> menuController( [[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); // Hacky way to mimic design of ordinary tray menu. [statusItem_ setMenu:[menuController menu]]; // -performClick: is a blocking call, which will run the task loop inside // itself. This can potentially include running JS, which can result in // this object being released. We take a temporary reference here to make // sure we stay alive long enough to successfully return from this // function. // TODO(nornagon/codebytere): Avoid nesting task loops here. [self retain]; [[statusItem_ button] performClick:self]; [statusItem_ setMenu:[menuController_ menu]]; [self release]; return; } if (menuController_ && ![menuController_ isMenuOpen]) { // Ensure the UI can update while the menu is fading out. base::ScopedPumpMessagesInPrivateModes pump_private; [[statusItem_ button] performClick:self]; } } - (void)closeContextMenu { if (menuController_) { [menuController_ cancel]; } } - (void)rightMouseUp:(NSEvent*)event { trayIcon_->NotifyRightClicked( gfx::ScreenRectFromNSRect(event.window.frame), ui::EventFlagsFromModifiers([event modifierFlags])); } - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEntered(); return NSDragOperationCopy; } - (void)mouseExited:(NSEvent*)event { trayIcon_->NotifyMouseExited( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseEntered:(NSEvent*)event { trayIcon_->NotifyMouseEntered( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)mouseMoved:(NSEvent*)event { trayIcon_->NotifyMouseMoved( gfx::ScreenPointFromNSPoint([event locationInWindow]), ui::EventFlagsFromModifiers([event modifierFlags])); } - (void)draggingExited:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragExited(); } - (void)draggingEnded:(id<NSDraggingInfo>)sender { trayIcon_->NotifyDragEnded(); if (NSPointInRect([sender draggingLocation], self.frame)) { trayIcon_->NotifyDrop(); } } - (BOOL)handleDrop:(id<NSDraggingInfo>)sender { NSPasteboard* pboard = [sender draggingPasteboard]; if ([[pboard types] containsObject:NSFilenamesPboardType]) { std::vector<std::string> dropFiles; NSArray* files = [pboard propertyListForType:NSFilenamesPboardType]; for (NSString* file in files) dropFiles.push_back(base::SysNSStringToUTF8(file)); trayIcon_->NotifyDropFiles(dropFiles); return YES; } else if ([[pboard types] containsObject:NSStringPboardType]) { NSString* dropText = [pboard stringForType:NSStringPboardType]; trayIcon_->NotifyDropText(base::SysNSStringToUTF8(dropText)); return YES; } return NO; } - (BOOL)prepareForDragOperation:(id<NSDraggingInfo>)sender { return YES; } - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender { [self handleDrop:sender]; return YES; } @end namespace electron { TrayIconCocoa::TrayIconCocoa() { status_item_view_.reset([[StatusItemView alloc] initWithIcon:this]); } TrayIconCocoa::~TrayIconCocoa() { [status_item_view_ removeItem]; } void TrayIconCocoa::SetImage(const gfx::Image& image) { [status_item_view_ setImage:image.AsNSImage()]; } void TrayIconCocoa::SetPressedImage(const gfx::Image& image) { [status_item_view_ setAlternateImage:image.AsNSImage()]; } void TrayIconCocoa::SetToolTip(const std::string& tool_tip) { [status_item_view_ setToolTip:base::SysUTF8ToNSString(tool_tip)]; } void TrayIconCocoa::SetTitle(const std::string& title, const TitleOptions& options) { [status_item_view_ setTitle:base::SysUTF8ToNSString(title) font_type:base::SysUTF8ToNSString(options.font_type)]; } std::string TrayIconCocoa::GetTitle() { return base::SysNSStringToUTF8([status_item_view_ title]); } void TrayIconCocoa::SetIgnoreDoubleClickEvents(bool ignore) { [status_item_view_ setIgnoreDoubleClickEvents:ignore]; } bool TrayIconCocoa::GetIgnoreDoubleClickEvents() { return [status_item_view_ getIgnoreDoubleClickEvents]; } void TrayIconCocoa::PopUpOnUI(ElectronMenuModel* menu_model) { [status_item_view_ popUpContextMenu:menu_model]; } void TrayIconCocoa::PopUpContextMenu(const gfx::Point& pos, ElectronMenuModel* menu_model) { base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TrayIconCocoa::PopUpOnUI, weak_factory_.GetWeakPtr(), base::Unretained(menu_model))); } void TrayIconCocoa::CloseContextMenu() { [status_item_view_ closeContextMenu]; } void TrayIconCocoa::SetContextMenu(ElectronMenuModel* menu_model) { if (menu_model) { // Create native menu. menu_.reset([[ElectronMenuController alloc] initWithModel:menu_model useDefaultAccelerator:NO]); } else { menu_.reset(); } [status_item_view_ setMenuController:menu_.get()]; } gfx::Rect TrayIconCocoa::GetBounds() { return gfx::ScreenRectFromNSRect([status_item_view_ window].frame); } // static TrayIcon* TrayIcon::Create(absl::optional<UUID> guid) { return new TrayIconCocoa; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,995
[Bug]: unable to resize height when maxWidth set
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.1 ### What operating system are you using? macOS ### Operating System Version 12.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 16.0.9 ### Expected Behavior When setting `maxWidth` but not a `maxHeight`, I expect the window to resizable in the y direction. ### Actual Behavior Unable to resize window in y direction. Also, removing `minWidth` to allow window to shrink, causes stuttering and mac's beach-ball cursor to show. ### Testcase Gist URL https://gist.github.com/eab3c4ec605b8b942cece3d05e7f749c ### Additional Information _No response_
https://github.com/electron/electron/issues/32995
https://github.com/electron/electron/pull/33025
306147ddf5e529e0455caa51101a7e6870f23196
ebd80a06022c6208c350ea9c70047caa422012ee
2022-02-20T07:47:52Z
c++
2022-03-01T22:20:07Z
shell/browser/native_window.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) || defined(USE_X11) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent() || !ui::win::IsAeroGlassEnabled()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay); int height; if (titlebar_overlay.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); int max_width = size_constraints.GetMaximumSize().width(); int max_height = size_constraints.GetMaximumSize().height(); options.Get(options::kMaxWidth, &max_width); options.Get(options::kMaxHeight, &max_height); size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseHexColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { extensions::SizeConstraints content_constraints(GetContentSizeConstraints()); if (window_constraints.HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMaximumSize())); content_constraints.set_maximum_size(max_bounds.size()); } if (window_constraints.HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMinimumSize())); content_constraints.set_minimum_size(min_bounds.size()); } SetContentSizeConstraints(content_constraints); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { extensions::SizeConstraints content_constraints = GetContentSizeConstraints(); extensions::SizeConstraints window_constraints; if (content_constraints.HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMaximumSize())); window_constraints.set_maximum_size(max_bounds.size()); } if (content_constraints.HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMinimumSize())); window_constraints.set_minimum_size(min_bounds.size()); } return window_constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { size_constraints_ = size_constraints; } extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { return size_constraints_; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWith(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowScrollTouchBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowScrollTouchBegin(); } void NativeWindow::NotifyWindowScrollTouchEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowScrollTouchEnd(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction( const std::string& item_id, const base::DictionaryValue& details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,995
[Bug]: unable to resize height when maxWidth set
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.0.1 ### What operating system are you using? macOS ### Operating System Version 12.1 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version 16.0.9 ### Expected Behavior When setting `maxWidth` but not a `maxHeight`, I expect the window to resizable in the y direction. ### Actual Behavior Unable to resize window in y direction. Also, removing `minWidth` to allow window to shrink, causes stuttering and mac's beach-ball cursor to show. ### Testcase Gist URL https://gist.github.com/eab3c4ec605b8b942cece3d05e7f749c ### Additional Information _No response_
https://github.com/electron/electron/issues/32995
https://github.com/electron/electron/pull/33025
306147ddf5e529e0455caa51101a7e6870f23196
ebd80a06022c6208c350ea9c70047caa422012ee
2022-02-20T07:47:52Z
c++
2022-03-01T22:20:07Z
shell/browser/native_window.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window.h" #include <algorithm> #include <string> #include <vector> #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/web_contents_user_data.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_features.h" #include "shell/browser/window_list.h" #include "shell/common/color_util.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/persistent_dictionary.h" #include "shell/common/options_switches.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(IS_WIN) #include "ui/base/win/shell.h" #include "ui/display/win/screen_win.h" #endif #if defined(USE_OZONE) || defined(USE_X11) #include "ui/base/ui_base_features.h" #include "ui/ozone/public/ozone_platform.h" #endif namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; if (!ConvertFromV8(isolate, val, &title_bar_style)) return false; if (title_bar_style == "hidden") { *out = TitleBarStyle::kHidden; #if BUILDFLAG(IS_MAC) } else if (title_bar_style == "hiddenInset") { *out = TitleBarStyle::kHiddenInset; } else if (title_bar_style == "customButtonsOnHover") { *out = TitleBarStyle::kCustomButtonsOnHover; #endif } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { #if BUILDFLAG(IS_WIN) gfx::Size GetExpandedWindowSize(const NativeWindow* window, gfx::Size size) { if (!window->transparent() || !ui::win::IsAeroGlassEnabled()) return size; gfx::Size min_size = display::win::ScreenWin::ScreenToDIPSize( window->GetAcceleratedWidget(), gfx::Size(64, 64)); // Some AMD drivers can't display windows that are less than 64x64 pixels, // so expand them to be at least that size. http://crbug.com/286609 gfx::Size expanded(std::max(size.width(), min_size.width()), std::max(size.height(), min_size.height())); return expanded; } #endif } // namespace NativeWindow::NativeWindow(const gin_helper::Dictionary& options, NativeWindow* parent) : widget_(std::make_unique<views::Widget>()), parent_(parent) { ++next_id_; options.Get(options::kFrame, &has_frame_); options.Get(options::kTransparent, &transparent_); options.Get(options::kEnableLargerThanScreen, &enable_larger_than_screen_); options.Get(options::kTitleBarStyle, &title_bar_style_); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay)) { if (titlebar_overlay->IsBoolean()) { options.Get(options::ktitleBarOverlay, &titlebar_overlay_); } else if (titlebar_overlay->IsObject()) { titlebar_overlay_ = true; gin_helper::Dictionary titlebar_overlay = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay); int height; if (titlebar_overlay.Get(options::kOverlayHeight, &height)) titlebar_overlay_height_ = height; #if !(BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)) DCHECK(false); #endif } } if (parent) options.Get("modal", &is_modal_); #if defined(USE_OZONE) // Ozone X11 likes to prefer custom frames, but we don't need them unless // on Wayland. if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations) && !ui::OzonePlatform::GetInstance() ->GetPlatformRuntimeProperties() .supports_server_side_window_decorations) { has_client_frame_ = true; } #endif WindowList::AddWindow(this); } NativeWindow::~NativeWindow() { // It's possible that the windows gets destroyed before it's closed, in that // case we need to ensure the Widget delegate gets destroyed and // OnWindowClosed message is still notified. if (widget_->widget_delegate()) widget_->OnNativeWidgetDestroyed(); NotifyWindowClosed(); } void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) { // Setup window from options. int x = -1, y = -1; bool center; if (options.Get(options::kX, &x) && options.Get(options::kY, &y)) { SetPosition(gfx::Point(x, y)); #if BUILDFLAG(IS_WIN) // FIXME(felixrieseberg): Dirty, dirty workaround for // https://github.com/electron/electron/issues/10862 // Somehow, we need to call `SetBounds` twice to get // usable results. The root cause is still unknown. SetPosition(gfx::Point(x, y)); #endif } else if (options.Get(options::kCenter, &center) && center) { Center(); } bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); // On Linux and Window we may already have maximum size defined. extensions::SizeConstraints size_constraints( use_content_size ? GetContentSizeConstraints() : GetSizeConstraints()); int min_width = size_constraints.GetMinimumSize().width(); int min_height = size_constraints.GetMinimumSize().height(); options.Get(options::kMinWidth, &min_width); options.Get(options::kMinHeight, &min_height); size_constraints.set_minimum_size(gfx::Size(min_width, min_height)); int max_width = size_constraints.GetMaximumSize().width(); int max_height = size_constraints.GetMaximumSize().height(); options.Get(options::kMaxWidth, &max_width); options.Get(options::kMaxHeight, &max_height); size_constraints.set_maximum_size(gfx::Size(max_width, max_height)); if (use_content_size) { SetContentSizeConstraints(size_constraints); } else { SetSizeConstraints(size_constraints); } #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) bool resizable; if (options.Get(options::kResizable, &resizable)) { SetResizable(resizable); } bool closable; if (options.Get(options::kClosable, &closable)) { SetClosable(closable); } #endif bool movable; if (options.Get(options::kMovable, &movable)) { SetMovable(movable); } bool has_shadow; if (options.Get(options::kHasShadow, &has_shadow)) { SetHasShadow(has_shadow); } double opacity; if (options.Get(options::kOpacity, &opacity)) { SetOpacity(opacity); } bool top; if (options.Get(options::kAlwaysOnTop, &top) && top) { SetAlwaysOnTop(ui::ZOrderLevel::kFloatingWindow); } bool fullscreenable = true; bool fullscreen = false; if (options.Get(options::kFullscreen, &fullscreen) && !fullscreen) { // Disable fullscreen button if 'fullscreen' is specified to false. #if BUILDFLAG(IS_MAC) fullscreenable = false; #endif } // Overridden by 'fullscreenable'. options.Get(options::kFullScreenable, &fullscreenable); SetFullScreenable(fullscreenable); if (fullscreen) { SetFullScreen(true); } bool skip; if (options.Get(options::kSkipTaskbar, &skip)) { SetSkipTaskbar(skip); } bool kiosk; if (options.Get(options::kKiosk, &kiosk) && kiosk) { SetKiosk(kiosk); } #if BUILDFLAG(IS_MAC) std::string type; if (options.Get(options::kVibrancyType, &type)) { SetVibrancy(type); } #endif std::string color; if (options.Get(options::kBackgroundColor, &color)) { SetBackgroundColor(ParseHexColor(color)); } else if (!transparent()) { // For normal window, use white as default background. SetBackgroundColor(SK_ColorWHITE); } std::string title(Browser::Get()->GetName()); options.Get(options::kTitle, &title); SetTitle(title); // Then show it. bool show = true; options.Get(options::kShow, &show); if (show) Show(); } bool NativeWindow::IsClosed() const { return is_closed_; } void NativeWindow::SetSize(const gfx::Size& size, bool animate) { SetBounds(gfx::Rect(GetPosition(), size), animate); } gfx::Size NativeWindow::GetSize() { return GetBounds().size(); } void NativeWindow::SetPosition(const gfx::Point& position, bool animate) { SetBounds(gfx::Rect(position, GetSize()), animate); } gfx::Point NativeWindow::GetPosition() { return GetBounds().origin(); } void NativeWindow::SetContentSize(const gfx::Size& size, bool animate) { SetSize(ContentBoundsToWindowBounds(gfx::Rect(size)).size(), animate); } gfx::Size NativeWindow::GetContentSize() { return GetContentBounds().size(); } void NativeWindow::SetContentBounds(const gfx::Rect& bounds, bool animate) { SetBounds(ContentBoundsToWindowBounds(bounds), animate); } gfx::Rect NativeWindow::GetContentBounds() { return WindowBoundsToContentBounds(GetBounds()); } bool NativeWindow::IsNormal() { return !IsMinimized() && !IsMaximized() && !IsFullscreen(); } void NativeWindow::SetSizeConstraints( const extensions::SizeConstraints& window_constraints) { extensions::SizeConstraints content_constraints(GetContentSizeConstraints()); if (window_constraints.HasMaximumSize()) { gfx::Rect max_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMaximumSize())); content_constraints.set_maximum_size(max_bounds.size()); } if (window_constraints.HasMinimumSize()) { gfx::Rect min_bounds = WindowBoundsToContentBounds( gfx::Rect(window_constraints.GetMinimumSize())); content_constraints.set_minimum_size(min_bounds.size()); } SetContentSizeConstraints(content_constraints); } extensions::SizeConstraints NativeWindow::GetSizeConstraints() const { extensions::SizeConstraints content_constraints = GetContentSizeConstraints(); extensions::SizeConstraints window_constraints; if (content_constraints.HasMaximumSize()) { gfx::Rect max_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMaximumSize())); window_constraints.set_maximum_size(max_bounds.size()); } if (content_constraints.HasMinimumSize()) { gfx::Rect min_bounds = ContentBoundsToWindowBounds( gfx::Rect(content_constraints.GetMinimumSize())); window_constraints.set_minimum_size(min_bounds.size()); } return window_constraints; } void NativeWindow::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { size_constraints_ = size_constraints; } extensions::SizeConstraints NativeWindow::GetContentSizeConstraints() const { return size_constraints_; } void NativeWindow::SetMinimumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_minimum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMinimumSize() const { return GetSizeConstraints().GetMinimumSize(); } void NativeWindow::SetMaximumSize(const gfx::Size& size) { extensions::SizeConstraints size_constraints; size_constraints.set_maximum_size(size); SetSizeConstraints(size_constraints); } gfx::Size NativeWindow::GetMaximumSize() const { return GetSizeConstraints().GetMaximumSize(); } gfx::Size NativeWindow::GetContentMinimumSize() const { return GetContentSizeConstraints().GetMinimumSize(); } gfx::Size NativeWindow::GetContentMaximumSize() const { gfx::Size maximum_size = GetContentSizeConstraints().GetMaximumSize(); #if BUILDFLAG(IS_WIN) return GetContentSizeConstraints().HasMaximumSize() ? GetExpandedWindowSize(this, maximum_size) : maximum_size; #else return maximum_size; #endif } void NativeWindow::SetSheetOffset(const double offsetX, const double offsetY) { sheet_offset_x_ = offsetX; sheet_offset_y_ = offsetY; } double NativeWindow::GetSheetOffsetX() { return sheet_offset_x_; } double NativeWindow::GetSheetOffsetY() { return sheet_offset_y_; } bool NativeWindow::IsTabletMode() const { return false; } void NativeWindow::SetRepresentedFilename(const std::string& filename) {} std::string NativeWindow::GetRepresentedFilename() { return ""; } void NativeWindow::SetDocumentEdited(bool edited) {} bool NativeWindow::IsDocumentEdited() { return false; } void NativeWindow::SetFocusable(bool focusable) {} bool NativeWindow::IsFocusable() { return false; } void NativeWindow::SetMenu(ElectronMenuModel* menu) {} void NativeWindow::SetParentWindow(NativeWindow* parent) { parent_ = parent; } void NativeWindow::SetAutoHideCursor(bool auto_hide) {} void NativeWindow::SelectPreviousTab() {} void NativeWindow::SelectNextTab() {} void NativeWindow::MergeAllWindows() {} void NativeWindow::MoveTabToNewWindow() {} void NativeWindow::ToggleTabBar() {} bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } void NativeWindow::SetVibrancy(const std::string& type) {} void NativeWindow::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) {} void NativeWindow::RefreshTouchBarItem(const std::string& item_id) {} void NativeWindow::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) {} void NativeWindow::SetAutoHideMenuBar(bool auto_hide) {} bool NativeWindow::IsMenuBarAutoHide() { return false; } void NativeWindow::SetMenuBarVisibility(bool visible) {} bool NativeWindow::IsMenuBarVisible() { return true; } double NativeWindow::GetAspectRatio() { return aspect_ratio_; } gfx::Size NativeWindow::GetAspectRatioExtraSize() { return aspect_ratio_extraSize_; } void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; aspect_ratio_extraSize_ = extra_size; } void NativeWindow::PreviewFile(const std::string& path, const std::string& display_name) {} void NativeWindow::CloseFilePreview() {} gfx::Rect NativeWindow::GetWindowControlsOverlayRect() { return overlay_rect_; } void NativeWindow::SetWindowControlsOverlayRect(const gfx::Rect& overlay_rect) { overlay_rect_ = overlay_rect; } void NativeWindow::NotifyWindowRequestPreferredWith(int* width) { for (NativeWindowObserver& observer : observers_) observer.RequestPreferredWidth(width); } void NativeWindow::NotifyWindowCloseButtonClicked() { // First ask the observers whether we want to close. bool prevent_default = false; for (NativeWindowObserver& observer : observers_) observer.WillCloseWindow(&prevent_default); if (prevent_default) { WindowList::WindowCloseCancelled(this); return; } // Then ask the observers how should we close the window. for (NativeWindowObserver& observer : observers_) observer.OnCloseButtonClicked(&prevent_default); if (prevent_default) return; CloseImmediately(); } void NativeWindow::NotifyWindowClosed() { if (is_closed_) return; is_closed_ = true; for (NativeWindowObserver& observer : observers_) observer.OnWindowClosed(); WindowList::RemoveWindow(this); } void NativeWindow::NotifyWindowEndSession() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEndSession(); } void NativeWindow::NotifyWindowBlur() { for (NativeWindowObserver& observer : observers_) observer.OnWindowBlur(); } void NativeWindow::NotifyWindowFocus() { for (NativeWindowObserver& observer : observers_) observer.OnWindowFocus(); } void NativeWindow::NotifyWindowIsKeyChanged(bool is_key) { for (NativeWindowObserver& observer : observers_) observer.OnWindowIsKeyChanged(is_key); } void NativeWindow::NotifyWindowShow() { for (NativeWindowObserver& observer : observers_) observer.OnWindowShow(); } void NativeWindow::NotifyWindowHide() { for (NativeWindowObserver& observer : observers_) observer.OnWindowHide(); } void NativeWindow::NotifyWindowMaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMaximize(); } void NativeWindow::NotifyWindowUnmaximize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowUnmaximize(); } void NativeWindow::NotifyWindowMinimize() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMinimize(); } void NativeWindow::NotifyWindowRestore() { for (NativeWindowObserver& observer : observers_) observer.OnWindowRestore(); } void NativeWindow::NotifyWindowWillResize(const gfx::Rect& new_bounds, const gfx::ResizeEdge& edge, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillResize(new_bounds, edge, prevent_default); } void NativeWindow::NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnWindowWillMove(new_bounds, prevent_default); } void NativeWindow::NotifyWindowResize() { NotifyLayoutWindowControlsOverlay(); for (NativeWindowObserver& observer : observers_) observer.OnWindowResize(); } void NativeWindow::NotifyWindowResized() { for (NativeWindowObserver& observer : observers_) observer.OnWindowResized(); } void NativeWindow::NotifyWindowMove() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMove(); } void NativeWindow::NotifyWindowMoved() { for (NativeWindowObserver& observer : observers_) observer.OnWindowMoved(); } void NativeWindow::NotifyWindowEnterFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterFullScreen(); } void NativeWindow::NotifyWindowScrollTouchBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowScrollTouchBegin(); } void NativeWindow::NotifyWindowScrollTouchEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowScrollTouchEnd(); } void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); } void NativeWindow::NotifyWindowRotateGesture(float rotation) { for (NativeWindowObserver& observer : observers_) observer.OnWindowRotateGesture(rotation); } void NativeWindow::NotifyWindowSheetBegin() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetBegin(); } void NativeWindow::NotifyWindowSheetEnd() { for (NativeWindowObserver& observer : observers_) observer.OnWindowSheetEnd(); } void NativeWindow::NotifyWindowLeaveFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveFullScreen(); } void NativeWindow::NotifyWindowEnterHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowEnterHtmlFullScreen(); } void NativeWindow::NotifyWindowLeaveHtmlFullScreen() { for (NativeWindowObserver& observer : observers_) observer.OnWindowLeaveHtmlFullScreen(); } void NativeWindow::NotifyWindowAlwaysOnTopChanged() { for (NativeWindowObserver& observer : observers_) observer.OnWindowAlwaysOnTopChanged(); } void NativeWindow::NotifyWindowExecuteAppCommand(const std::string& command) { for (NativeWindowObserver& observer : observers_) observer.OnExecuteAppCommand(command); } void NativeWindow::NotifyTouchBarItemInteraction( const std::string& item_id, const base::DictionaryValue& details) { for (NativeWindowObserver& observer : observers_) observer.OnTouchBarItemResult(item_id, details); } void NativeWindow::NotifyNewWindowForTab() { for (NativeWindowObserver& observer : observers_) observer.OnNewWindowForTab(); } void NativeWindow::NotifyWindowSystemContextMenu(int x, int y, bool* prevent_default) { for (NativeWindowObserver& observer : observers_) observer.OnSystemContextMenu(x, y, prevent_default); } void NativeWindow::NotifyLayoutWindowControlsOverlay() { gfx::Rect bounding_rect = GetWindowControlsOverlayRect(); if (!bounding_rect.IsEmpty()) { for (NativeWindowObserver& observer : observers_) observer.UpdateWindowControlsOverlay(bounding_rect); } } #if BUILDFLAG(IS_WIN) void NativeWindow::NotifyWindowMessage(UINT message, WPARAM w_param, LPARAM l_param) { for (NativeWindowObserver& observer : observers_) observer.OnWindowMessage(message, w_param, l_param); } #endif views::Widget* NativeWindow::GetWidget() { return widget(); } const views::Widget* NativeWindow::GetWidget() const { return widget(); } std::u16string NativeWindow::GetAccessibleWindowTitle() const { if (accessible_title_.empty()) { return views::WidgetDelegate::GetAccessibleWindowTitle(); } return accessible_title_; } void NativeWindow::SetAccessibleTitle(const std::string& title) { accessible_title_ = base::UTF8ToUTF16(title); } std::string NativeWindow::GetAccessibleTitle() { return base::UTF16ToUTF8(accessible_title_); } // static int32_t NativeWindow::next_id_ = 0; // static void NativeWindowRelay::CreateForWebContents( content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) { DCHECK(web_contents); if (!web_contents->GetUserData(UserDataKey())) { web_contents->SetUserData( UserDataKey(), base::WrapUnique(new NativeWindowRelay(web_contents, window))); } } NativeWindowRelay::NativeWindowRelay(content::WebContents* web_contents, base::WeakPtr<NativeWindow> window) : content::WebContentsUserData<NativeWindowRelay>(*web_contents), native_window_(window) {} NativeWindowRelay::~NativeWindowRelay() = default; WEB_CONTENTS_USER_DATA_KEY_IMPL(NativeWindowRelay); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,023
[Bug]: Devtools Sources "Open in Containing Folder" crashes
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version master ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.2 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior Clicking "Open in Containing Folder" opens the file's containing directory and selects the specified file. <img width="809" alt="Screen Shot 2022-02-21 at 10 42 21 AM" src="https://user-images.githubusercontent.com/2036040/154929325-8c0ddb3a-771f-4ba3-8454-8c291db29b54.png"> ### Actual Behavior The file opens as default-specified and Electron crashes. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/33023
https://github.com/electron/electron/pull/33024
b96f15bfc262edd88d5df8c3684484c894d08ce5
076bc58b2a15ff18ab07d67e23864aa7b4a4a9eb
2022-02-21T09:45:13Z
c++
2022-03-08T19:40:25Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kDevToolsSyncPreferences[] = "electron.devtools.sync_preferences"; const char kDevToolsSyncedPreferencesSyncEnabled[] = "electron.devtools.synced_preferences_sync_enabled"; const char kDevToolsSyncedPreferencesSyncDisabled[] = "electron.devtools.synced_preferences_sync_disabled"; const char kSyncDevToolsPreferencesFrontendName[] = "electron.sync_preferences"; const bool kSyncDevToolsPreferencesDefault = false; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; // Stores all instances of InspectableWebContents. InspectableWebContents::List g_web_contents_instances_; base::Value RectToDictionary(const gfx::Rect& bounds) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey("x", base::Value(bounds.x())); dict.SetKey("y", base::Value(bounds.y())); dict.SetKey("width", base::Value(bounds.width())); dict.SetKey("height", base::Value(bounds.height())); return dict; } gfx::Rect DictionaryToRect(const base::Value* dict) { const base::Value* found = dict->FindKey("x"); int x = found ? found->GetInt() : 0; found = dict->FindKey("y"); int y = found ? found->GetInt() : 0; found = dict->FindKey("width"); int width = found ? found->GetInt() : 800; found = dict->FindKey("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = base::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI.streamWrite", &id, &chunkValue, &encodedValue); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::DictionaryValue response; response.SetInteger("statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); auto headers = std::make_unique<base::DictionaryValue>(); size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); response.Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; InspectableWebContents* const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static const InspectableWebContents::List& InspectableWebContents::GetAll() { return g_web_contents_instances_; } // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect(0, 0, 800, 600))); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncEnabled); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncDisabled); registry->RegisterBooleanPref(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = pref_service_->Get(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } g_web_contents_instances_.push_back(this); } InspectableWebContents::~InspectableWebContents() { g_web_contents_instances_.remove(this); // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!GetDevToolsWebContents()) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript), base::NullCallback()); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds)); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); } else { if (dock_state_.empty()) { const base::Value* prefs = pref_service_->GetDictionary(kDevToolsPreferences); const std::string* current_dock_state = prefs->FindStringKey("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } std::u16string javascript = base::UTF8ToUTF16( "UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::ListValue results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); auto extension_info = std::make_unique<base::DictionaryValue>(); extension_info->SetString("startPage", devtools_page_url.spec()); extension_info->SetString("name", extension->name()); extension_info->SetBoolean( "exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI.addExtensions", &results, NULL, NULL); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) {} void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); // Pass empty callback here; we can ignore errors platform_util::OpenPath(path, platform_util::OpenCallback()); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::RegisterPreference( const std::string& name, const RegisterOptions& options) { // kSyncDevToolsPreferenceFrontendName is not stored in any of the relevant // dictionaries. Skip registration. if (name == kSyncDevToolsPreferencesFrontendName) return; if (options.sync_mode == RegisterOptions::SyncMode::kSync) { synced_setting_names_.insert(name); } // Setting might have had a different sync status in the past. Move the // setting to the correct dictionary. const char* dictionary_to_remove_from = options.sync_mode == RegisterOptions::SyncMode::kSync ? kDevToolsPreferences : GetDictionaryNameForSyncedPrefs(); const std::string* settings_value = pref_service_->GetDictionary(dictionary_to_remove_from) ->FindStringKey(name); if (!settings_value) { return; } const char* dictionary_to_insert_into = GetDictionaryNameForSettingsName(name); // Settings already moved to the synced dictionary on a different device have // precedence. const std::string* already_synced_value = pref_service_->GetDictionary(dictionary_to_insert_into) ->FindStringKey(name); if (dictionary_to_insert_into == kDevToolsPreferences || !already_synced_value) { DictionaryPrefUpdate insert_update(pref_service_, dictionary_to_insert_into); insert_update.Get()->SetKey(name, base::Value(*settings_value)); } DictionaryPrefUpdate remove_update(pref_service_, dictionary_to_remove_from); remove_update.Get()->RemoveKey(name); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { base::Value settings(base::Value::Type::DICTIONARY); settings.SetBoolKey(kSyncDevToolsPreferencesFrontendName, pref_service_->GetBoolean(kDevToolsSyncPreferences)); settings.MergeDictionary(pref_service_->GetDictionary(kDevToolsPreferences)); settings.MergeDictionary( pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs())); std::move(callback).Run(&settings); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { // Handle kSyncDevToolsPreferencesFrontendName if (name == kSyncDevToolsPreferencesFrontendName) { base::Value pref = base::Value(pref_service_->GetBoolean(kDevToolsSyncPreferences)); std::move(callback).Run(&pref); return; } // Check dev tools prefs if (auto* pref = pref_service_->GetDictionary(kDevToolsPreferences)->FindKey(name)) { std::move(callback).Run(pref); return; } // Check synced prefs if (auto* pref = pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs()) ->FindKey(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, value == "true"); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->SetKey(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->RemoveKey(name); } void InspectableWebContents::ClearPreferences() { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); DictionaryPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update.Get()->DictClear(); DictionaryPrefUpdate sync_enabled_update( pref_service_, kDevToolsSyncedPreferencesSyncEnabled); sync_enabled_update.Get()->DictClear(); DictionaryPrefUpdate sync_disabled_update( pref_service_, kDevToolsSyncedPreferencesSyncDisabled); sync_disabled_update.Get()->DictClear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { // TODO(anyone): do we want devtool syncing in Electron? base::Value result(base::Value::Type::DICTIONARY); result.SetBoolKey("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = nullptr; base::Value* params = nullptr; if (message.is_dict()) { method = message.FindStringKey(kFrontendHostMethod); params = message.FindKey(kFrontendHostParams); } if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } base::Value empty_params(base::Value::Type::LIST); if (!params) { params = &empty_params; } int id = message.FindIntKey(kFrontendHostId).value_or(0); std::vector<base::Value> params_list; if (params) params_list = std::move(*params).TakeListDeprecated(); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.size() < kMaxMessageChunkSize) { std::string param; base::EscapeJSONString(str_message, true, &param); std::u16string javascript = base::UTF8ToUTF16("DevToolsAPI.dispatchMessage(" + param + ");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); return; } base::Value total_size(static_cast<int>(str_message.length())); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::Value message_value(str_message.substr(pos, kMaxMessageChunkSize)); CallClientFunction("DevToolsAPI.dispatchMessageChunk", &message_value, pos ? nullptr : &total_size, nullptr); } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(), base::GenerateGUID().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { base::Value id_value(request_id); CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr); } const char* InspectableWebContents::GetDictionaryNameForSettingsName( const std::string& name) const { return synced_setting_names_.contains(name) ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsPreferences; } const char* InspectableWebContents::GetDictionaryNameForSyncedPrefs() const { const bool isDevToolsSyncEnabled = pref_service_->GetBoolean(kDevToolsSyncPreferences); return isDevToolsSyncEnabled ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsSyncedPreferencesSyncDisabled; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,023
[Bug]: Devtools Sources "Open in Containing Folder" crashes
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version master ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.2 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior Clicking "Open in Containing Folder" opens the file's containing directory and selects the specified file. <img width="809" alt="Screen Shot 2022-02-21 at 10 42 21 AM" src="https://user-images.githubusercontent.com/2036040/154929325-8c0ddb3a-771f-4ba3-8454-8c291db29b54.png"> ### Actual Behavior The file opens as default-specified and Electron crashes. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/33023
https://github.com/electron/electron/pull/33024
b96f15bfc262edd88d5df8c3684484c894d08ce5
076bc58b2a15ff18ab07d67e23864aa7b4a4a9eb
2022-02-21T09:45:13Z
c++
2022-03-08T19:40:25Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kDevToolsSyncPreferences[] = "electron.devtools.sync_preferences"; const char kDevToolsSyncedPreferencesSyncEnabled[] = "electron.devtools.synced_preferences_sync_enabled"; const char kDevToolsSyncedPreferencesSyncDisabled[] = "electron.devtools.synced_preferences_sync_disabled"; const char kSyncDevToolsPreferencesFrontendName[] = "electron.sync_preferences"; const bool kSyncDevToolsPreferencesDefault = false; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; // Stores all instances of InspectableWebContents. InspectableWebContents::List g_web_contents_instances_; base::Value RectToDictionary(const gfx::Rect& bounds) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey("x", base::Value(bounds.x())); dict.SetKey("y", base::Value(bounds.y())); dict.SetKey("width", base::Value(bounds.width())); dict.SetKey("height", base::Value(bounds.height())); return dict; } gfx::Rect DictionaryToRect(const base::Value* dict) { const base::Value* found = dict->FindKey("x"); int x = found ? found->GetInt() : 0; found = dict->FindKey("y"); int y = found ? found->GetInt() : 0; found = dict->FindKey("width"); int width = found ? found->GetInt() : 800; found = dict->FindKey("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = base::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI.streamWrite", &id, &chunkValue, &encodedValue); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::DictionaryValue response; response.SetInteger("statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); auto headers = std::make_unique<base::DictionaryValue>(); size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); response.Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; InspectableWebContents* const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static const InspectableWebContents::List& InspectableWebContents::GetAll() { return g_web_contents_instances_; } // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect(0, 0, 800, 600))); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncEnabled); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncDisabled); registry->RegisterBooleanPref(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = pref_service_->Get(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } g_web_contents_instances_.push_back(this); } InspectableWebContents::~InspectableWebContents() { g_web_contents_instances_.remove(this); // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!GetDevToolsWebContents()) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript), base::NullCallback()); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds)); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); } else { if (dock_state_.empty()) { const base::Value* prefs = pref_service_->GetDictionary(kDevToolsPreferences); const std::string* current_dock_state = prefs->FindStringKey("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } std::u16string javascript = base::UTF8ToUTF16( "UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::ListValue results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); auto extension_info = std::make_unique<base::DictionaryValue>(); extension_info->SetString("startPage", devtools_page_url.spec()); extension_info->SetString("name", extension->name()); extension_info->SetBoolean( "exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI.addExtensions", &results, NULL, NULL); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) {} void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); // Pass empty callback here; we can ignore errors platform_util::OpenPath(path, platform_util::OpenCallback()); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::RegisterPreference( const std::string& name, const RegisterOptions& options) { // kSyncDevToolsPreferenceFrontendName is not stored in any of the relevant // dictionaries. Skip registration. if (name == kSyncDevToolsPreferencesFrontendName) return; if (options.sync_mode == RegisterOptions::SyncMode::kSync) { synced_setting_names_.insert(name); } // Setting might have had a different sync status in the past. Move the // setting to the correct dictionary. const char* dictionary_to_remove_from = options.sync_mode == RegisterOptions::SyncMode::kSync ? kDevToolsPreferences : GetDictionaryNameForSyncedPrefs(); const std::string* settings_value = pref_service_->GetDictionary(dictionary_to_remove_from) ->FindStringKey(name); if (!settings_value) { return; } const char* dictionary_to_insert_into = GetDictionaryNameForSettingsName(name); // Settings already moved to the synced dictionary on a different device have // precedence. const std::string* already_synced_value = pref_service_->GetDictionary(dictionary_to_insert_into) ->FindStringKey(name); if (dictionary_to_insert_into == kDevToolsPreferences || !already_synced_value) { DictionaryPrefUpdate insert_update(pref_service_, dictionary_to_insert_into); insert_update.Get()->SetKey(name, base::Value(*settings_value)); } DictionaryPrefUpdate remove_update(pref_service_, dictionary_to_remove_from); remove_update.Get()->RemoveKey(name); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { base::Value settings(base::Value::Type::DICTIONARY); settings.SetBoolKey(kSyncDevToolsPreferencesFrontendName, pref_service_->GetBoolean(kDevToolsSyncPreferences)); settings.MergeDictionary(pref_service_->GetDictionary(kDevToolsPreferences)); settings.MergeDictionary( pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs())); std::move(callback).Run(&settings); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { // Handle kSyncDevToolsPreferencesFrontendName if (name == kSyncDevToolsPreferencesFrontendName) { base::Value pref = base::Value(pref_service_->GetBoolean(kDevToolsSyncPreferences)); std::move(callback).Run(&pref); return; } // Check dev tools prefs if (auto* pref = pref_service_->GetDictionary(kDevToolsPreferences)->FindKey(name)) { std::move(callback).Run(pref); return; } // Check synced prefs if (auto* pref = pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs()) ->FindKey(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, value == "true"); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->SetKey(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->RemoveKey(name); } void InspectableWebContents::ClearPreferences() { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); DictionaryPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update.Get()->DictClear(); DictionaryPrefUpdate sync_enabled_update( pref_service_, kDevToolsSyncedPreferencesSyncEnabled); sync_enabled_update.Get()->DictClear(); DictionaryPrefUpdate sync_disabled_update( pref_service_, kDevToolsSyncedPreferencesSyncDisabled); sync_disabled_update.Get()->DictClear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { // TODO(anyone): do we want devtool syncing in Electron? base::Value result(base::Value::Type::DICTIONARY); result.SetBoolKey("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = nullptr; base::Value* params = nullptr; if (message.is_dict()) { method = message.FindStringKey(kFrontendHostMethod); params = message.FindKey(kFrontendHostParams); } if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } base::Value empty_params(base::Value::Type::LIST); if (!params) { params = &empty_params; } int id = message.FindIntKey(kFrontendHostId).value_or(0); std::vector<base::Value> params_list; if (params) params_list = std::move(*params).TakeListDeprecated(); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.size() < kMaxMessageChunkSize) { std::string param; base::EscapeJSONString(str_message, true, &param); std::u16string javascript = base::UTF8ToUTF16("DevToolsAPI.dispatchMessage(" + param + ");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); return; } base::Value total_size(static_cast<int>(str_message.length())); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::Value message_value(str_message.substr(pos, kMaxMessageChunkSize)); CallClientFunction("DevToolsAPI.dispatchMessageChunk", &message_value, pos ? nullptr : &total_size, nullptr); } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(), base::GenerateGUID().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { base::Value id_value(request_id); CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr); } const char* InspectableWebContents::GetDictionaryNameForSettingsName( const std::string& name) const { return synced_setting_names_.contains(name) ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsPreferences; } const char* InspectableWebContents::GetDictionaryNameForSyncedPrefs() const { const bool isDevToolsSyncEnabled = pref_service_->GetBoolean(kDevToolsSyncPreferences); return isDevToolsSyncEnabled ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsSyncedPreferencesSyncDisabled; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,102
[Bug]: DevTools shortcut settings do not persist
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? Windows ### Operating System Version 10.0.19043 Build 19043 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting remains last selected value ### Actual Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting reverts to default ### Testcase Gist URL _No response_ ### Additional Information Seems like it could be related to #31864
https://github.com/electron/electron/issues/33102
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2022-02-28T15:05:48Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kDevToolsSyncPreferences[] = "electron.devtools.sync_preferences"; const char kDevToolsSyncedPreferencesSyncEnabled[] = "electron.devtools.synced_preferences_sync_enabled"; const char kDevToolsSyncedPreferencesSyncDisabled[] = "electron.devtools.synced_preferences_sync_disabled"; const char kSyncDevToolsPreferencesFrontendName[] = "electron.sync_preferences"; const bool kSyncDevToolsPreferencesDefault = false; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; // Stores all instances of InspectableWebContents. InspectableWebContents::List g_web_contents_instances_; base::Value RectToDictionary(const gfx::Rect& bounds) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey("x", base::Value(bounds.x())); dict.SetKey("y", base::Value(bounds.y())); dict.SetKey("width", base::Value(bounds.width())); dict.SetKey("height", base::Value(bounds.height())); return dict; } gfx::Rect DictionaryToRect(const base::Value* dict) { const base::Value* found = dict->FindKey("x"); int x = found ? found->GetInt() : 0; found = dict->FindKey("y"); int y = found ? found->GetInt() : 0; found = dict->FindKey("width"); int width = found ? found->GetInt() : 800; found = dict->FindKey("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = base::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } void OnOpenItemComplete(const base::FilePath& path, const std::string& result) { platform_util::ShowItemInFolder(path); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI.streamWrite", &id, &chunkValue, &encodedValue); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::DictionaryValue response; response.SetInteger("statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); auto headers = std::make_unique<base::DictionaryValue>(); size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); response.Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; InspectableWebContents* const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static const InspectableWebContents::List& InspectableWebContents::GetAll() { return g_web_contents_instances_; } // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect(0, 0, 800, 600))); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncEnabled); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncDisabled); registry->RegisterBooleanPref(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = pref_service_->Get(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } g_web_contents_instances_.push_back(this); } InspectableWebContents::~InspectableWebContents() { g_web_contents_instances_.remove(this); // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!GetDevToolsWebContents()) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript), base::NullCallback()); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds)); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); } else { if (dock_state_.empty()) { const base::Value* prefs = pref_service_->GetDictionary(kDevToolsPreferences); const std::string* current_dock_state = prefs->FindStringKey("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } std::u16string javascript = base::UTF8ToUTF16( "UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::ListValue results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); auto extension_info = std::make_unique<base::DictionaryValue>(); extension_info->SetString("startPage", devtools_page_url.spec()); extension_info->SetString("name", extension->name()); extension_info->SetBoolean( "exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI.addExtensions", &results, NULL, NULL); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) {} void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); platform_util::OpenPath(path.DirName(), base::BindOnce(&OnOpenItemComplete, path)); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::RegisterPreference( const std::string& name, const RegisterOptions& options) { // kSyncDevToolsPreferenceFrontendName is not stored in any of the relevant // dictionaries. Skip registration. if (name == kSyncDevToolsPreferencesFrontendName) return; if (options.sync_mode == RegisterOptions::SyncMode::kSync) { synced_setting_names_.insert(name); } // Setting might have had a different sync status in the past. Move the // setting to the correct dictionary. const char* dictionary_to_remove_from = options.sync_mode == RegisterOptions::SyncMode::kSync ? kDevToolsPreferences : GetDictionaryNameForSyncedPrefs(); const std::string* settings_value = pref_service_->GetDictionary(dictionary_to_remove_from) ->FindStringKey(name); if (!settings_value) { return; } const char* dictionary_to_insert_into = GetDictionaryNameForSettingsName(name); // Settings already moved to the synced dictionary on a different device have // precedence. const std::string* already_synced_value = pref_service_->GetDictionary(dictionary_to_insert_into) ->FindStringKey(name); if (dictionary_to_insert_into == kDevToolsPreferences || !already_synced_value) { DictionaryPrefUpdate insert_update(pref_service_, dictionary_to_insert_into); insert_update.Get()->SetKey(name, base::Value(*settings_value)); } DictionaryPrefUpdate remove_update(pref_service_, dictionary_to_remove_from); remove_update.Get()->RemoveKey(name); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { base::Value settings(base::Value::Type::DICTIONARY); settings.SetBoolKey(kSyncDevToolsPreferencesFrontendName, pref_service_->GetBoolean(kDevToolsSyncPreferences)); settings.MergeDictionary(pref_service_->GetDictionary(kDevToolsPreferences)); settings.MergeDictionary( pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs())); std::move(callback).Run(&settings); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { // Handle kSyncDevToolsPreferencesFrontendName if (name == kSyncDevToolsPreferencesFrontendName) { base::Value pref = base::Value(pref_service_->GetBoolean(kDevToolsSyncPreferences)); std::move(callback).Run(&pref); return; } // Check dev tools prefs if (auto* pref = pref_service_->GetDictionary(kDevToolsPreferences)->FindKey(name)) { std::move(callback).Run(pref); return; } // Check synced prefs if (auto* pref = pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs()) ->FindKey(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, value == "true"); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->SetKey(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->RemoveKey(name); } void InspectableWebContents::ClearPreferences() { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); DictionaryPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update.Get()->DictClear(); DictionaryPrefUpdate sync_enabled_update( pref_service_, kDevToolsSyncedPreferencesSyncEnabled); sync_enabled_update.Get()->DictClear(); DictionaryPrefUpdate sync_disabled_update( pref_service_, kDevToolsSyncedPreferencesSyncDisabled); sync_disabled_update.Get()->DictClear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { // TODO(anyone): do we want devtool syncing in Electron? base::Value result(base::Value::Type::DICTIONARY); result.SetBoolKey("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = nullptr; base::Value* params = nullptr; if (message.is_dict()) { method = message.FindStringKey(kFrontendHostMethod); params = message.FindKey(kFrontendHostParams); } if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } base::Value empty_params(base::Value::Type::LIST); if (!params) { params = &empty_params; } int id = message.FindIntKey(kFrontendHostId).value_or(0); std::vector<base::Value> params_list; if (params) params_list = std::move(*params).TakeListDeprecated(); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.size() < kMaxMessageChunkSize) { std::string param; base::EscapeJSONString(str_message, true, &param); std::u16string javascript = base::UTF8ToUTF16("DevToolsAPI.dispatchMessage(" + param + ");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); return; } base::Value total_size(static_cast<int>(str_message.length())); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::Value message_value(str_message.substr(pos, kMaxMessageChunkSize)); CallClientFunction("DevToolsAPI.dispatchMessageChunk", &message_value, pos ? nullptr : &total_size, nullptr); } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(), base::GenerateGUID().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { base::Value id_value(request_id); CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr); } const char* InspectableWebContents::GetDictionaryNameForSettingsName( const std::string& name) const { return synced_setting_names_.contains(name) ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsPreferences; } const char* InspectableWebContents::GetDictionaryNameForSyncedPrefs() const { const bool isDevToolsSyncEnabled = pref_service_->GetBoolean(kDevToolsSyncPreferences); return isDevToolsSyncEnabled ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsSyncedPreferencesSyncDisabled; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,102
[Bug]: DevTools shortcut settings do not persist
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? Windows ### Operating System Version 10.0.19043 Build 19043 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting remains last selected value ### Actual Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting reverts to default ### Testcase Gist URL _No response_ ### Additional Information Seems like it could be related to #31864
https://github.com/electron/electron/issues/33102
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2022-02-28T15:05:48Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/containers/span.h" #include "base/containers/unique_ptr_adapters.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "chrome/browser/devtools/devtools_embedder_message_dispatcher.h" #include "chrome/browser/devtools/devtools_settings.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "ui/gfx/geometry/rect.h" class PrefService; class PrefRegistrySimple; struct RegisterOptions; namespace electron { class InspectableWebContentsDelegate; class InspectableWebContentsView; class InspectableWebContents : public content::DevToolsAgentHostClient, public content::WebContentsObserver, public content::WebContentsDelegate, public DevToolsEmbedderMessageDispatcher::Delegate { public: using List = std::list<InspectableWebContents*>; static const List& GetAll(); static void RegisterPrefs(PrefRegistrySimple* pref_registry); InspectableWebContents(std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest); ~InspectableWebContents() override; // disable copy InspectableWebContents(const InspectableWebContents&) = delete; InspectableWebContents& operator=(const InspectableWebContents&) = delete; InspectableWebContentsView* GetView() const; content::WebContents* GetWebContents() const; content::WebContents* GetDevToolsWebContents() const; void SetDelegate(InspectableWebContentsDelegate* delegate); InspectableWebContentsDelegate* GetDelegate() const; bool IsGuest() const; void ReleaseWebContents(); void SetDevToolsWebContents(content::WebContents* devtools); void SetDockState(const std::string& state); void ShowDevTools(bool activate); void CloseDevTools(); bool IsDevToolsViewShowing(); void AttachTo(scoped_refptr<content::DevToolsAgentHost>); void Detach(); void CallClientFunction(const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3); void InspectElement(int x, int y); // Return the last position and size of devtools window. gfx::Rect GetDevToolsBounds() const; void SaveDevToolsBounds(const gfx::Rect& bounds); // Return the last set zoom level of devtools window. double GetDevToolsZoomLevel() const; void UpdateDevToolsZoomLevel(double level); private: // DevToolsEmbedderMessageDispacher::Delegate void ActivateWindow() override; void CloseWindow() override; void LoadCompleted() override; void SetInspectedPageBounds(const gfx::Rect& rect) override; void InspectElementCompleted() override; void InspectedURLChanged(const std::string& url) override; void LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) override; void SetIsDocked(DispatchCallback callback, bool is_docked) override; void OpenInNewTab(const std::string& url) override; void ShowItemInFolder(const std::string& file_system_path) override; void SaveToFile(const std::string& url, const std::string& content, bool save_as) override; void AppendToFile(const std::string& url, const std::string& content) override; void RequestFileSystems() override; void AddFileSystem(const std::string& type) override; void RemoveFileSystem(const std::string& file_system_path) override; void UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) override; void IndexPath(int index_request_id, const std::string& file_system_path, const std::string& excluded_folders) override; void StopIndexing(int index_request_id) override; void SearchInPath(int search_request_id, const std::string& file_system_path, const std::string& query) override; void SetWhitelistedShortcuts(const std::string& message) override; void SetEyeDropperActive(bool active) override; void ShowCertificateViewer(const std::string& cert_chain) override; void ZoomIn() override; void ZoomOut() override; void ResetZoom() override; void SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) override; void SetDevicesUpdatesEnabled(bool enabled) override; void PerformActionOnRemotePage(const std::string& page_id, const std::string& action) override; void OpenRemotePage(const std::string& browser_id, const std::string& url) override; void OpenNodeFrontend() override; void DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) override; void SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) override; void RegisterPreference(const std::string& name, const RegisterOptions& options) override; void GetPreferences(DispatchCallback callback) override; void GetPreference(DispatchCallback callback, const std::string& name) override; void SetPreference(const std::string& name, const std::string& value) override; void RemovePreference(const std::string& name) override; void ClearPreferences() override; void GetSyncInformation(DispatchCallback callback) override; void ConnectionReady() override; void RegisterExtensionsAPI(const std::string& origin, const std::string& script) override; void Reattach(DispatchCallback callback) override; void RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) override {} void ReadyForTest() override {} void SetOpenNewWindowForPopups(bool value) override {} void RecordPerformanceHistogram(const std::string& name, double duration) override {} void RecordUserMetricsAction(const std::string& name) override {} void ShowSurvey(DispatchCallback callback, const std::string& trigger) override {} void CanShowSurvey(DispatchCallback callback, const std::string& trigger) override {} // content::DevToolsFrontendHostDelegate: void HandleMessageFromDevToolsFrontend(base::Value message); // content::DevToolsAgentHostClient: void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) override; void AgentHostClosed(content::DevToolsAgentHost* agent_host) override; // content::WebContentsObserver: void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void WebContentsDestroyed() override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; // content::WebContentsDelegate: bool HandleKeyboardEvent(content::WebContents*, const content::NativeWebKeyboardEvent&) override; void CloseContents(content::WebContents* source) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; void SendMessageAck(int request_id, const base::Value* arg1); const char* GetDictionaryNameForSettingsName(const std::string& name) const; const char* GetDictionaryNameForSyncedPrefs() const; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void AddDevToolsExtensionsToClient(); #endif DevToolsContentsResizingStrategy contents_resizing_strategy_; gfx::Rect devtools_bounds_; bool can_dock_ = true; std::string dock_state_; bool activate_ = true; InspectableWebContentsDelegate* delegate_ = nullptr; // weak references. PrefService* pref_service_; // weak reference. std::unique_ptr<content::WebContents> web_contents_; // The default devtools created by this class when we don't have an external // one assigned by SetDevToolsWebContents. std::unique_ptr<content::WebContents> managed_devtools_web_contents_; // The external devtools assigned by SetDevToolsWebContents. content::WebContents* external_devtools_web_contents_ = nullptr; bool is_guest_; std::unique_ptr<InspectableWebContentsView> view_; bool frontend_loaded_ = false; scoped_refptr<content::DevToolsAgentHost> agent_host_; std::unique_ptr<content::DevToolsFrontendHost> frontend_host_; std::unique_ptr<DevToolsEmbedderMessageDispatcher> embedder_message_dispatcher_; class NetworkResourceLoader; std::set<std::unique_ptr<NetworkResourceLoader>, base::UniquePtrComparator> loaders_; using ExtensionsAPIs = std::map<std::string, std::string>; ExtensionsAPIs extensions_api_; // Contains the set of synced settings. // The DevTools frontend *must* call `Register` for each setting prior to // use, which guarantees that this set must not be persisted. base::flat_set<std::string> synced_setting_names_; base::WeakPtrFactory<InspectableWebContents> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
31,864
[Bug]: Dark mode in Devtools is not working on the latest 16.0.0 - 16.0.8 / 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.0 - 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 7 x64 SP1 ### What arch are you using? x64 ### Last Known Working Electron version 15.3.4 ### Expected Behavior Devtools should have a dark mode applied when the settings is set to 'Dark Mode'. ### Actual Behavior When switching to dark mode, it displays the message that 'Devtools requires a reload' but when I click on the reload button it does nothing. Restarting the app has no effect as well and stays on the light mode. This worked fine on the previous 15.3.2 version. ### Testcase Gist URL _No response_ ### Additional Information One thing I noticed, when updating from the last version (15.3.2) the dev tools will show up with dark mode enabled on the first run but on subsequent runs, it reverts back to light mode.
https://github.com/electron/electron/issues/31864
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2021-11-16T17:32:36Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kDevToolsSyncPreferences[] = "electron.devtools.sync_preferences"; const char kDevToolsSyncedPreferencesSyncEnabled[] = "electron.devtools.synced_preferences_sync_enabled"; const char kDevToolsSyncedPreferencesSyncDisabled[] = "electron.devtools.synced_preferences_sync_disabled"; const char kSyncDevToolsPreferencesFrontendName[] = "electron.sync_preferences"; const bool kSyncDevToolsPreferencesDefault = false; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; // Stores all instances of InspectableWebContents. InspectableWebContents::List g_web_contents_instances_; base::Value RectToDictionary(const gfx::Rect& bounds) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey("x", base::Value(bounds.x())); dict.SetKey("y", base::Value(bounds.y())); dict.SetKey("width", base::Value(bounds.width())); dict.SetKey("height", base::Value(bounds.height())); return dict; } gfx::Rect DictionaryToRect(const base::Value* dict) { const base::Value* found = dict->FindKey("x"); int x = found ? found->GetInt() : 0; found = dict->FindKey("y"); int y = found ? found->GetInt() : 0; found = dict->FindKey("width"); int width = found ? found->GetInt() : 800; found = dict->FindKey("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = base::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } void OnOpenItemComplete(const base::FilePath& path, const std::string& result) { platform_util::ShowItemInFolder(path); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI.streamWrite", &id, &chunkValue, &encodedValue); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::DictionaryValue response; response.SetInteger("statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); auto headers = std::make_unique<base::DictionaryValue>(); size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); response.Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; InspectableWebContents* const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static const InspectableWebContents::List& InspectableWebContents::GetAll() { return g_web_contents_instances_; } // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect(0, 0, 800, 600))); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncEnabled); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncDisabled); registry->RegisterBooleanPref(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = pref_service_->Get(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } g_web_contents_instances_.push_back(this); } InspectableWebContents::~InspectableWebContents() { g_web_contents_instances_.remove(this); // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!GetDevToolsWebContents()) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript), base::NullCallback()); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds)); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); } else { if (dock_state_.empty()) { const base::Value* prefs = pref_service_->GetDictionary(kDevToolsPreferences); const std::string* current_dock_state = prefs->FindStringKey("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } std::u16string javascript = base::UTF8ToUTF16( "UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::ListValue results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); auto extension_info = std::make_unique<base::DictionaryValue>(); extension_info->SetString("startPage", devtools_page_url.spec()); extension_info->SetString("name", extension->name()); extension_info->SetBoolean( "exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI.addExtensions", &results, NULL, NULL); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) {} void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); platform_util::OpenPath(path.DirName(), base::BindOnce(&OnOpenItemComplete, path)); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::RegisterPreference( const std::string& name, const RegisterOptions& options) { // kSyncDevToolsPreferenceFrontendName is not stored in any of the relevant // dictionaries. Skip registration. if (name == kSyncDevToolsPreferencesFrontendName) return; if (options.sync_mode == RegisterOptions::SyncMode::kSync) { synced_setting_names_.insert(name); } // Setting might have had a different sync status in the past. Move the // setting to the correct dictionary. const char* dictionary_to_remove_from = options.sync_mode == RegisterOptions::SyncMode::kSync ? kDevToolsPreferences : GetDictionaryNameForSyncedPrefs(); const std::string* settings_value = pref_service_->GetDictionary(dictionary_to_remove_from) ->FindStringKey(name); if (!settings_value) { return; } const char* dictionary_to_insert_into = GetDictionaryNameForSettingsName(name); // Settings already moved to the synced dictionary on a different device have // precedence. const std::string* already_synced_value = pref_service_->GetDictionary(dictionary_to_insert_into) ->FindStringKey(name); if (dictionary_to_insert_into == kDevToolsPreferences || !already_synced_value) { DictionaryPrefUpdate insert_update(pref_service_, dictionary_to_insert_into); insert_update.Get()->SetKey(name, base::Value(*settings_value)); } DictionaryPrefUpdate remove_update(pref_service_, dictionary_to_remove_from); remove_update.Get()->RemoveKey(name); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { base::Value settings(base::Value::Type::DICTIONARY); settings.SetBoolKey(kSyncDevToolsPreferencesFrontendName, pref_service_->GetBoolean(kDevToolsSyncPreferences)); settings.MergeDictionary(pref_service_->GetDictionary(kDevToolsPreferences)); settings.MergeDictionary( pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs())); std::move(callback).Run(&settings); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { // Handle kSyncDevToolsPreferencesFrontendName if (name == kSyncDevToolsPreferencesFrontendName) { base::Value pref = base::Value(pref_service_->GetBoolean(kDevToolsSyncPreferences)); std::move(callback).Run(&pref); return; } // Check dev tools prefs if (auto* pref = pref_service_->GetDictionary(kDevToolsPreferences)->FindKey(name)) { std::move(callback).Run(pref); return; } // Check synced prefs if (auto* pref = pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs()) ->FindKey(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, value == "true"); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->SetKey(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->RemoveKey(name); } void InspectableWebContents::ClearPreferences() { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); DictionaryPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update.Get()->DictClear(); DictionaryPrefUpdate sync_enabled_update( pref_service_, kDevToolsSyncedPreferencesSyncEnabled); sync_enabled_update.Get()->DictClear(); DictionaryPrefUpdate sync_disabled_update( pref_service_, kDevToolsSyncedPreferencesSyncDisabled); sync_disabled_update.Get()->DictClear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { // TODO(anyone): do we want devtool syncing in Electron? base::Value result(base::Value::Type::DICTIONARY); result.SetBoolKey("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = nullptr; base::Value* params = nullptr; if (message.is_dict()) { method = message.FindStringKey(kFrontendHostMethod); params = message.FindKey(kFrontendHostParams); } if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } base::Value empty_params(base::Value::Type::LIST); if (!params) { params = &empty_params; } int id = message.FindIntKey(kFrontendHostId).value_or(0); std::vector<base::Value> params_list; if (params) params_list = std::move(*params).TakeListDeprecated(); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.size() < kMaxMessageChunkSize) { std::string param; base::EscapeJSONString(str_message, true, &param); std::u16string javascript = base::UTF8ToUTF16("DevToolsAPI.dispatchMessage(" + param + ");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); return; } base::Value total_size(static_cast<int>(str_message.length())); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::Value message_value(str_message.substr(pos, kMaxMessageChunkSize)); CallClientFunction("DevToolsAPI.dispatchMessageChunk", &message_value, pos ? nullptr : &total_size, nullptr); } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(), base::GenerateGUID().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { base::Value id_value(request_id); CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr); } const char* InspectableWebContents::GetDictionaryNameForSettingsName( const std::string& name) const { return synced_setting_names_.contains(name) ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsPreferences; } const char* InspectableWebContents::GetDictionaryNameForSyncedPrefs() const { const bool isDevToolsSyncEnabled = pref_service_->GetBoolean(kDevToolsSyncPreferences); return isDevToolsSyncEnabled ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsSyncedPreferencesSyncDisabled; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
31,864
[Bug]: Dark mode in Devtools is not working on the latest 16.0.0 - 16.0.8 / 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.0 - 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 7 x64 SP1 ### What arch are you using? x64 ### Last Known Working Electron version 15.3.4 ### Expected Behavior Devtools should have a dark mode applied when the settings is set to 'Dark Mode'. ### Actual Behavior When switching to dark mode, it displays the message that 'Devtools requires a reload' but when I click on the reload button it does nothing. Restarting the app has no effect as well and stays on the light mode. This worked fine on the previous 15.3.2 version. ### Testcase Gist URL _No response_ ### Additional Information One thing I noticed, when updating from the last version (15.3.2) the dev tools will show up with dark mode enabled on the first run but on subsequent runs, it reverts back to light mode.
https://github.com/electron/electron/issues/31864
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2021-11-16T17:32:36Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/containers/span.h" #include "base/containers/unique_ptr_adapters.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "chrome/browser/devtools/devtools_embedder_message_dispatcher.h" #include "chrome/browser/devtools/devtools_settings.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "ui/gfx/geometry/rect.h" class PrefService; class PrefRegistrySimple; struct RegisterOptions; namespace electron { class InspectableWebContentsDelegate; class InspectableWebContentsView; class InspectableWebContents : public content::DevToolsAgentHostClient, public content::WebContentsObserver, public content::WebContentsDelegate, public DevToolsEmbedderMessageDispatcher::Delegate { public: using List = std::list<InspectableWebContents*>; static const List& GetAll(); static void RegisterPrefs(PrefRegistrySimple* pref_registry); InspectableWebContents(std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest); ~InspectableWebContents() override; // disable copy InspectableWebContents(const InspectableWebContents&) = delete; InspectableWebContents& operator=(const InspectableWebContents&) = delete; InspectableWebContentsView* GetView() const; content::WebContents* GetWebContents() const; content::WebContents* GetDevToolsWebContents() const; void SetDelegate(InspectableWebContentsDelegate* delegate); InspectableWebContentsDelegate* GetDelegate() const; bool IsGuest() const; void ReleaseWebContents(); void SetDevToolsWebContents(content::WebContents* devtools); void SetDockState(const std::string& state); void ShowDevTools(bool activate); void CloseDevTools(); bool IsDevToolsViewShowing(); void AttachTo(scoped_refptr<content::DevToolsAgentHost>); void Detach(); void CallClientFunction(const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3); void InspectElement(int x, int y); // Return the last position and size of devtools window. gfx::Rect GetDevToolsBounds() const; void SaveDevToolsBounds(const gfx::Rect& bounds); // Return the last set zoom level of devtools window. double GetDevToolsZoomLevel() const; void UpdateDevToolsZoomLevel(double level); private: // DevToolsEmbedderMessageDispacher::Delegate void ActivateWindow() override; void CloseWindow() override; void LoadCompleted() override; void SetInspectedPageBounds(const gfx::Rect& rect) override; void InspectElementCompleted() override; void InspectedURLChanged(const std::string& url) override; void LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) override; void SetIsDocked(DispatchCallback callback, bool is_docked) override; void OpenInNewTab(const std::string& url) override; void ShowItemInFolder(const std::string& file_system_path) override; void SaveToFile(const std::string& url, const std::string& content, bool save_as) override; void AppendToFile(const std::string& url, const std::string& content) override; void RequestFileSystems() override; void AddFileSystem(const std::string& type) override; void RemoveFileSystem(const std::string& file_system_path) override; void UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) override; void IndexPath(int index_request_id, const std::string& file_system_path, const std::string& excluded_folders) override; void StopIndexing(int index_request_id) override; void SearchInPath(int search_request_id, const std::string& file_system_path, const std::string& query) override; void SetWhitelistedShortcuts(const std::string& message) override; void SetEyeDropperActive(bool active) override; void ShowCertificateViewer(const std::string& cert_chain) override; void ZoomIn() override; void ZoomOut() override; void ResetZoom() override; void SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) override; void SetDevicesUpdatesEnabled(bool enabled) override; void PerformActionOnRemotePage(const std::string& page_id, const std::string& action) override; void OpenRemotePage(const std::string& browser_id, const std::string& url) override; void OpenNodeFrontend() override; void DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) override; void SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) override; void RegisterPreference(const std::string& name, const RegisterOptions& options) override; void GetPreferences(DispatchCallback callback) override; void GetPreference(DispatchCallback callback, const std::string& name) override; void SetPreference(const std::string& name, const std::string& value) override; void RemovePreference(const std::string& name) override; void ClearPreferences() override; void GetSyncInformation(DispatchCallback callback) override; void ConnectionReady() override; void RegisterExtensionsAPI(const std::string& origin, const std::string& script) override; void Reattach(DispatchCallback callback) override; void RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) override {} void ReadyForTest() override {} void SetOpenNewWindowForPopups(bool value) override {} void RecordPerformanceHistogram(const std::string& name, double duration) override {} void RecordUserMetricsAction(const std::string& name) override {} void ShowSurvey(DispatchCallback callback, const std::string& trigger) override {} void CanShowSurvey(DispatchCallback callback, const std::string& trigger) override {} // content::DevToolsFrontendHostDelegate: void HandleMessageFromDevToolsFrontend(base::Value message); // content::DevToolsAgentHostClient: void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) override; void AgentHostClosed(content::DevToolsAgentHost* agent_host) override; // content::WebContentsObserver: void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void WebContentsDestroyed() override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; // content::WebContentsDelegate: bool HandleKeyboardEvent(content::WebContents*, const content::NativeWebKeyboardEvent&) override; void CloseContents(content::WebContents* source) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; void SendMessageAck(int request_id, const base::Value* arg1); const char* GetDictionaryNameForSettingsName(const std::string& name) const; const char* GetDictionaryNameForSyncedPrefs() const; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void AddDevToolsExtensionsToClient(); #endif DevToolsContentsResizingStrategy contents_resizing_strategy_; gfx::Rect devtools_bounds_; bool can_dock_ = true; std::string dock_state_; bool activate_ = true; InspectableWebContentsDelegate* delegate_ = nullptr; // weak references. PrefService* pref_service_; // weak reference. std::unique_ptr<content::WebContents> web_contents_; // The default devtools created by this class when we don't have an external // one assigned by SetDevToolsWebContents. std::unique_ptr<content::WebContents> managed_devtools_web_contents_; // The external devtools assigned by SetDevToolsWebContents. content::WebContents* external_devtools_web_contents_ = nullptr; bool is_guest_; std::unique_ptr<InspectableWebContentsView> view_; bool frontend_loaded_ = false; scoped_refptr<content::DevToolsAgentHost> agent_host_; std::unique_ptr<content::DevToolsFrontendHost> frontend_host_; std::unique_ptr<DevToolsEmbedderMessageDispatcher> embedder_message_dispatcher_; class NetworkResourceLoader; std::set<std::unique_ptr<NetworkResourceLoader>, base::UniquePtrComparator> loaders_; using ExtensionsAPIs = std::map<std::string, std::string>; ExtensionsAPIs extensions_api_; // Contains the set of synced settings. // The DevTools frontend *must* call `Register` for each setting prior to // use, which guarantees that this set must not be persisted. base::flat_set<std::string> synced_setting_names_; base::WeakPtrFactory<InspectableWebContents> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
33,102
[Bug]: DevTools shortcut settings do not persist
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? Windows ### Operating System Version 10.0.19043 Build 19043 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting remains last selected value ### Actual Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting reverts to default ### Testcase Gist URL _No response_ ### Additional Information Seems like it could be related to #31864
https://github.com/electron/electron/issues/33102
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2022-02-28T15:05:48Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kDevToolsSyncPreferences[] = "electron.devtools.sync_preferences"; const char kDevToolsSyncedPreferencesSyncEnabled[] = "electron.devtools.synced_preferences_sync_enabled"; const char kDevToolsSyncedPreferencesSyncDisabled[] = "electron.devtools.synced_preferences_sync_disabled"; const char kSyncDevToolsPreferencesFrontendName[] = "electron.sync_preferences"; const bool kSyncDevToolsPreferencesDefault = false; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; // Stores all instances of InspectableWebContents. InspectableWebContents::List g_web_contents_instances_; base::Value RectToDictionary(const gfx::Rect& bounds) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey("x", base::Value(bounds.x())); dict.SetKey("y", base::Value(bounds.y())); dict.SetKey("width", base::Value(bounds.width())); dict.SetKey("height", base::Value(bounds.height())); return dict; } gfx::Rect DictionaryToRect(const base::Value* dict) { const base::Value* found = dict->FindKey("x"); int x = found ? found->GetInt() : 0; found = dict->FindKey("y"); int y = found ? found->GetInt() : 0; found = dict->FindKey("width"); int width = found ? found->GetInt() : 800; found = dict->FindKey("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = base::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } void OnOpenItemComplete(const base::FilePath& path, const std::string& result) { platform_util::ShowItemInFolder(path); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI.streamWrite", &id, &chunkValue, &encodedValue); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::DictionaryValue response; response.SetInteger("statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); auto headers = std::make_unique<base::DictionaryValue>(); size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); response.Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; InspectableWebContents* const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static const InspectableWebContents::List& InspectableWebContents::GetAll() { return g_web_contents_instances_; } // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect(0, 0, 800, 600))); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncEnabled); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncDisabled); registry->RegisterBooleanPref(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = pref_service_->Get(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } g_web_contents_instances_.push_back(this); } InspectableWebContents::~InspectableWebContents() { g_web_contents_instances_.remove(this); // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!GetDevToolsWebContents()) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript), base::NullCallback()); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds)); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); } else { if (dock_state_.empty()) { const base::Value* prefs = pref_service_->GetDictionary(kDevToolsPreferences); const std::string* current_dock_state = prefs->FindStringKey("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } std::u16string javascript = base::UTF8ToUTF16( "UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::ListValue results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); auto extension_info = std::make_unique<base::DictionaryValue>(); extension_info->SetString("startPage", devtools_page_url.spec()); extension_info->SetString("name", extension->name()); extension_info->SetBoolean( "exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI.addExtensions", &results, NULL, NULL); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) {} void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); platform_util::OpenPath(path.DirName(), base::BindOnce(&OnOpenItemComplete, path)); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::RegisterPreference( const std::string& name, const RegisterOptions& options) { // kSyncDevToolsPreferenceFrontendName is not stored in any of the relevant // dictionaries. Skip registration. if (name == kSyncDevToolsPreferencesFrontendName) return; if (options.sync_mode == RegisterOptions::SyncMode::kSync) { synced_setting_names_.insert(name); } // Setting might have had a different sync status in the past. Move the // setting to the correct dictionary. const char* dictionary_to_remove_from = options.sync_mode == RegisterOptions::SyncMode::kSync ? kDevToolsPreferences : GetDictionaryNameForSyncedPrefs(); const std::string* settings_value = pref_service_->GetDictionary(dictionary_to_remove_from) ->FindStringKey(name); if (!settings_value) { return; } const char* dictionary_to_insert_into = GetDictionaryNameForSettingsName(name); // Settings already moved to the synced dictionary on a different device have // precedence. const std::string* already_synced_value = pref_service_->GetDictionary(dictionary_to_insert_into) ->FindStringKey(name); if (dictionary_to_insert_into == kDevToolsPreferences || !already_synced_value) { DictionaryPrefUpdate insert_update(pref_service_, dictionary_to_insert_into); insert_update.Get()->SetKey(name, base::Value(*settings_value)); } DictionaryPrefUpdate remove_update(pref_service_, dictionary_to_remove_from); remove_update.Get()->RemoveKey(name); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { base::Value settings(base::Value::Type::DICTIONARY); settings.SetBoolKey(kSyncDevToolsPreferencesFrontendName, pref_service_->GetBoolean(kDevToolsSyncPreferences)); settings.MergeDictionary(pref_service_->GetDictionary(kDevToolsPreferences)); settings.MergeDictionary( pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs())); std::move(callback).Run(&settings); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { // Handle kSyncDevToolsPreferencesFrontendName if (name == kSyncDevToolsPreferencesFrontendName) { base::Value pref = base::Value(pref_service_->GetBoolean(kDevToolsSyncPreferences)); std::move(callback).Run(&pref); return; } // Check dev tools prefs if (auto* pref = pref_service_->GetDictionary(kDevToolsPreferences)->FindKey(name)) { std::move(callback).Run(pref); return; } // Check synced prefs if (auto* pref = pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs()) ->FindKey(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, value == "true"); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->SetKey(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->RemoveKey(name); } void InspectableWebContents::ClearPreferences() { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); DictionaryPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update.Get()->DictClear(); DictionaryPrefUpdate sync_enabled_update( pref_service_, kDevToolsSyncedPreferencesSyncEnabled); sync_enabled_update.Get()->DictClear(); DictionaryPrefUpdate sync_disabled_update( pref_service_, kDevToolsSyncedPreferencesSyncDisabled); sync_disabled_update.Get()->DictClear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { // TODO(anyone): do we want devtool syncing in Electron? base::Value result(base::Value::Type::DICTIONARY); result.SetBoolKey("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = nullptr; base::Value* params = nullptr; if (message.is_dict()) { method = message.FindStringKey(kFrontendHostMethod); params = message.FindKey(kFrontendHostParams); } if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } base::Value empty_params(base::Value::Type::LIST); if (!params) { params = &empty_params; } int id = message.FindIntKey(kFrontendHostId).value_or(0); std::vector<base::Value> params_list; if (params) params_list = std::move(*params).TakeListDeprecated(); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.size() < kMaxMessageChunkSize) { std::string param; base::EscapeJSONString(str_message, true, &param); std::u16string javascript = base::UTF8ToUTF16("DevToolsAPI.dispatchMessage(" + param + ");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); return; } base::Value total_size(static_cast<int>(str_message.length())); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::Value message_value(str_message.substr(pos, kMaxMessageChunkSize)); CallClientFunction("DevToolsAPI.dispatchMessageChunk", &message_value, pos ? nullptr : &total_size, nullptr); } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(), base::GenerateGUID().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { base::Value id_value(request_id); CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr); } const char* InspectableWebContents::GetDictionaryNameForSettingsName( const std::string& name) const { return synced_setting_names_.contains(name) ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsPreferences; } const char* InspectableWebContents::GetDictionaryNameForSyncedPrefs() const { const bool isDevToolsSyncEnabled = pref_service_->GetBoolean(kDevToolsSyncPreferences); return isDevToolsSyncEnabled ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsSyncedPreferencesSyncDisabled; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,102
[Bug]: DevTools shortcut settings do not persist
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? Windows ### Operating System Version 10.0.19043 Build 19043 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting remains last selected value ### Actual Behavior 1. Open DevTools->Settings->Shortcuts 2. Change "Match shortcuts from preset" to "Visual Studio Code" 3. Close devtools and reopen 4. Shortcut setting reverts to default ### Testcase Gist URL _No response_ ### Additional Information Seems like it could be related to #31864
https://github.com/electron/electron/issues/33102
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2022-02-28T15:05:48Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/containers/span.h" #include "base/containers/unique_ptr_adapters.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "chrome/browser/devtools/devtools_embedder_message_dispatcher.h" #include "chrome/browser/devtools/devtools_settings.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "ui/gfx/geometry/rect.h" class PrefService; class PrefRegistrySimple; struct RegisterOptions; namespace electron { class InspectableWebContentsDelegate; class InspectableWebContentsView; class InspectableWebContents : public content::DevToolsAgentHostClient, public content::WebContentsObserver, public content::WebContentsDelegate, public DevToolsEmbedderMessageDispatcher::Delegate { public: using List = std::list<InspectableWebContents*>; static const List& GetAll(); static void RegisterPrefs(PrefRegistrySimple* pref_registry); InspectableWebContents(std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest); ~InspectableWebContents() override; // disable copy InspectableWebContents(const InspectableWebContents&) = delete; InspectableWebContents& operator=(const InspectableWebContents&) = delete; InspectableWebContentsView* GetView() const; content::WebContents* GetWebContents() const; content::WebContents* GetDevToolsWebContents() const; void SetDelegate(InspectableWebContentsDelegate* delegate); InspectableWebContentsDelegate* GetDelegate() const; bool IsGuest() const; void ReleaseWebContents(); void SetDevToolsWebContents(content::WebContents* devtools); void SetDockState(const std::string& state); void ShowDevTools(bool activate); void CloseDevTools(); bool IsDevToolsViewShowing(); void AttachTo(scoped_refptr<content::DevToolsAgentHost>); void Detach(); void CallClientFunction(const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3); void InspectElement(int x, int y); // Return the last position and size of devtools window. gfx::Rect GetDevToolsBounds() const; void SaveDevToolsBounds(const gfx::Rect& bounds); // Return the last set zoom level of devtools window. double GetDevToolsZoomLevel() const; void UpdateDevToolsZoomLevel(double level); private: // DevToolsEmbedderMessageDispacher::Delegate void ActivateWindow() override; void CloseWindow() override; void LoadCompleted() override; void SetInspectedPageBounds(const gfx::Rect& rect) override; void InspectElementCompleted() override; void InspectedURLChanged(const std::string& url) override; void LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) override; void SetIsDocked(DispatchCallback callback, bool is_docked) override; void OpenInNewTab(const std::string& url) override; void ShowItemInFolder(const std::string& file_system_path) override; void SaveToFile(const std::string& url, const std::string& content, bool save_as) override; void AppendToFile(const std::string& url, const std::string& content) override; void RequestFileSystems() override; void AddFileSystem(const std::string& type) override; void RemoveFileSystem(const std::string& file_system_path) override; void UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) override; void IndexPath(int index_request_id, const std::string& file_system_path, const std::string& excluded_folders) override; void StopIndexing(int index_request_id) override; void SearchInPath(int search_request_id, const std::string& file_system_path, const std::string& query) override; void SetWhitelistedShortcuts(const std::string& message) override; void SetEyeDropperActive(bool active) override; void ShowCertificateViewer(const std::string& cert_chain) override; void ZoomIn() override; void ZoomOut() override; void ResetZoom() override; void SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) override; void SetDevicesUpdatesEnabled(bool enabled) override; void PerformActionOnRemotePage(const std::string& page_id, const std::string& action) override; void OpenRemotePage(const std::string& browser_id, const std::string& url) override; void OpenNodeFrontend() override; void DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) override; void SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) override; void RegisterPreference(const std::string& name, const RegisterOptions& options) override; void GetPreferences(DispatchCallback callback) override; void GetPreference(DispatchCallback callback, const std::string& name) override; void SetPreference(const std::string& name, const std::string& value) override; void RemovePreference(const std::string& name) override; void ClearPreferences() override; void GetSyncInformation(DispatchCallback callback) override; void ConnectionReady() override; void RegisterExtensionsAPI(const std::string& origin, const std::string& script) override; void Reattach(DispatchCallback callback) override; void RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) override {} void ReadyForTest() override {} void SetOpenNewWindowForPopups(bool value) override {} void RecordPerformanceHistogram(const std::string& name, double duration) override {} void RecordUserMetricsAction(const std::string& name) override {} void ShowSurvey(DispatchCallback callback, const std::string& trigger) override {} void CanShowSurvey(DispatchCallback callback, const std::string& trigger) override {} // content::DevToolsFrontendHostDelegate: void HandleMessageFromDevToolsFrontend(base::Value message); // content::DevToolsAgentHostClient: void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) override; void AgentHostClosed(content::DevToolsAgentHost* agent_host) override; // content::WebContentsObserver: void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void WebContentsDestroyed() override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; // content::WebContentsDelegate: bool HandleKeyboardEvent(content::WebContents*, const content::NativeWebKeyboardEvent&) override; void CloseContents(content::WebContents* source) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; void SendMessageAck(int request_id, const base::Value* arg1); const char* GetDictionaryNameForSettingsName(const std::string& name) const; const char* GetDictionaryNameForSyncedPrefs() const; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void AddDevToolsExtensionsToClient(); #endif DevToolsContentsResizingStrategy contents_resizing_strategy_; gfx::Rect devtools_bounds_; bool can_dock_ = true; std::string dock_state_; bool activate_ = true; InspectableWebContentsDelegate* delegate_ = nullptr; // weak references. PrefService* pref_service_; // weak reference. std::unique_ptr<content::WebContents> web_contents_; // The default devtools created by this class when we don't have an external // one assigned by SetDevToolsWebContents. std::unique_ptr<content::WebContents> managed_devtools_web_contents_; // The external devtools assigned by SetDevToolsWebContents. content::WebContents* external_devtools_web_contents_ = nullptr; bool is_guest_; std::unique_ptr<InspectableWebContentsView> view_; bool frontend_loaded_ = false; scoped_refptr<content::DevToolsAgentHost> agent_host_; std::unique_ptr<content::DevToolsFrontendHost> frontend_host_; std::unique_ptr<DevToolsEmbedderMessageDispatcher> embedder_message_dispatcher_; class NetworkResourceLoader; std::set<std::unique_ptr<NetworkResourceLoader>, base::UniquePtrComparator> loaders_; using ExtensionsAPIs = std::map<std::string, std::string>; ExtensionsAPIs extensions_api_; // Contains the set of synced settings. // The DevTools frontend *must* call `Register` for each setting prior to // use, which guarantees that this set must not be persisted. base::flat_set<std::string> synced_setting_names_; base::WeakPtrFactory<InspectableWebContents> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
31,864
[Bug]: Dark mode in Devtools is not working on the latest 16.0.0 - 16.0.8 / 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.0 - 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 7 x64 SP1 ### What arch are you using? x64 ### Last Known Working Electron version 15.3.4 ### Expected Behavior Devtools should have a dark mode applied when the settings is set to 'Dark Mode'. ### Actual Behavior When switching to dark mode, it displays the message that 'Devtools requires a reload' but when I click on the reload button it does nothing. Restarting the app has no effect as well and stays on the light mode. This worked fine on the previous 15.3.2 version. ### Testcase Gist URL _No response_ ### Additional Information One thing I noticed, when updating from the last version (15.3.2) the dev tools will show up with dark mode enabled on the first run but on subsequent runs, it reverts back to light mode.
https://github.com/electron/electron/issues/31864
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2021-11-16T17:32:36Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> #include <utility> #include "base/base64.h" #include "base/guid.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/json/string_escape.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/values.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/shared_cors_origin_access_list.h" #include "content/public/browser/storage_partition.h" #include "content/public/common/user_agent.h" #include "ipc/ipc_channel.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/logging/logging_utils.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "v8/include/v8.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/extensions/chrome_manifest_url_handlers.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/render_process_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/permissions/permissions_data.h" #include "shell/browser/electron_browser_context.h" #endif namespace electron { namespace { const double kPresetZoomFactors[] = {0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; const char kChromeUIDevToolsURL[] = "devtools://devtools/bundled/devtools_app.html?" "remoteBase=%s&" "can_dock=%s&" "toolbarColor=rgba(223,223,223,1)&" "textColor=rgba(0,0,0,1)&" "experiments=true"; const char kChromeUIDevToolsRemoteFrontendBase[] = "https://chrome-devtools-frontend.appspot.com/"; const char kChromeUIDevToolsRemoteFrontendPath[] = "serve_file"; const char kDevToolsBoundsPref[] = "electron.devtools.bounds"; const char kDevToolsZoomPref[] = "electron.devtools.zoom"; const char kDevToolsPreferences[] = "electron.devtools.preferences"; const char kDevToolsSyncPreferences[] = "electron.devtools.sync_preferences"; const char kDevToolsSyncedPreferencesSyncEnabled[] = "electron.devtools.synced_preferences_sync_enabled"; const char kDevToolsSyncedPreferencesSyncDisabled[] = "electron.devtools.synced_preferences_sync_disabled"; const char kSyncDevToolsPreferencesFrontendName[] = "electron.sync_preferences"; const bool kSyncDevToolsPreferencesDefault = false; const char kFrontendHostId[] = "id"; const char kFrontendHostMethod[] = "method"; const char kFrontendHostParams[] = "params"; const char kTitleFormat[] = "Developer Tools - %s"; const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; // Stores all instances of InspectableWebContents. InspectableWebContents::List g_web_contents_instances_; base::Value RectToDictionary(const gfx::Rect& bounds) { base::Value dict(base::Value::Type::DICTIONARY); dict.SetKey("x", base::Value(bounds.x())); dict.SetKey("y", base::Value(bounds.y())); dict.SetKey("width", base::Value(bounds.width())); dict.SetKey("height", base::Value(bounds.height())); return dict; } gfx::Rect DictionaryToRect(const base::Value* dict) { const base::Value* found = dict->FindKey("x"); int x = found ? found->GetInt() : 0; found = dict->FindKey("y"); int y = found ? found->GetInt() : 0; found = dict->FindKey("width"); int width = found ? found->GetInt() : 800; found = dict->FindKey("height"); int height = found ? found->GetInt() : 600; return gfx::Rect(x, y, width, height); } bool IsPointInRect(const gfx::Point& point, const gfx::Rect& rect) { return point.x() > rect.x() && point.x() < (rect.width() + rect.x()) && point.y() > rect.y() && point.y() < (rect.height() + rect.y()); } bool IsPointInScreen(const gfx::Point& point) { for (const auto& display : display::Screen::GetScreen()->GetAllDisplays()) { if (IsPointInRect(point, display.bounds())) return true; } return false; } void SetZoomLevelForWebContents(content::WebContents* web_contents, double level) { content::HostZoomMap::SetZoomLevel(web_contents, level); } double GetNextZoomLevel(double level, bool out) { double factor = blink::PageZoomLevelToZoomFactor(level); size_t size = base::size(kPresetZoomFactors); for (size_t i = 0; i < size; ++i) { if (!blink::PageZoomValuesEqual(kPresetZoomFactors[i], factor)) continue; if (out && i > 0) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i - 1]); if (!out && i != size - 1) return blink::PageZoomFactorToZoomLevel(kPresetZoomFactors[i + 1]); } return level; } GURL GetRemoteBaseURL() { return GURL(base::StringPrintf("%s%s/%s/", kChromeUIDevToolsRemoteFrontendBase, kChromeUIDevToolsRemoteFrontendPath, content::GetChromiumGitRevision().c_str())); } GURL GetDevToolsURL(bool can_dock) { auto url_string = base::StringPrintf(kChromeUIDevToolsURL, GetRemoteBaseURL().spec().c_str(), can_dock ? "true" : ""); return GURL(url_string); } void OnOpenItemComplete(const base::FilePath& path, const std::string& result) { platform_util::ShowItemInFolder(path); } constexpr base::TimeDelta kInitialBackoffDelay = base::Milliseconds(250); constexpr base::TimeDelta kMaxBackoffDelay = base::Seconds(10); } // namespace class InspectableWebContents::NetworkResourceLoader : public network::SimpleURLLoaderStreamConsumer { public: class URLLoaderFactoryHolder { public: network::mojom::URLLoaderFactory* get() { return ptr_.get() ? ptr_.get() : refptr_.get(); } void operator=(std::unique_ptr<network::mojom::URLLoaderFactory>&& ptr) { ptr_ = std::move(ptr); } void operator=(scoped_refptr<network::SharedURLLoaderFactory>&& refptr) { refptr_ = std::move(refptr); } private: std::unique_ptr<network::mojom::URLLoaderFactory> ptr_; scoped_refptr<network::SharedURLLoaderFactory> refptr_; }; static void Create(int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta retry_delay = base::TimeDelta()) { auto resource_loader = std::make_unique<InspectableWebContents::NetworkResourceLoader>( stream_id, bindings, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback), retry_delay); bindings->loaders_.insert(std::move(resource_loader)); } NetworkResourceLoader( int stream_id, InspectableWebContents* bindings, const network::ResourceRequest& resource_request, const net::NetworkTrafficAnnotationTag& traffic_annotation, URLLoaderFactoryHolder url_loader_factory, DispatchCallback callback, base::TimeDelta delay) : stream_id_(stream_id), bindings_(bindings), resource_request_(resource_request), traffic_annotation_(traffic_annotation), loader_(network::SimpleURLLoader::Create( std::make_unique<network::ResourceRequest>(resource_request), traffic_annotation)), url_loader_factory_(std::move(url_loader_factory)), callback_(std::move(callback)), retry_delay_(delay) { loader_->SetOnResponseStartedCallback(base::BindOnce( &NetworkResourceLoader::OnResponseStarted, base::Unretained(this))); timer_.Start(FROM_HERE, delay, base::BindRepeating(&NetworkResourceLoader::DownloadAsStream, base::Unretained(this))); } NetworkResourceLoader(const NetworkResourceLoader&) = delete; NetworkResourceLoader& operator=(const NetworkResourceLoader&) = delete; private: void DownloadAsStream() { loader_->DownloadAsStream(url_loader_factory_.get(), this); } base::TimeDelta GetNextExponentialBackoffDelay(const base::TimeDelta& delta) { if (delta.is_zero()) { return kInitialBackoffDelay; } else { return delta * 1.3; } } void OnResponseStarted(const GURL& final_url, const network::mojom::URLResponseHead& response_head) { response_headers_ = response_head.headers; } void OnDataReceived(base::StringPiece chunk, base::OnceClosure resume) override { base::Value chunkValue; bool encoded = !base::IsStringUTF8(chunk); if (encoded) { std::string encoded_string; base::Base64Encode(chunk, &encoded_string); chunkValue = base::Value(std::move(encoded_string)); } else { chunkValue = base::Value(chunk); } base::Value id(stream_id_); base::Value encodedValue(encoded); bindings_->CallClientFunction("DevToolsAPI.streamWrite", &id, &chunkValue, &encodedValue); std::move(resume).Run(); } void OnComplete(bool success) override { if (!success && loader_->NetError() == net::ERR_INSUFFICIENT_RESOURCES && retry_delay_ < kMaxBackoffDelay) { const base::TimeDelta delay = GetNextExponentialBackoffDelay(retry_delay_); LOG(WARNING) << "InspectableWebContents::NetworkResourceLoader id = " << stream_id_ << " failed with insufficient resources, retrying in " << delay << "." << std::endl; NetworkResourceLoader::Create( stream_id_, bindings_, resource_request_, traffic_annotation_, std::move(url_loader_factory_), std::move(callback_), delay); } else { base::DictionaryValue response; response.SetInteger("statusCode", response_headers_ ? response_headers_->response_code() : net::HTTP_OK); auto headers = std::make_unique<base::DictionaryValue>(); size_t iterator = 0; std::string name; std::string value; while (response_headers_ && response_headers_->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); response.Set("headers", std::move(headers)); std::move(callback_).Run(&response); } bindings_->loaders_.erase(bindings_->loaders_.find(this)); } void OnRetry(base::OnceClosure start_retry) override {} const int stream_id_; InspectableWebContents* const bindings_; const network::ResourceRequest resource_request_; const net::NetworkTrafficAnnotationTag traffic_annotation_; std::unique_ptr<network::SimpleURLLoader> loader_; URLLoaderFactoryHolder url_loader_factory_; DispatchCallback callback_; scoped_refptr<net::HttpResponseHeaders> response_headers_; base::OneShotTimer timer_; base::TimeDelta retry_delay_; }; // Implemented separately on each platform. InspectableWebContentsView* CreateInspectableContentsView( InspectableWebContents* inspectable_web_contents); // static const InspectableWebContents::List& InspectableWebContents::GetAll() { return g_web_contents_instances_; } // static void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) { registry->RegisterDictionaryPref(kDevToolsBoundsPref, RectToDictionary(gfx::Rect(0, 0, 800, 600))); registry->RegisterDoublePref(kDevToolsZoomPref, 0.); registry->RegisterDictionaryPref(kDevToolsPreferences); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncEnabled); registry->RegisterDictionaryPref(kDevToolsSyncedPreferencesSyncDisabled); registry->RegisterBooleanPref(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); } InspectableWebContents::InspectableWebContents( std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest) : pref_service_(pref_service), web_contents_(std::move(web_contents)), is_guest_(is_guest), view_(CreateInspectableContentsView(this)) { const base::Value* bounds_dict = pref_service_->Get(kDevToolsBoundsPref); if (bounds_dict->is_dict()) { devtools_bounds_ = DictionaryToRect(bounds_dict); // Sometimes the devtools window is out of screen or has too small size. if (devtools_bounds_.height() < 100 || devtools_bounds_.width() < 100) { devtools_bounds_.set_height(600); devtools_bounds_.set_width(800); } if (!IsPointInScreen(devtools_bounds_.origin())) { gfx::Rect display; if (!is_guest && web_contents_->GetNativeView()) { display = display::Screen::GetScreen() ->GetDisplayNearestView(web_contents_->GetNativeView()) .bounds(); } else { display = display::Screen::GetScreen()->GetPrimaryDisplay().bounds(); } devtools_bounds_.set_x(display.x() + (display.width() - devtools_bounds_.width()) / 2); devtools_bounds_.set_y( display.y() + (display.height() - devtools_bounds_.height()) / 2); } } g_web_contents_instances_.push_back(this); } InspectableWebContents::~InspectableWebContents() { g_web_contents_instances_.remove(this); // Unsubscribe from devtools and Clean up resources. if (GetDevToolsWebContents()) WebContentsDestroyed(); // Let destructor destroy managed_devtools_web_contents_. } InspectableWebContentsView* InspectableWebContents::GetView() const { return view_.get(); } content::WebContents* InspectableWebContents::GetWebContents() const { return web_contents_.get(); } content::WebContents* InspectableWebContents::GetDevToolsWebContents() const { if (external_devtools_web_contents_) return external_devtools_web_contents_; else return managed_devtools_web_contents_.get(); } void InspectableWebContents::InspectElement(int x, int y) { if (agent_host_) agent_host_->InspectElement(web_contents_->GetMainFrame(), x, y); } void InspectableWebContents::SetDelegate( InspectableWebContentsDelegate* delegate) { delegate_ = delegate; } InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } bool InspectableWebContents::IsGuest() const { return is_guest_; } void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); view_.reset(); } void InspectableWebContents::SetDockState(const std::string& state) { if (state == "detach") { can_dock_ = false; } else { can_dock_ = true; dock_state_ = state; } } void InspectableWebContents::SetDevToolsWebContents( content::WebContents* devtools) { if (!managed_devtools_web_contents_) external_devtools_web_contents_ = devtools; } void InspectableWebContents::ShowDevTools(bool activate) { if (embedder_message_dispatcher_) { if (managed_devtools_web_contents_) view_->ShowDevTools(activate); return; } activate_ = activate; // Show devtools only after it has done loading, this is to make sure the // SetIsDocked is called *BEFORE* ShowDevTools. embedder_message_dispatcher_ = DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this); if (!external_devtools_web_contents_) { // no external devtools managed_devtools_web_contents_ = content::WebContents::Create( content::WebContents::CreateParams(web_contents_->GetBrowserContext())); managed_devtools_web_contents_->SetDelegate(this); v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::HandleScope scope(isolate); api::WebContents::FromOrCreate(isolate, managed_devtools_web_contents_.get()); } Observe(GetDevToolsWebContents()); AttachTo(content::DevToolsAgentHost::GetOrCreateFor(web_contents_.get())); GetDevToolsWebContents()->GetController().LoadURL( GetDevToolsURL(can_dock_), content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } void InspectableWebContents::CloseDevTools() { if (GetDevToolsWebContents()) { frontend_loaded_ = false; if (managed_devtools_web_contents_) { view_->CloseDevTools(); managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); if (!IsGuest()) web_contents_->Focus(); } } bool InspectableWebContents::IsDevToolsViewShowing() { return managed_devtools_web_contents_ && view_->IsDevToolsViewShowing(); } void InspectableWebContents::AttachTo( scoped_refptr<content::DevToolsAgentHost> host) { Detach(); agent_host_ = std::move(host); // We could use ForceAttachClient here if problem arises with // devtools multiple session support. agent_host_->AttachClient(this); } void InspectableWebContents::Detach() { if (agent_host_) agent_host_->DetachClient(this); agent_host_ = nullptr; } void InspectableWebContents::Reattach(DispatchCallback callback) { if (agent_host_) { agent_host_->DetachClient(this); agent_host_->AttachClient(this); } std::move(callback).Run(nullptr); } void InspectableWebContents::CallClientFunction( const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { if (!GetDevToolsWebContents()) return; std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript), base::NullCallback()); } gfx::Rect InspectableWebContents::GetDevToolsBounds() const { return devtools_bounds_; } void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, RectToDictionary(bounds)); devtools_bounds_ = bounds; } double InspectableWebContents::GetDevToolsZoomLevel() const { return pref_service_->GetDouble(kDevToolsZoomPref); } void InspectableWebContents::UpdateDevToolsZoomLevel(double level) { pref_service_->SetDouble(kDevToolsZoomPref, level); } void InspectableWebContents::ActivateWindow() { // Set the zoom level. SetZoomLevelForWebContents(GetDevToolsWebContents(), GetDevToolsZoomLevel()); } void InspectableWebContents::CloseWindow() { GetDevToolsWebContents()->DispatchBeforeUnload(false /* auto_cancel */); } void InspectableWebContents::LoadCompleted() { frontend_loaded_ = true; if (managed_devtools_web_contents_) view_->ShowDevTools(activate_); // If the devtools can dock, "SetIsDocked" will be called by devtools itself. if (!can_dock_) { SetIsDocked(DispatchCallback(), false); } else { if (dock_state_.empty()) { const base::Value* prefs = pref_service_->GetDictionary(kDevToolsPreferences); const std::string* current_dock_state = prefs->FindStringKey("currentDockState"); base::RemoveChars(*current_dock_state, "\"", &dock_state_); } std::u16string javascript = base::UTF8ToUTF16( "UI.DockController.instance().setDockSide(\"" + dock_state_ + "\");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) AddDevToolsExtensionsToClient(); #endif if (view_->GetDelegate()) view_->GetDelegate()->DevToolsOpened(); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void InspectableWebContents::AddDevToolsExtensionsToClient() { // get main browser context auto* browser_context = web_contents_->GetBrowserContext(); const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); if (!registry) return; base::ListValue results; for (auto& extension : registry->enabled_extensions()) { auto devtools_page_url = extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()); if (devtools_page_url.is_empty()) continue; // Each devtools extension will need to be able to run in the devtools // process. Grant the devtools process the ability to request URLs from the // extension. content::ChildProcessSecurityPolicy::GetInstance()->GrantRequestOrigin( web_contents_->GetMainFrame()->GetProcess()->GetID(), url::Origin::Create(extension->url())); auto extension_info = std::make_unique<base::DictionaryValue>(); extension_info->SetString("startPage", devtools_page_url.spec()); extension_info->SetString("name", extension->name()); extension_info->SetBoolean( "exposeExperimentalAPIs", extension->permissions_data()->HasAPIPermission( extensions::mojom::APIPermissionID::kExperimental)); results.Append(std::move(extension_info)); } CallClientFunction("DevToolsAPI.addExtensions", &results, NULL, NULL); } #endif void InspectableWebContents::SetInspectedPageBounds(const gfx::Rect& rect) { DevToolsContentsResizingStrategy strategy(rect); if (contents_resizing_strategy_.Equals(strategy)) return; contents_resizing_strategy_.CopyFrom(strategy); if (managed_devtools_web_contents_) view_->SetContentsResizingStrategy(contents_resizing_strategy_); } void InspectableWebContents::InspectElementCompleted() {} void InspectableWebContents::InspectedURLChanged(const std::string& url) { if (managed_devtools_web_contents_) view_->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); } void InspectableWebContents::LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", net::HTTP_NOT_FOUND); std::move(callback).Run(&response); return; } // Create traffic annotation tag. net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("devtools_network_resource", R"( semantics { sender: "Developer Tools" description: "When user opens Developer Tools, the browser may fetch additional " "resources from the network to enrich the debugging experience " "(e.g. source map resources)." trigger: "User opens Developer Tools to debug a web page." data: "Any resources requested by Developer Tools." destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "It's not possible to disable this feature from settings." })"); network::ResourceRequest resource_request; resource_request.url = gurl; resource_request.site_for_cookies = net::SiteForCookies::FromUrl(gurl); resource_request.headers.AddHeadersFromString(headers); auto* protocol_registry = ProtocolRegistry::FromBrowserContext( GetDevToolsWebContents()->GetBrowserContext()); NetworkResourceLoader::URLLoaderFactoryHolder url_loader_factory; if (gurl.SchemeIsFile()) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = AsarURLLoaderFactory::Create(); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else if (protocol_registry->IsProtocolRegistered(gurl.scheme())) { auto& protocol_handler = protocol_registry->handlers().at(gurl.scheme()); mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote = ElectronURLLoaderFactory::Create(protocol_handler.first, protocol_handler.second); url_loader_factory = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_remote))); } else { auto* partition = GetDevToolsWebContents() ->GetBrowserContext() ->GetDefaultStoragePartition(); url_loader_factory = partition->GetURLLoaderFactoryForBrowserProcess(); } NetworkResourceLoader::Create( stream_id, this, resource_request, traffic_annotation, std::move(url_loader_factory), std::move(callback)); } void InspectableWebContents::SetIsDocked(DispatchCallback callback, bool docked) { if (managed_devtools_web_contents_) view_->SetIsDocked(docked, activate_); if (!callback.is_null()) std::move(callback).Run(nullptr); } void InspectableWebContents::OpenInNewTab(const std::string& url) {} void InspectableWebContents::ShowItemInFolder( const std::string& file_system_path) { if (file_system_path.empty()) return; base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path); platform_util::OpenPath(path.DirName(), base::BindOnce(&OnOpenItemComplete, path)); } void InspectableWebContents::SaveToFile(const std::string& url, const std::string& content, bool save_as) { if (delegate_) delegate_->DevToolsSaveToFile(url, content, save_as); } void InspectableWebContents::AppendToFile(const std::string& url, const std::string& content) { if (delegate_) delegate_->DevToolsAppendToFile(url, content); } void InspectableWebContents::RequestFileSystems() { if (delegate_) delegate_->DevToolsRequestFileSystems(); } void InspectableWebContents::AddFileSystem(const std::string& type) { if (delegate_) delegate_->DevToolsAddFileSystem(type, base::FilePath()); } void InspectableWebContents::RemoveFileSystem( const std::string& file_system_path) { if (delegate_) delegate_->DevToolsRemoveFileSystem( base::FilePath::FromUTF8Unsafe(file_system_path)); } void InspectableWebContents::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) {} void InspectableWebContents::IndexPath(int request_id, const std::string& file_system_path, const std::string& excluded_folders) { if (delegate_) delegate_->DevToolsIndexPath(request_id, file_system_path, excluded_folders); } void InspectableWebContents::StopIndexing(int request_id) { if (delegate_) delegate_->DevToolsStopIndexing(request_id); } void InspectableWebContents::SearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (delegate_) delegate_->DevToolsSearchInPath(request_id, file_system_path, query); } void InspectableWebContents::SetWhitelistedShortcuts( const std::string& message) {} void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } void InspectableWebContents::ShowCertificateViewer( const std::string& cert_chain) {} void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ZoomOut() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), true); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); UpdateDevToolsZoomLevel(new_level); } void InspectableWebContents::ResetZoom() { SetZoomLevelForWebContents(GetDevToolsWebContents(), 0.); UpdateDevToolsZoomLevel(0.); } void InspectableWebContents::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) {} void InspectableWebContents::SetDevicesUpdatesEnabled(bool enabled) {} void InspectableWebContents::PerformActionOnRemotePage( const std::string& page_id, const std::string& action) {} void InspectableWebContents::OpenRemotePage(const std::string& browser_id, const std::string& url) {} void InspectableWebContents::OpenNodeFrontend() {} void InspectableWebContents::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { // If the devtools wants to reload the page, hijack the message and handle it // to the delegate. if (base::MatchPattern(message, "{\"id\":*," "\"method\":\"Page.reload\"," "\"params\":*}")) { if (delegate_) delegate_->DevToolsReloadPage(); return; } if (agent_host_) agent_host_->DispatchProtocolMessage( this, base::as_bytes(base::make_span(message))); } void InspectableWebContents::SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) { std::move(callback).Run(nullptr); } void InspectableWebContents::RegisterPreference( const std::string& name, const RegisterOptions& options) { // kSyncDevToolsPreferenceFrontendName is not stored in any of the relevant // dictionaries. Skip registration. if (name == kSyncDevToolsPreferencesFrontendName) return; if (options.sync_mode == RegisterOptions::SyncMode::kSync) { synced_setting_names_.insert(name); } // Setting might have had a different sync status in the past. Move the // setting to the correct dictionary. const char* dictionary_to_remove_from = options.sync_mode == RegisterOptions::SyncMode::kSync ? kDevToolsPreferences : GetDictionaryNameForSyncedPrefs(); const std::string* settings_value = pref_service_->GetDictionary(dictionary_to_remove_from) ->FindStringKey(name); if (!settings_value) { return; } const char* dictionary_to_insert_into = GetDictionaryNameForSettingsName(name); // Settings already moved to the synced dictionary on a different device have // precedence. const std::string* already_synced_value = pref_service_->GetDictionary(dictionary_to_insert_into) ->FindStringKey(name); if (dictionary_to_insert_into == kDevToolsPreferences || !already_synced_value) { DictionaryPrefUpdate insert_update(pref_service_, dictionary_to_insert_into); insert_update.Get()->SetKey(name, base::Value(*settings_value)); } DictionaryPrefUpdate remove_update(pref_service_, dictionary_to_remove_from); remove_update.Get()->RemoveKey(name); } void InspectableWebContents::GetPreferences(DispatchCallback callback) { base::Value settings(base::Value::Type::DICTIONARY); settings.SetBoolKey(kSyncDevToolsPreferencesFrontendName, pref_service_->GetBoolean(kDevToolsSyncPreferences)); settings.MergeDictionary(pref_service_->GetDictionary(kDevToolsPreferences)); settings.MergeDictionary( pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs())); std::move(callback).Run(&settings); } void InspectableWebContents::GetPreference(DispatchCallback callback, const std::string& name) { // Handle kSyncDevToolsPreferencesFrontendName if (name == kSyncDevToolsPreferencesFrontendName) { base::Value pref = base::Value(pref_service_->GetBoolean(kDevToolsSyncPreferences)); std::move(callback).Run(&pref); return; } // Check dev tools prefs if (auto* pref = pref_service_->GetDictionary(kDevToolsPreferences)->FindKey(name)) { std::move(callback).Run(pref); return; } // Check synced prefs if (auto* pref = pref_service_->GetDictionary(GetDictionaryNameForSyncedPrefs()) ->FindKey(name)) { std::move(callback).Run(pref); return; } // Pref wasn't found, return an empty value base::Value no_pref; std::move(callback).Run(&no_pref); } void InspectableWebContents::SetPreference(const std::string& name, const std::string& value) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, value == "true"); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->SetKey(name, base::Value(value)); } void InspectableWebContents::RemovePreference(const std::string& name) { if (name == kSyncDevToolsPreferencesFrontendName) { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); return; } DictionaryPrefUpdate update(pref_service_, GetDictionaryNameForSettingsName(name)); update.Get()->RemoveKey(name); } void InspectableWebContents::ClearPreferences() { pref_service_->SetBoolean(kDevToolsSyncPreferences, kSyncDevToolsPreferencesDefault); DictionaryPrefUpdate unsynced_update(pref_service_, kDevToolsPreferences); unsynced_update.Get()->DictClear(); DictionaryPrefUpdate sync_enabled_update( pref_service_, kDevToolsSyncedPreferencesSyncEnabled); sync_enabled_update.Get()->DictClear(); DictionaryPrefUpdate sync_disabled_update( pref_service_, kDevToolsSyncedPreferencesSyncDisabled); sync_disabled_update.Get()->DictClear(); } void InspectableWebContents::GetSyncInformation(DispatchCallback callback) { // TODO(anyone): do we want devtool syncing in Electron? base::Value result(base::Value::Type::DICTIONARY); result.SetBoolKey("isSyncActive", false); std::move(callback).Run(&result); } void InspectableWebContents::ConnectionReady() {} void InspectableWebContents::RegisterExtensionsAPI(const std::string& origin, const std::string& script) { extensions_api_[origin + "/"] = script; } void InspectableWebContents::HandleMessageFromDevToolsFrontend( base::Value message) { // TODO(alexeykuzmin): Should we expect it to exist? if (!embedder_message_dispatcher_) { return; } const std::string* method = nullptr; base::Value* params = nullptr; if (message.is_dict()) { method = message.FindStringKey(kFrontendHostMethod); params = message.FindKey(kFrontendHostParams); } if (!method || (params && !params->is_list())) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } base::Value empty_params(base::Value::Type::LIST); if (!params) { params = &empty_params; } int id = message.FindIntKey(kFrontendHostId).value_or(0); std::vector<base::Value> params_list; if (params) params_list = std::move(*params).TakeListDeprecated(); embedder_message_dispatcher_->Dispatch( base::BindRepeating(&InspectableWebContents::SendMessageAck, weak_factory_.GetWeakPtr(), id), *method, params_list); } void InspectableWebContents::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) { if (!frontend_loaded_) return; base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), message.size()); if (str_message.size() < kMaxMessageChunkSize) { std::string param; base::EscapeJSONString(str_message, true, &param); std::u16string javascript = base::UTF8ToUTF16("DevToolsAPI.dispatchMessage(" + param + ");"); GetDevToolsWebContents()->GetMainFrame()->ExecuteJavaScript( javascript, base::NullCallback()); return; } base::Value total_size(static_cast<int>(str_message.length())); for (size_t pos = 0; pos < str_message.length(); pos += kMaxMessageChunkSize) { base::Value message_value(str_message.substr(pos, kMaxMessageChunkSize)); CallClientFunction("DevToolsAPI.dispatchMessageChunk", &message_value, pos ? nullptr : &total_size, nullptr); } } void InspectableWebContents::AgentHostClosed( content::DevToolsAgentHost* agent_host) {} void InspectableWebContents::RenderFrameHostChanged( content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) { if (new_host->GetParent()) return; frontend_host_ = content::DevToolsFrontendHost::Create( new_host, base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, weak_factory_.GetWeakPtr())); } void InspectableWebContents::WebContentsDestroyed() { if (managed_devtools_web_contents_) managed_devtools_web_contents_->SetDelegate(nullptr); frontend_loaded_ = false; external_devtools_web_contents_ = nullptr; Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); } bool InspectableWebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { auto* delegate = web_contents_->GetDelegate(); return !delegate || delegate->HandleKeyboardEvent(source, event); } void InspectableWebContents::CloseContents(content::WebContents* source) { // This is where the devtools closes itself (by clicking the x button). CloseDevTools(); } void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->RunFileChooser(render_frame_host, std::move(listener), params); } void InspectableWebContents::EnumerateDirectory( content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { auto* delegate = web_contents_->GetDelegate(); if (delegate) delegate->EnumerateDirectory(source, std::move(listener), path); } void InspectableWebContents::OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) { #if defined(TOOLKIT_VIEWS) if (view_->GetDelegate()) view_->GetDelegate()->DevToolsFocused(); #endif } void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetMainFrame() && frontend_host_) { return; } frontend_host_ = content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::BindRepeating( &InspectableWebContents::HandleMessageFromDevToolsFrontend, base::Unretained(this))); return; } } void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (navigation_handle->IsInMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; content::RenderFrameHost* frame = navigation_handle->GetRenderFrameHost(); auto origin = navigation_handle->GetURL().DeprecatedGetOriginAsURL().spec(); auto it = extensions_api_.find(origin); if (it == extensions_api_.end()) return; // Injected Script from devtools frontend doesn't expose chrome, // most likely bug in chromium. base::ReplaceFirstSubstringAfterOffset(&it->second, 0, "var chrome", "var chrome = window.chrome "); auto script = base::StringPrintf("%s(\"%s\")", it->second.c_str(), base::GenerateGUID().c_str()); // Invoking content::DevToolsFrontendHost::SetupExtensionsAPI(frame, script); // should be enough, but it seems to be a noop currently. frame->ExecuteJavaScriptForTests(base::UTF8ToUTF16(script), base::NullCallback()); } void InspectableWebContents::SendMessageAck(int request_id, const base::Value* arg) { base::Value id_value(request_id); CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr); } const char* InspectableWebContents::GetDictionaryNameForSettingsName( const std::string& name) const { return synced_setting_names_.contains(name) ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsPreferences; } const char* InspectableWebContents::GetDictionaryNameForSyncedPrefs() const { const bool isDevToolsSyncEnabled = pref_service_->GetBoolean(kDevToolsSyncPreferences); return isDevToolsSyncEnabled ? kDevToolsSyncedPreferencesSyncEnabled : kDevToolsSyncedPreferencesSyncDisabled; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
31,864
[Bug]: Dark mode in Devtools is not working on the latest 16.0.0 - 16.0.8 / 17.0.0
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.0 - 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 7 x64 SP1 ### What arch are you using? x64 ### Last Known Working Electron version 15.3.4 ### Expected Behavior Devtools should have a dark mode applied when the settings is set to 'Dark Mode'. ### Actual Behavior When switching to dark mode, it displays the message that 'Devtools requires a reload' but when I click on the reload button it does nothing. Restarting the app has no effect as well and stays on the light mode. This worked fine on the previous 15.3.2 version. ### Testcase Gist URL _No response_ ### Additional Information One thing I noticed, when updating from the last version (15.3.2) the dev tools will show up with dark mode enabled on the first run but on subsequent runs, it reverts back to light mode.
https://github.com/electron/electron/issues/31864
https://github.com/electron/electron/pull/33120
27527fe5ca790dc7061c6e816cc8b6ff72fe56d0
373a9053199f8881cdec7d44b8f3524d68ae8223
2021-11-16T17:32:36Z
c++
2022-03-09T01:17:43Z
shell/browser/ui/inspectable_web_contents.h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_ #include <list> #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/containers/span.h" #include "base/containers/unique_ptr_adapters.h" #include "base/memory/weak_ptr.h" #include "chrome/browser/devtools/devtools_contents_resizing_strategy.h" #include "chrome/browser/devtools/devtools_embedder_message_dispatcher.h" #include "chrome/browser/devtools/devtools_settings.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_contents_observer.h" #include "electron/buildflags/buildflags.h" #include "ui/gfx/geometry/rect.h" class PrefService; class PrefRegistrySimple; struct RegisterOptions; namespace electron { class InspectableWebContentsDelegate; class InspectableWebContentsView; class InspectableWebContents : public content::DevToolsAgentHostClient, public content::WebContentsObserver, public content::WebContentsDelegate, public DevToolsEmbedderMessageDispatcher::Delegate { public: using List = std::list<InspectableWebContents*>; static const List& GetAll(); static void RegisterPrefs(PrefRegistrySimple* pref_registry); InspectableWebContents(std::unique_ptr<content::WebContents> web_contents, PrefService* pref_service, bool is_guest); ~InspectableWebContents() override; // disable copy InspectableWebContents(const InspectableWebContents&) = delete; InspectableWebContents& operator=(const InspectableWebContents&) = delete; InspectableWebContentsView* GetView() const; content::WebContents* GetWebContents() const; content::WebContents* GetDevToolsWebContents() const; void SetDelegate(InspectableWebContentsDelegate* delegate); InspectableWebContentsDelegate* GetDelegate() const; bool IsGuest() const; void ReleaseWebContents(); void SetDevToolsWebContents(content::WebContents* devtools); void SetDockState(const std::string& state); void ShowDevTools(bool activate); void CloseDevTools(); bool IsDevToolsViewShowing(); void AttachTo(scoped_refptr<content::DevToolsAgentHost>); void Detach(); void CallClientFunction(const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3); void InspectElement(int x, int y); // Return the last position and size of devtools window. gfx::Rect GetDevToolsBounds() const; void SaveDevToolsBounds(const gfx::Rect& bounds); // Return the last set zoom level of devtools window. double GetDevToolsZoomLevel() const; void UpdateDevToolsZoomLevel(double level); private: // DevToolsEmbedderMessageDispacher::Delegate void ActivateWindow() override; void CloseWindow() override; void LoadCompleted() override; void SetInspectedPageBounds(const gfx::Rect& rect) override; void InspectElementCompleted() override; void InspectedURLChanged(const std::string& url) override; void LoadNetworkResource(DispatchCallback callback, const std::string& url, const std::string& headers, int stream_id) override; void SetIsDocked(DispatchCallback callback, bool is_docked) override; void OpenInNewTab(const std::string& url) override; void ShowItemInFolder(const std::string& file_system_path) override; void SaveToFile(const std::string& url, const std::string& content, bool save_as) override; void AppendToFile(const std::string& url, const std::string& content) override; void RequestFileSystems() override; void AddFileSystem(const std::string& type) override; void RemoveFileSystem(const std::string& file_system_path) override; void UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) override; void IndexPath(int index_request_id, const std::string& file_system_path, const std::string& excluded_folders) override; void StopIndexing(int index_request_id) override; void SearchInPath(int search_request_id, const std::string& file_system_path, const std::string& query) override; void SetWhitelistedShortcuts(const std::string& message) override; void SetEyeDropperActive(bool active) override; void ShowCertificateViewer(const std::string& cert_chain) override; void ZoomIn() override; void ZoomOut() override; void ResetZoom() override; void SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config, bool network_discovery_enabled, const std::string& network_discovery_config) override; void SetDevicesUpdatesEnabled(bool enabled) override; void PerformActionOnRemotePage(const std::string& page_id, const std::string& action) override; void OpenRemotePage(const std::string& browser_id, const std::string& url) override; void OpenNodeFrontend() override; void DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) override; void SendJsonRequest(DispatchCallback callback, const std::string& browser_id, const std::string& url) override; void RegisterPreference(const std::string& name, const RegisterOptions& options) override; void GetPreferences(DispatchCallback callback) override; void GetPreference(DispatchCallback callback, const std::string& name) override; void SetPreference(const std::string& name, const std::string& value) override; void RemovePreference(const std::string& name) override; void ClearPreferences() override; void GetSyncInformation(DispatchCallback callback) override; void ConnectionReady() override; void RegisterExtensionsAPI(const std::string& origin, const std::string& script) override; void Reattach(DispatchCallback callback) override; void RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) override {} void ReadyForTest() override {} void SetOpenNewWindowForPopups(bool value) override {} void RecordPerformanceHistogram(const std::string& name, double duration) override {} void RecordUserMetricsAction(const std::string& name) override {} void ShowSurvey(DispatchCallback callback, const std::string& trigger) override {} void CanShowSurvey(DispatchCallback callback, const std::string& trigger) override {} // content::DevToolsFrontendHostDelegate: void HandleMessageFromDevToolsFrontend(base::Value message); // content::DevToolsAgentHostClient: void DispatchProtocolMessage(content::DevToolsAgentHost* agent_host, base::span<const uint8_t> message) override; void AgentHostClosed(content::DevToolsAgentHost* agent_host) override; // content::WebContentsObserver: void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host) override; void WebContentsDestroyed() override; void OnWebContentsFocused( content::RenderWidgetHost* render_widget_host) override; void ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) override; void DidFinishNavigation( content::NavigationHandle* navigation_handle) override; // content::WebContentsDelegate: bool HandleKeyboardEvent(content::WebContents*, const content::NativeWebKeyboardEvent&) override; void CloseContents(content::WebContents* source) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override; void EnumerateDirectory(content::WebContents* source, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) override; void SendMessageAck(int request_id, const base::Value* arg1); const char* GetDictionaryNameForSettingsName(const std::string& name) const; const char* GetDictionaryNameForSyncedPrefs() const; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void AddDevToolsExtensionsToClient(); #endif DevToolsContentsResizingStrategy contents_resizing_strategy_; gfx::Rect devtools_bounds_; bool can_dock_ = true; std::string dock_state_; bool activate_ = true; InspectableWebContentsDelegate* delegate_ = nullptr; // weak references. PrefService* pref_service_; // weak reference. std::unique_ptr<content::WebContents> web_contents_; // The default devtools created by this class when we don't have an external // one assigned by SetDevToolsWebContents. std::unique_ptr<content::WebContents> managed_devtools_web_contents_; // The external devtools assigned by SetDevToolsWebContents. content::WebContents* external_devtools_web_contents_ = nullptr; bool is_guest_; std::unique_ptr<InspectableWebContentsView> view_; bool frontend_loaded_ = false; scoped_refptr<content::DevToolsAgentHost> agent_host_; std::unique_ptr<content::DevToolsFrontendHost> frontend_host_; std::unique_ptr<DevToolsEmbedderMessageDispatcher> embedder_message_dispatcher_; class NetworkResourceLoader; std::set<std::unique_ptr<NetworkResourceLoader>, base::UniquePtrComparator> loaders_; using ExtensionsAPIs = std::map<std::string, std::string>; ExtensionsAPIs extensions_api_; // Contains the set of synced settings. // The DevTools frontend *must* call `Register` for each setting prior to // use, which guarantees that this set must not be persisted. base::flat_set<std::string> synced_setting_names_; base::WeakPtrFactory<InspectableWebContents> weak_factory_{this}; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_H_
closed
electron/electron
https://github.com/electron/electron
15,448
Support Chromium's command-line switch --unsafely-treat-insecure-origin-as-secure
**Is your feature request related to a problem? Please describe.** Notifications, Geolocation, Device motion/orientation, EME, getUserMedia, AppCache require a secure origin to work in Chromium. HTTP URLs are not considered secure. That's why Chromium provides the command-line switch `--unsafely-treat-insecure-origin-as-secure="$url"` to circumvent this problem. Unfortunately it's not working in Electron. **Describe the solution you'd like** Please make it work. In the renderer. I'd suggest simply like ``` new BrowserWindow({ webPreferences: { additionalArguments: { '--unsafely-treat-insecure-origin-as-secure', 'http://insecure-origin' } } ``` Or a new option `considerSecure: String[]` to `BrowserWindow.webPreferences`. I guess it should be not too hard to implement since Chromium already supports it and it seems to get lost only in the process of Electron integration. **Describe alternatives you've considered** - `app.commandLine.appendSwitch('unsafely-treat-insecure-origin-as-secure', $url)` in the main thread - Invisible [BrowserWindow](https://github.com/electron/electron/blob/master/docs/api/browser-window.md) with secure origin + IPC - `<iframe>` on a secure origin - localhost-Proxy - Using Data URLs in [loadURL](https://github.com/electron/electron/blob/master/docs/api/browser-window.md#winloadurlurl-options): `data:text/html,<script>new Notification("hi")</script>` - webFrame.registerURLSchemeAsPrivileged **Additional context** 'Deprecating Powerful Features on Insecure Origins' https://goo.gl/rStTGz When the flag is set in Chromium a message appears under the address bar, saying that 'You are using an unsupported command-line flag'. ![image](https://user-images.githubusercontent.com/23075755/47640947-1c6ebf80-db65-11e8-9e6e-d7a5bd90c208.png) Nonetheless the features are then working on the origin treated securely.
https://github.com/electron/electron/issues/15448
https://github.com/electron/electron/pull/33189
865a29ed17d498335790c2c6998578e1e76c5513
ebfcf89a0b554804fc8707215752a1130dc10182
2018-10-29T09:42:35Z
c++
2022-03-09T15:15:50Z
shell/browser/electron_browser_client.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_client.h" #if BUILDFLAG(IS_WIN) #include <shlobj.h> #endif #include <memory> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/crash_logging.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/lazy_instance.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version.h" #include "components/net_log/chrome_net_log.h" #include "components/network_hints/common/network_hints.mojom.h" #include "content/browser/keyboard_lock/keyboard_lock_service_impl.h" // nogncheck #include "content/browser/site_instance_impl.h" // nogncheck #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/login_delegate.h" #include "content/public/browser/overlay_window.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/service_worker_version_base_info.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/tts_controller.h" #include "content/public/browser/tts_platform.h" #include "content/public/common/content_descriptors.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "crypto/crypto_buildflags.h" #include "electron/buildflags/buildflags.h" #include "electron/grit/electron_resources.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/api/messaging/messaging_api_message_filter.h" #include "mojo/public/cpp/bindings/binder_map.h" #include "net/base/escape.h" #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/buildflags/buildflags.h" #include "ppapi/host/ppapi_host.h" #include "printing/buildflags/buildflags.h" #include "services/device/public/cpp/geolocation/location_provider.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/resource_request_body.h" #include "services/network/public/cpp/self_deleting_url_loader_factory.h" #include "shell/app/electron_crash_reporter_client.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_crash_reporter.h" #include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/api/electron_api_web_request.h" #include "shell/browser/badging/badge_manager.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_handler_impl.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/electron_quota_permission_context.h" #include "shell/browser/electron_speech_recognition_manager_delegate.h" #include "shell/browser/font_defaults.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/native_window.h" #include "shell/browser/net/network_context_service.h" #include "shell/browser/net/network_context_service_factory.h" #include "shell/browser/net/proxying_url_loader_factory.h" #include "shell/browser/net/proxying_websocket.h" #include "shell/browser/net/system_network_context_manager.h" #include "shell/browser/network_hints_handler_impl.h" #include "shell/browser/notifications/notification_presenter.h" #include "shell/browser/notifications/platform_notification_service.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/window_list.h" #include "shell/common/api/api.mojom.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/logging.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/mojom/badging/badging.mojom.h" #include "ui/base/resource/resource_bundle.h" #include "ui/native_theme/native_theme.h" #include "v8/include/v8.h" #if BUILDFLAG(IS_WIN) #include "sandbox/win/src/sandbox_policy.h" #endif #if BUILDFLAG(USE_NSS_CERTS) #include "net/ssl/client_cert_store_nss.h" #elif BUILDFLAG(IS_WIN) #include "net/ssl/client_cert_store_win.h" #elif BUILDFLAG(IS_MAC) #include "net/ssl/client_cert_store_mac.h" #elif defined(USE_OPENSSL) #include "net/ssl/client_cert_store.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" // nogncheck #include "components/spellcheck/common/spellcheck.mojom.h" // nogncheck #endif #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #include "shell/browser/fake_location_provider.h" #endif // BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/webui_url_constants.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/web_ui_url_loader_factory.h" #include "extensions/browser/api/mime_handler_private/mime_handler_private.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_message_filter.h" #include "extensions/browser/extension_navigation_throttle.h" #include "extensions/browser/extension_navigation_ui_data.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_protocols.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/guest_view/extensions_guest_view.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" #include "extensions/browser/info_map.h" #include "extensions/browser/process_manager.h" #include "extensions/browser/process_map.h" #include "extensions/browser/url_loader_factory_manager.h" #include "extensions/common/api/mime_handler.mojom.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/switches.h" #include "shell/browser/extensions/electron_extension_message_filter.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h" // nogncheck #include "shell/browser/plugins/plugin_utils.h" #endif #if BUILDFLAG(IS_MAC) #include "content/common/mac_helpers.h" #include "content/public/common/child_process_host.h" #endif #if BUILDFLAG(IS_LINUX) && !defined(MAS_BUILD) #include "base/debug/leak_annotations.h" #include "components/crash/content/browser/crash_handler_host_linux.h" #include "components/crash/core/app/breakpad_linux.h" // nogncheck #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) && BUILDFLAG(IS_WIN) #include "chrome/browser/ui/views/overlay/document_overlay_window_views.h" #include "chrome/browser/ui/views/overlay/video_overlay_window_views.h" #include "shell/browser/browser.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/win/shell.h" #include "ui/views/widget/widget.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #endif using content::BrowserThread; namespace electron { namespace { ElectronBrowserClient* g_browser_client = nullptr; base::LazyInstance<std::string>::DestructorAtExit g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER; base::NoDestructor<std::string> g_application_locale; void SetApplicationLocaleOnIOThread(const std::string& locale) { DCHECK_CURRENTLY_ON(BrowserThread::IO); g_io_thread_application_locale.Get() = locale; } void BindNetworkHintsHandler( content::RenderFrameHost* frame_host, mojo::PendingReceiver<network_hints::mojom::NetworkHintsHandler> receiver) { NetworkHintsHandlerImpl::Create(frame_host, std::move(receiver)); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions // below. Extension, and isolated apps require different privileges to be // granted to their RenderProcessHosts. This classification allows us to make // sure URLs are served by hosts with the right set of privileges. enum class RenderProcessHostPrivilege { kNormal, kHosted, kIsolated, kExtension, }; // Copied from chrome/browser/extensions/extension_util.cc. bool AllowFileAccess(const std::string& extension_id, content::BrowserContext* context) { return base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kDisableExtensionsFileAccessCheck) || extensions::ExtensionPrefs::Get(context)->AllowFileAccess( extension_id); } RenderProcessHostPrivilege GetPrivilegeRequiredByUrl( const GURL& url, extensions::ExtensionRegistry* registry) { // Default to a normal renderer cause it is lower privileged. This should only // occur if the URL on a site instance is either malformed, or uninitialized. // If it is malformed, then there is no need for better privileges anyways. // If it is uninitialized, but eventually settles on being an a scheme other // than normal webrenderer, the navigation logic will correct us out of band // anyways. if (!url.is_valid()) return RenderProcessHostPrivilege::kNormal; if (!url.SchemeIs(extensions::kExtensionScheme)) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } RenderProcessHostPrivilege GetProcessPrivilege( content::RenderProcessHost* process_host, extensions::ProcessMap* process_map, extensions::ExtensionRegistry* registry) { std::set<std::string> extension_ids = process_map->GetExtensionsInProcess(process_host->GetID()); if (extension_ids.empty()) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } const extensions::Extension* GetEnabledExtensionFromEffectiveURL( content::BrowserContext* context, const GURL& effective_url) { if (!effective_url.SchemeIs(extensions::kExtensionScheme)) return nullptr; extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(context); if (!registry) return nullptr; return registry->enabled_extensions().GetByID(effective_url.host()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(IS_LINUX) breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost( const std::string& process_type) { base::FilePath dumps_path; base::PathService::Get(electron::DIR_CRASH_DUMPS, &dumps_path); { ANNOTATE_SCOPED_MEMORY_LEAK; bool upload = ElectronCrashReporterClient::Get()->GetCollectStatsConsent(); breakpad::CrashHandlerHostLinux* crash_handler = new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload); crash_handler->StartUploaderThread(); return crash_handler; } } int GetCrashSignalFD(const base::CommandLine& command_line) { if (crash_reporter::IsCrashpadEnabled()) { int fd; pid_t pid; return crash_reporter::GetHandlerSocket(&fd, &pid) ? fd : -1; } // Extensions have the same process type as renderers. if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost("extension"); return crash_handler->GetDeathSignalSocket(); } std::string process_type = command_line.GetSwitchValueASCII(::switches::kProcessType); if (process_type == ::switches::kRendererProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == ::switches::kPpapiPluginProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == ::switches::kGpuProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == ::switches::kUtilityProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } return -1; } #endif // BUILDFLAG(IS_LINUX) } // namespace // static ElectronBrowserClient* ElectronBrowserClient::Get() { return g_browser_client; } // static void ElectronBrowserClient::SetApplicationLocale(const std::string& locale) { if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) || !base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) { g_io_thread_application_locale.Get() = locale; } *g_application_locale = locale; } ElectronBrowserClient::ElectronBrowserClient() { DCHECK(!g_browser_client); g_browser_client = this; } ElectronBrowserClient::~ElectronBrowserClient() { DCHECK(g_browser_client); g_browser_client = nullptr; } content::WebContents* ElectronBrowserClient::GetWebContentsFromProcessID( int process_id) { // If the process is a pending process, we should use the web contents // for the frame host passed into RegisterPendingProcess. const auto iter = pending_processes_.find(process_id); if (iter != std::end(pending_processes_)) return iter->second; // Certain render process will be created with no associated render view, // for example: ServiceWorker. return WebContentsPreferences::GetWebContentsFromProcessID(process_id); } content::SiteInstance* ElectronBrowserClient::GetSiteInstanceFromAffinity( content::BrowserContext* browser_context, const GURL& url, content::RenderFrameHost* rfh) const { return nullptr; } bool ElectronBrowserClient::IsRendererSubFrame(int process_id) const { return base::Contains(renderer_is_subframe_, process_id); } void ElectronBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { // When a render process is crashed, it might be reused. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) int process_id = host->GetID(); auto* browser_context = host->GetBrowserContext(); host->AddFilter( new extensions::ExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new ElectronExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new extensions::MessagingAPIMessageFilter(process_id, browser_context)); #endif // ensure the ProcessPreferences is removed later host->AddObserver(this); } content::SpeechRecognitionManagerDelegate* ElectronBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new ElectronSpeechRecognitionManagerDelegate; } content::TtsPlatform* ElectronBrowserClient::GetTtsPlatform() { return nullptr; } void ElectronBrowserClient::OverrideWebkitPrefs( content::WebContents* web_contents, blink::web_pref::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->allow_universal_access_from_file_urls = true; prefs->allow_file_access_from_file_urls = true; prefs->webgl1_enabled = true; prefs->webgl2_enabled = true; prefs->allow_running_insecure_content = false; prefs->default_minimum_page_scale_factor = 1.f; prefs->default_maximum_page_scale_factor = 1.f; prefs->navigate_on_drag_drop = false; #if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) prefs->picture_in_picture_enabled = false; #endif ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi(); prefs->preferred_color_scheme = native_theme->ShouldUseDarkColors() ? blink::mojom::PreferredColorScheme::kDark : blink::mojom::PreferredColorScheme::kLight; auto preloads = SessionPreferences::GetValidPreloads(web_contents->GetBrowserContext()); if (!preloads.empty()) prefs->preloads = preloads; SetFontDefaults(prefs); // Custom preferences of guest page. auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) { web_preferences->OverrideWebkitPrefs(prefs); } } void ElectronBrowserClient::RegisterPendingSiteInstance( content::RenderFrameHost* rfh, content::SiteInstance* pending_site_instance) { // Remember the original web contents for the pending renderer process. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* pending_process = pending_site_instance->GetProcess(); pending_processes_[pending_process->GetID()] = web_contents; if (rfh->GetParent()) renderer_is_subframe_.insert(pending_process->GetID()); else renderer_is_subframe_.erase(pending_process->GetID()); } void ElectronBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { // Make sure we're about to launch a known executable { base::ThreadRestrictions::ScopedAllowIO allow_io; base::FilePath child_path; base::FilePath program = base::MakeAbsoluteFilePath(command_line->GetProgram()); #if BUILDFLAG(IS_MAC) auto renderer_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_RENDERER); auto gpu_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_GPU); #if BUILDFLAG(ENABLE_PLUGINS) auto plugin_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_PLUGIN); #endif if (program != renderer_child_path && program != gpu_child_path #if BUILDFLAG(ENABLE_PLUGINS) && program != plugin_child_path #endif ) { child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_NORMAL); CHECK_EQ(program, child_path) << "Aborted from launching unexpected helper executable"; } #else if (!base::PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) { CHECK(false) << "Unable to get child process binary name."; } SCOPED_CRASH_KEY_STRING256("ChildProcess", "child_process_exe", child_path.AsUTF8Unsafe()); SCOPED_CRASH_KEY_STRING256("ChildProcess", "program", program.AsUTF8Unsafe()); CHECK_EQ(program, child_path); #endif } std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); #if BUILDFLAG(IS_LINUX) bool enable_crash_reporter = false; if (crash_reporter::IsCrashpadEnabled()) { command_line->AppendSwitch(::switches::kEnableCrashpad); enable_crash_reporter = true; int fd; pid_t pid; if (crash_reporter::GetHandlerSocket(&fd, &pid)) { command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, base::NumberToString(pid)); } } else { enable_crash_reporter = breakpad::IsCrashReporterEnabled(); } // Zygote Process gets booted before any JS runs, accessing GetClientId // will end up touching DIR_USER_DATA path provider and this will // configure default value because app.name from browser_init has // not run yet. if (enable_crash_reporter && process_type != ::switches::kZygoteProcess) { std::string switch_value = api::crash_reporter::GetClientId() + ",no_channel"; command_line->AppendSwitchASCII(::switches::kEnableCrashReporter, switch_value); if (!crash_reporter::IsCrashpadEnabled()) { for (const auto& pair : api::crash_reporter::GetGlobalCrashKeys()) { if (!switch_value.empty()) switch_value += ","; switch_value += pair.first; switch_value += "="; switch_value += pair.second; } command_line->AppendSwitchASCII(switches::kGlobalCrashKeys, switch_value); } } #endif // The zygote process is booted before JS runs, so DIR_USER_DATA isn't usable // at that time. It doesn't need --user-data-dir to be correct anyway, since // the zygote itself doesn't access anything in that directory. if (process_type != ::switches::kZygoteProcess) { base::FilePath user_data_dir; if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) command_line->AppendSwitchPath(::switches::kUserDataDir, user_data_dir); } if (process_type == ::switches::kUtilityProcess || process_type == ::switches::kRendererProcess) { // Copy following switches to child process. static const char* const kCommonSwitchNames[] = { switches::kStandardSchemes, switches::kEnableSandbox, switches::kSecureSchemes, switches::kBypassCSPSchemes, switches::kCORSSchemes, switches::kFetchSchemes, switches::kServiceWorkerSchemes, switches::kStreamingSchemes}; command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(), kCommonSwitchNames, base::size(kCommonSwitchNames)); } if (process_type == ::switches::kRendererProcess) { #if BUILDFLAG(IS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif if (delegate_) { auto app_path = static_cast<api::App*>(delegate_)->GetAppPath(); command_line->AppendSwitchPath(switches::kAppPath, app_path); } auto env = base::Environment::Create(); if (env->HasVar("ELECTRON_PROFILE_INIT_SCRIPTS")) { command_line->AppendSwitch("profile-electron-init"); } // Extension background pages don't have WebContentsPreferences, but they // support WebSQL by default. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) content::RenderProcessHost* process = content::RenderProcessHost::FromID(process_id); if (extensions::ProcessMap::Get(process->GetBrowserContext()) ->Contains(process_id)) command_line->AppendSwitch(switches::kEnableWebSQL); #endif content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); if (web_contents) { auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) web_preferences->AppendCommandLineSwitches( command_line, IsRendererSubFrame(process_id)); } } } void ElectronBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) {} // attempt to get api key from env std::string ElectronBrowserClient::GetGeolocationApiKey() { auto env = base::Environment::Create(); std::string api_key; env->GetVar("GOOGLE_API_KEY", &api_key); return api_key; } scoped_refptr<content::QuotaPermissionContext> ElectronBrowserClient::CreateQuotaPermissionContext() { return base::MakeRefCounted<ElectronQuotaPermissionContext>(); } content::GeneratedCodeCacheSettings ElectronBrowserClient::GetGeneratedCodeCacheSettings( content::BrowserContext* context) { // TODO(deepak1556): Use platform cache directory. base::FilePath cache_path = context->GetPath(); // If we pass 0 for size, disk_cache will pick a default size using the // heuristics based on available disk size. These are implemented in // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc. return content::GeneratedCodeCacheSettings(true, 0, cache_path); } void ElectronBrowserClient::AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool is_main_frame_request, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback) { if (delegate_) { delegate_->AllowCertificateError(web_contents, cert_error, ssl_info, request_url, is_main_frame_request, strict_enforcement, std::move(callback)); } } base::OnceClosure ElectronBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (!client_certs.empty() && delegate_) { delegate_->SelectClientCertificate(web_contents, cert_request_info, std::move(client_certs), std::move(delegate)); } return base::OnceClosure(); } bool ElectronBrowserClient::CanCreateWindow( content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const url::Origin& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, const std::string& raw_features, const scoped_refptr<network::ResourceRequestBody>& body, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(opener); WebContentsPreferences* prefs = WebContentsPreferences::From(web_contents); if (prefs) { if (prefs->ShouldDisablePopups()) { // <webview> without allowpopups attribute should return // null from window.open calls return false; } else { *no_javascript_access = false; return true; } } if (delegate_) { return delegate_->CanCreateWindow( opener, opener_url, opener_top_level_frame_url, source_origin, container_type, target_url, referrer, frame_name, disposition, features, raw_features, body, user_gesture, opener_suppressed, no_javascript_access); } return false; } #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) std::unique_ptr<content::VideoOverlayWindow> ElectronBrowserClient::CreateWindowForVideoPictureInPicture( content::VideoPictureInPictureWindowController* controller) { auto overlay_window = content::VideoOverlayWindow::Create(controller); #if BUILDFLAG(IS_WIN) std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID(); if (!app_user_model_id.empty()) { auto* overlay_window_view = static_cast<VideoOverlayWindowViews*>(overlay_window.get()); ui::win::SetAppIdForWindow(app_user_model_id, overlay_window_view->GetNativeWindow() ->GetHost() ->GetAcceleratedWidget()); } #endif return overlay_window; } std::unique_ptr<content::DocumentOverlayWindow> ElectronBrowserClient::CreateWindowForDocumentPictureInPicture( content::DocumentPictureInPictureWindowController* controller) { auto overlay_window = content::DocumentOverlayWindow::Create(controller); #if BUILDFLAG(IS_WIN) std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID(); if (!app_user_model_id.empty()) { auto* overlay_window_view = static_cast<DocumentOverlayWindowViews*>(overlay_window.get()); ui::win::SetAppIdForWindow(app_user_model_id, overlay_window_view->GetNativeWindow() ->GetHost() ->GetAcceleratedWidget()); } #endif return overlay_window; } #endif void ElectronBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { auto schemes_list = api::GetStandardSchemes(); if (!schemes_list.empty()) additional_schemes->insert(additional_schemes->end(), schemes_list.begin(), schemes_list.end()); additional_schemes->push_back(content::kChromeDevToolsScheme); additional_schemes->push_back(content::kChromeUIScheme); } void ElectronBrowserClient::GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) { additional_schemes->push_back(content::kChromeDevToolsScheme); } void ElectronBrowserClient::SiteInstanceGotProcess( content::SiteInstance* site_instance) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext()); if (!browser_context->IsOffTheRecord()) { extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); const extensions::Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL( site_instance->GetSiteURL()); if (!extension) return; extensions::ProcessMap::Get(browser_context) ->Insert(extension->id(), site_instance->GetProcess()->GetID(), site_instance->GetId()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) } bool ElectronBrowserClient::IsSuitableHost( content::RenderProcessHost* process_host, const GURL& site_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = process_host->GetBrowserContext(); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser_context); // Otherwise, just make sure the process privilege matches the privilege // required by the site. RenderProcessHostPrivilege privilege_required = GetPrivilegeRequiredByUrl(site_url, registry); return GetProcessPrivilege(process_host, process_map, registry) == privilege_required; #else return content::ContentBrowserClient::IsSuitableHost(process_host, site_url); #endif } bool ElectronBrowserClient::ShouldUseProcessPerSite( content::BrowserContext* browser_context, const GURL& effective_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const extensions::Extension* extension = GetEnabledExtensionFromEffectiveURL(browser_context, effective_url); return extension != nullptr; #else return content::ContentBrowserClient::ShouldUseProcessPerSite(browser_context, effective_url); #endif } bool ElectronBrowserClient::ArePersistentMediaDeviceIDsAllowed( content::BrowserContext* browser_context, const GURL& scope, const net::SiteForCookies& site_for_cookies, const absl::optional<url::Origin>& top_frame_origin) { return true; } base::FilePath ElectronBrowserClient::GetLoggingFileName( const base::CommandLine& cmd_line) { return logging::GetLogFileName(cmd_line); } void ElectronBrowserClient::SiteInstanceDeleting( content::SiteInstance* site_instance) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Don't do anything if we're shutting down. if (content::BrowserMainRunner::ExitedMainMessageLoop()) return; auto* browser_context = static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext()); if (!browser_context->IsOffTheRecord()) { // If this isn't an extension renderer there's nothing to do. extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); const extensions::Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL( site_instance->GetSiteURL()); if (!extension) return; extensions::ProcessMap::Get(browser_context) ->Remove(extension->id(), site_instance->GetProcess()->GetID(), site_instance->GetId()); } #endif } std::unique_ptr<net::ClientCertStore> ElectronBrowserClient::CreateClientCertStore( content::BrowserContext* browser_context) { #if BUILDFLAG(USE_NSS_CERTS) return std::make_unique<net::ClientCertStoreNSS>( net::ClientCertStoreNSS::PasswordDelegateFactory()); #elif BUILDFLAG(IS_WIN) return std::make_unique<net::ClientCertStoreWin>(); #elif BUILDFLAG(IS_MAC) return std::make_unique<net::ClientCertStoreMac>(); #elif defined(USE_OPENSSL) return std::unique_ptr<net::ClientCertStore>(); #endif } std::unique_ptr<device::LocationProvider> ElectronBrowserClient::OverrideSystemLocationProvider() { #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) return std::make_unique<FakeLocationProvider>(); #else return nullptr; #endif } void ElectronBrowserClient::ConfigureNetworkContextParams( content::BrowserContext* browser_context, bool in_memory, const base::FilePath& relative_partition_path, network::mojom::NetworkContextParams* network_context_params, cert_verifier::mojom::CertVerifierCreationParams* cert_verifier_creation_params) { DCHECK(browser_context); return NetworkContextServiceFactory::GetForContext(browser_context) ->ConfigureNetworkContextParams(network_context_params, cert_verifier_creation_params); } network::mojom::NetworkContext* ElectronBrowserClient::GetSystemNetworkContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(g_browser_process->system_network_context_manager()); return g_browser_process->system_network_context_manager()->GetContext(); } std::unique_ptr<content::BrowserMainParts> ElectronBrowserClient::CreateBrowserMainParts( content::MainFunctionParams params) { auto browser_main_parts = std::make_unique<ElectronBrowserMainParts>(std::move(params)); #if BUILDFLAG(IS_MAC) browser_main_parts_ = browser_main_parts.get(); #endif return browser_main_parts; } void ElectronBrowserClient::WebNotificationAllowed( content::RenderFrameHost* rfh, base::OnceCallback<void(bool, bool)> callback) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) { std::move(callback).Run(false, false); return; } auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { std::move(callback).Run(false, false); return; } permission_helper->RequestWebNotificationPermission( base::BindOnce(std::move(callback), web_contents->IsAudioMuted())); } void ElectronBrowserClient::RenderProcessHostDestroyed( content::RenderProcessHost* host) { int process_id = host->GetID(); pending_processes_.erase(process_id); renderer_is_subframe_.erase(process_id); host->RemoveObserver(this); } void ElectronBrowserClient::RenderProcessReady( content::RenderProcessHost* host) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessReady(host); } } void ElectronBrowserClient::RenderProcessExited( content::RenderProcessHost* host, const content::ChildProcessTerminationInfo& info) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessExited(host); } } void OnOpenExternal(const GURL& escaped_url, bool allowed) { if (allowed) { platform_util::OpenExternal( escaped_url, platform_util::OpenExternalOptions(), base::DoNothing()); } } void HandleExternalProtocolInUI( const GURL& url, content::WebContents::OnceGetter web_contents_getter, bool has_user_gesture) { content::WebContents* web_contents = std::move(web_contents_getter).Run(); if (!web_contents) return; auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) return; GURL escaped_url(net::EscapeExternalHandlerValue(url.spec())); auto callback = base::BindOnce(&OnOpenExternal, escaped_url); permission_helper->RequestOpenExternalPermission(std::move(callback), has_user_gesture, url); } bool ElectronBrowserClient::HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int child_id, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_main_frame, network::mojom::WebSandboxFlags sandbox_flags, ui::PageTransition page_transition, bool has_user_gesture, const absl::optional<url::Origin>& initiating_origin, content::RenderFrameHost* initiator_document, mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) { base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&HandleExternalProtocolInUI, url, std::move(web_contents_getter), has_user_gesture)); return true; } std::vector<std::unique_ptr<content::NavigationThrottle>> ElectronBrowserClient::CreateThrottlesForNavigation( content::NavigationHandle* handle) { std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; throttles.push_back(std::make_unique<ElectronNavigationThrottle>(handle)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) throttles.push_back( std::make_unique<extensions::ExtensionNavigationThrottle>(handle)); #endif return throttles; } content::MediaObserver* ElectronBrowserClient::GetMediaObserver() { return MediaCaptureDevicesDispatcher::GetInstance(); } std::unique_ptr<content::DevToolsManagerDelegate> ElectronBrowserClient::CreateDevToolsManagerDelegate() { return std::make_unique<DevToolsManagerDelegate>(); } NotificationPresenter* ElectronBrowserClient::GetNotificationPresenter() { if (!notification_presenter_) { notification_presenter_.reset(NotificationPresenter::Create()); } return notification_presenter_.get(); } content::PlatformNotificationService* ElectronBrowserClient::GetPlatformNotificationService() { if (!notification_service_) { notification_service_ = std::make_unique<PlatformNotificationService>(this); } return notification_service_.get(); } base::FilePath ElectronBrowserClient::GetDefaultDownloadDirectory() { base::FilePath download_path; if (base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_path)) return download_path; return base::FilePath(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserClient::GetSystemSharedURLLoaderFactory() { if (!g_browser_process) return nullptr; return g_browser_process->shared_url_loader_factory(); } void ElectronBrowserClient::OnNetworkServiceCreated( network::mojom::NetworkService* network_service) { if (!g_browser_process) return; g_browser_process->system_network_context_manager()->OnNetworkServiceCreated( network_service); } std::vector<base::FilePath> ElectronBrowserClient::GetNetworkContextsParentDirectory() { base::FilePath user_data_dir; base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); DCHECK(!user_data_dir.empty()); return {user_data_dir}; } std::string ElectronBrowserClient::GetProduct() { return "Chrome/" CHROME_VERSION_STRING; } std::string ElectronBrowserClient::GetUserAgent() { if (user_agent_override_.empty()) return GetApplicationUserAgent(); return user_agent_override_; } void ElectronBrowserClient::SetUserAgent(const std::string& user_agent) { user_agent_override_ = user_agent; } void ElectronBrowserClient::RegisterNonNetworkNavigationURLLoaderFactories( int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) { content::WebContents* web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); content::BrowserContext* context = web_contents->GetBrowserContext(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionNavigationURLLoaderFactory( context, ukm_source_id, false /* we don't support extensions::WebViewGuest */)); #endif // Always allow navigating to file:// URLs. auto* protocol_registry = ProtocolRegistry::FromBrowserContext(context); protocol_registry->RegisterURLLoaderFactories(factories, true /* allow_file_access */); } void ElectronBrowserClient:: RegisterNonNetworkWorkerMainResourceURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); // Workers are not allowed to request file:// URLs, there is no particular // reason for it, and we could consider supporting it in future. protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) namespace { // The FileURLLoaderFactory provided to the extension background pages. // Checks with the ChildProcessSecurityPolicy to validate the file access. class FileURLLoaderFactory : public network::SelfDeletingURLLoaderFactory { public: static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create( int child_id) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote; // The FileURLLoaderFactory will delete itself when there are no more // receivers - see the SelfDeletingURLLoaderFactory::OnDisconnect method. new FileURLLoaderFactory(child_id, pending_remote.InitWithNewPipeAndPassReceiver()); return pending_remote; } // disable copy FileURLLoaderFactory(const FileURLLoaderFactory&) = delete; FileURLLoaderFactory& operator=(const FileURLLoaderFactory&) = delete; private: explicit FileURLLoaderFactory( int child_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver) : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)), child_id_(child_id) {} ~FileURLLoaderFactory() override = default; // network::mojom::URLLoaderFactory: void CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { if (!content::ChildProcessSecurityPolicy::GetInstance()->CanRequestURL( child_id_, request.url)) { mojo::Remote<network::mojom::URLLoaderClient>(std::move(client)) ->OnComplete( network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED)); return; } content::CreateFileURLLoaderBypassingSecurityChecks( request, std::move(loader), std::move(client), /*observer=*/nullptr, /* allow_directory_listing */ true); } int child_id_; }; } // namespace #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void ElectronBrowserClient::RegisterNonNetworkSubresourceURLLoaderFactories( int render_process_id, int render_frame_id, const absl::optional<url::Origin>& request_initiator_origin, NonNetworkURLLoaderFactoryMap* factories) { auto* render_process_host = content::RenderProcessHost::FromID(render_process_id); DCHECK(render_process_host); if (!render_process_host || !render_process_host->GetBrowserContext()) return; content::RenderFrameHost* frame_host = content::RenderFrameHost::FromID(render_process_id, render_frame_id); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(frame_host); // Allow accessing file:// subresources from non-file protocols if web // security is disabled. bool allow_file_access = false; if (web_contents) { const auto& web_preferences = web_contents->GetOrCreateWebPreferences(); if (!web_preferences.web_security_enabled) allow_file_access = true; } ProtocolRegistry::FromBrowserContext(render_process_host->GetBrowserContext()) ->RegisterURLLoaderFactories(factories, allow_file_access); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto factory = extensions::CreateExtensionURLLoaderFactory(render_process_id, render_frame_id); if (factory) factories->emplace(extensions::kExtensionScheme, std::move(factory)); if (!web_contents) return; extensions::ElectronExtensionWebContentsObserver* web_observer = extensions::ElectronExtensionWebContentsObserver::FromWebContents( web_contents); // There is nothing to do if no ElectronExtensionWebContentsObserver is // attached to the |web_contents|. if (!web_observer) return; const extensions::Extension* extension = web_observer->GetExtensionFromFrame(frame_host, false); if (!extension) return; // Support for chrome:// scheme if appropriate. if (extension->is_extension() && extensions::Manifest::IsComponentLocation(extension->location())) { // Components of chrome that are implemented as extensions or platform apps // are allowed to use chrome://resources/ and chrome://theme/ URLs. factories->emplace(content::kChromeUIScheme, content::CreateWebUIURLLoaderFactory( frame_host, content::kChromeUIScheme, {content::kChromeUIResourcesHost})); } // Extensions with the necessary permissions get access to file:// URLs that // gets approval from ChildProcessSecurityPolicy. Keep this logic in sync with // ExtensionWebContentsObserver::RenderFrameCreated. extensions::Manifest::Type type = extension->GetType(); if (type == extensions::Manifest::TYPE_EXTENSION && AllowFileAccess(extension->id(), web_contents->GetBrowserContext())) { factories->emplace(url::kFileScheme, FileURLLoaderFactory::Create(render_process_id)); } #endif } void ElectronBrowserClient:: RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { DCHECK(browser_context); DCHECK(factories); #if BUILDFLAG(ENABLE_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionServiceWorkerScriptURLLoaderFactory( browser_context)); #endif // BUILDFLAG(ENABLE_EXTENSIONS) } bool ElectronBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel( base::StringPiece scheme, bool is_embedded_origin_secure) { if (is_embedded_origin_secure && scheme == content::kChromeUIScheme) return true; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) return scheme == extensions::kExtensionScheme; #else return false; #endif } bool ElectronBrowserClient::WillInterceptWebSocket( content::RenderFrameHost* frame) { if (!frame) return false; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); // NOTE: Some unit test environments do not initialize // BrowserContextKeyedAPI factories for e.g. WebRequest. if (!web_request.get()) return false; bool has_listener = web_request->HasListener(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const auto* web_request_api = extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get( browser_context); if (web_request_api) has_listener |= web_request_api->MayHaveProxies(); #endif return has_listener; } void ElectronBrowserClient::CreateWebSocket( content::RenderFrameHost* frame, WebSocketFactory factory, const GURL& url, const net::SiteForCookies& site_for_cookies, const absl::optional<std::string>& user_agent, mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); if (web_request_api && web_request_api->MayHaveProxies()) { web_request_api->ProxyWebSocket(frame, std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client)); return; } } #endif ProxyingWebSocket::StartProxying( web_request.get(), std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client), true, frame->GetProcess()->GetID(), frame->GetRoutingID(), frame->GetLastCommittedOrigin(), browser_context, &next_id_); } bool ElectronBrowserClient::WillCreateURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame_host, int render_process_id, URLLoaderFactoryType type, const url::Origin& request_initiator, absl::optional<int64_t> navigation_id, ukm::SourceIdObj ukm_source_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* header_client, bool* bypass_redirect_checks, bool* disable_secure_dns, network::mojom::URLLoaderFactoryOverridePtr* factory_override) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); DCHECK(web_request_api); bool use_proxy_for_web_request = web_request_api->MaybeProxyURLLoaderFactory( browser_context, frame_host, render_process_id, type, navigation_id, ukm_source_id, factory_receiver, header_client); if (bypass_redirect_checks) *bypass_redirect_checks = use_proxy_for_web_request; if (use_proxy_for_web_request) return true; } #endif auto proxied_receiver = std::move(*factory_receiver); mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote; *factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver(); // Required by WebRequestInfoInitParams. // // Note that in Electron we allow webRequest to capture requests sent from // browser process, so creation of |navigation_ui_data| is different from // Chromium which only does for renderer-initialized navigations. std::unique_ptr<extensions::ExtensionNavigationUIData> navigation_ui_data; if (navigation_id.has_value()) { navigation_ui_data = std::make_unique<extensions::ExtensionNavigationUIData>(); } mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> header_client_receiver; if (header_client) header_client_receiver = header_client->InitWithNewPipeAndPassReceiver(); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); new ProxyingURLLoaderFactory( web_request.get(), protocol_registry->intercept_handlers(), render_process_id, frame_host ? frame_host->GetRoutingID() : MSG_ROUTING_NONE, frame_host ? frame_host->GetRenderViewHost()->GetRoutingID() : MSG_ROUTING_NONE, &next_id_, std::move(navigation_ui_data), std::move(navigation_id), std::move(proxied_receiver), std::move(target_factory_remote), std::move(header_client_receiver), type); if (bypass_redirect_checks) *bypass_redirect_checks = true; return true; } void ElectronBrowserClient::OverrideURLLoaderFactoryParams( content::BrowserContext* browser_context, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) { if (factory_params->top_frame_id) { // Bypass CORB and CORS when web security is disabled. auto* rfh = content::RenderFrameHost::FromFrameToken( factory_params->process_id, blink::LocalFrameToken(factory_params->top_frame_id.value())); auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* prefs = WebContentsPreferences::From(web_contents); if (prefs && !prefs->IsWebSecurityEnabled()) { factory_params->is_corb_enabled = false; factory_params->disable_web_security = true; } } extensions::URLLoaderFactoryManager::OverrideURLLoaderFactoryParams( browser_context, origin, is_for_isolated_world, factory_params); } #if BUILDFLAG(IS_WIN) bool ElectronBrowserClient::PreSpawnChild(sandbox::TargetPolicy* policy, sandbox::mojom::Sandbox sandbox_type, ChildSpawnFlags flags) { // Allow crashpad to communicate via named pipe. sandbox::ResultCode result = policy->AddRule( sandbox::TargetPolicy::SUBSYS_FILES, sandbox::TargetPolicy::FILES_ALLOW_ANY, L"\\??\\pipe\\crashpad_*"); if (result != sandbox::SBOX_ALL_OK) return false; return true; } #endif // BUILDFLAG(IS_WIN) void ElectronBrowserClient:: RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, // NOLINT(runtime/references) blink::AssociatedInterfaceRegistry& associated_registry) { // NOLINT(runtime/references) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<electron::mojom::ElectronBrowser> receiver) { ElectronBrowserHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver> receiver) { AutofillDriverFactory::BindAutofillDriver(std::move(receiver), render_frame_host); }, &render_frame_host)); #if BUILDFLAG(ENABLE_PRINTING) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver) { PrintViewManagerElectron::BindPrintManagerHost(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_EXTENSIONS) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<extensions::mojom::LocalFrameHost> receiver) { extensions::ExtensionWebContentsObserver::BindLocalFrameHost( std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<pdf::mojom::PdfService> receiver) { pdf::PDFWebContentsHelper::BindPdfService(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif } std::string ElectronBrowserClient::GetApplicationLocale() { if (BrowserThread::CurrentlyOn(BrowserThread::IO)) return g_io_thread_application_locale.Get(); return *g_application_locale; } base::FilePath ElectronBrowserClient::GetFontLookupTableCacheDir() { base::FilePath user_data_dir; base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); DCHECK(!user_data_dir.empty()); return user_data_dir.Append(FILE_PATH_LITERAL("FontLookupTableCache")); } bool ElectronBrowserClient::ShouldEnableStrictSiteIsolation() { // Enable site isolation. It is off by default in Chromium <= 69. return true; } void ElectronBrowserClient::BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) { #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) if (auto host_receiver = receiver.As<spellcheck::mojom::SpellCheckHost>()) { SpellCheckHostChromeImpl::Create(render_process_host->GetID(), std::move(host_receiver)); return; } #endif } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void BindMimeHandlerService( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::MimeHandlerService> receiver) { content::WebContents* contents = content::WebContents::FromRenderFrameHost(frame_host); auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(contents); if (!guest_view) return; extensions::MimeHandlerServiceImpl::Create(guest_view->GetStreamWeakPtr(), std::move(receiver)); } void BindBeforeUnloadControl( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::BeforeUnloadControl> receiver) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); if (!web_contents) return; auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(web_contents); if (!guest_view) return; guest_view->FuseBeforeUnloadControl(std::move(receiver)); } #endif void ElectronBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) associated_registry->AddInterface(base::BindRepeating( &extensions::EventRouter::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface( base::BindRepeating(&extensions::ExtensionsGuestView::CreateForExtensions, render_process_host->GetID())); #endif } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForFrame( content::RenderFrameHost* render_frame_host, mojo::BinderMapWithContext<content::RenderFrameHost*>* map) { map->Add<network_hints::mojom::NetworkHintsHandler>( base::BindRepeating(&BindNetworkHintsHandler)); map->Add<blink::mojom::BadgeService>( base::BindRepeating(&badging::BadgeManager::BindFrameReceiver)); map->Add<blink::mojom::KeyboardLockService>(base::BindRepeating( &content::KeyboardLockServiceImpl::CreateMojoService)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) map->Add<extensions::mime_handler::MimeHandlerService>( base::BindRepeating(&BindMimeHandlerService)); map->Add<extensions::mime_handler::BeforeUnloadControl>( base::BindRepeating(&BindBeforeUnloadControl)); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); if (!web_contents) return; const GURL& site = render_frame_host->GetSiteInstance()->GetSiteURL(); if (!site.SchemeIs(extensions::kExtensionScheme)) return; content::BrowserContext* browser_context = render_frame_host->GetProcess()->GetBrowserContext(); auto* extension = extensions::ExtensionRegistry::Get(browser_context) ->enabled_extensions() .GetByID(site.host()); if (!extension) return; extensions::ExtensionsBrowserClient::Get() ->RegisterBrowserInterfaceBindersForFrame(map, render_frame_host, extension); #endif } #if BUILDFLAG(IS_LINUX) void ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) { int crash_signal_fd = GetCrashSignalFD(command_line); if (crash_signal_fd >= 0) { mappings->Share(kCrashDumpSignal, crash_signal_fd); } } #endif std::unique_ptr<content::LoginDelegate> ElectronBrowserClient::CreateLoginDelegate( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, const content::GlobalRequestID& request_id, bool is_main_frame, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) { return std::make_unique<LoginHandler>( auth_info, web_contents, is_main_frame, url, response_headers, first_auth_attempt, std::move(auth_required_callback)); } std::vector<std::unique_ptr<blink::URLLoaderThrottle>> ElectronBrowserClient::CreateURLLoaderThrottles( const network::ResourceRequest& request, content::BrowserContext* browser_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>( request.destination, frame_tree_node_id)); #endif return result; } base::flat_set<std::string> ElectronBrowserClient::GetPluginMimeTypesWithExternalHandlers( content::BrowserContext* browser_context) { base::flat_set<std::string> mime_types; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto map = PluginUtils::GetMimeTypeToExtensionIdMap(browser_context); for (const auto& pair : map) mime_types.insert(pair.first); #endif return mime_types; } content::SerialDelegate* ElectronBrowserClient::GetSerialDelegate() { if (!serial_delegate_) serial_delegate_ = std::make_unique<ElectronSerialDelegate>(); return serial_delegate_.get(); } content::BluetoothDelegate* ElectronBrowserClient::GetBluetoothDelegate() { if (!bluetooth_delegate_) bluetooth_delegate_ = std::make_unique<ElectronBluetoothDelegate>(); return bluetooth_delegate_.get(); } void BindBadgeServiceForServiceWorker( const content::ServiceWorkerVersionBaseInfo& info, mojo::PendingReceiver<blink::mojom::BadgeService> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RenderProcessHost* render_process_host = content::RenderProcessHost::FromID(info.process_id); if (!render_process_host) return; badging::BadgeManager::BindServiceWorkerReceiver( render_process_host, info.scope, std::move(receiver)); } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForServiceWorker( mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) { map->Add<blink::mojom::BadgeService>( base::BindRepeating(&BindBadgeServiceForServiceWorker)); } device::GeolocationManager* ElectronBrowserClient::GetGeolocationManager() { #if BUILDFLAG(IS_MAC) return browser_main_parts_->GetGeolocationManager(); #else return nullptr; #endif } content::HidDelegate* ElectronBrowserClient::GetHidDelegate() { if (!hid_delegate_) hid_delegate_ = std::make_unique<ElectronHidDelegate>(); return hid_delegate_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
15,448
Support Chromium's command-line switch --unsafely-treat-insecure-origin-as-secure
**Is your feature request related to a problem? Please describe.** Notifications, Geolocation, Device motion/orientation, EME, getUserMedia, AppCache require a secure origin to work in Chromium. HTTP URLs are not considered secure. That's why Chromium provides the command-line switch `--unsafely-treat-insecure-origin-as-secure="$url"` to circumvent this problem. Unfortunately it's not working in Electron. **Describe the solution you'd like** Please make it work. In the renderer. I'd suggest simply like ``` new BrowserWindow({ webPreferences: { additionalArguments: { '--unsafely-treat-insecure-origin-as-secure', 'http://insecure-origin' } } ``` Or a new option `considerSecure: String[]` to `BrowserWindow.webPreferences`. I guess it should be not too hard to implement since Chromium already supports it and it seems to get lost only in the process of Electron integration. **Describe alternatives you've considered** - `app.commandLine.appendSwitch('unsafely-treat-insecure-origin-as-secure', $url)` in the main thread - Invisible [BrowserWindow](https://github.com/electron/electron/blob/master/docs/api/browser-window.md) with secure origin + IPC - `<iframe>` on a secure origin - localhost-Proxy - Using Data URLs in [loadURL](https://github.com/electron/electron/blob/master/docs/api/browser-window.md#winloadurlurl-options): `data:text/html,<script>new Notification("hi")</script>` - webFrame.registerURLSchemeAsPrivileged **Additional context** 'Deprecating Powerful Features on Insecure Origins' https://goo.gl/rStTGz When the flag is set in Chromium a message appears under the address bar, saying that 'You are using an unsupported command-line flag'. ![image](https://user-images.githubusercontent.com/23075755/47640947-1c6ebf80-db65-11e8-9e6e-d7a5bd90c208.png) Nonetheless the features are then working on the origin treated securely.
https://github.com/electron/electron/issues/15448
https://github.com/electron/electron/pull/33189
865a29ed17d498335790c2c6998578e1e76c5513
ebfcf89a0b554804fc8707215752a1130dc10182
2018-10-29T09:42:35Z
c++
2022-03-09T15:15:50Z
shell/browser/electron_browser_client.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_client.h" #if BUILDFLAG(IS_WIN) #include <shlobj.h> #endif #include <memory> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/debug/crash_logging.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/lazy_instance.h" #include "base/no_destructor.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version.h" #include "components/net_log/chrome_net_log.h" #include "components/network_hints/common/network_hints.mojom.h" #include "content/browser/keyboard_lock/keyboard_lock_service_impl.h" // nogncheck #include "content/browser/site_instance_impl.h" // nogncheck #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/browser_ppapi_host.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/client_certificate_delegate.h" #include "content/public/browser/login_delegate.h" #include "content/public/browser/overlay_window.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/service_worker_version_base_info.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/tts_controller.h" #include "content/public/browser/tts_platform.h" #include "content/public/common/content_descriptors.h" #include "content/public/common/content_paths.h" #include "content/public/common/content_switches.h" #include "content/public/common/url_constants.h" #include "crypto/crypto_buildflags.h" #include "electron/buildflags/buildflags.h" #include "electron/grit/electron_resources.h" #include "electron/shell/common/api/api.mojom.h" #include "extensions/browser/api/messaging/messaging_api_message_filter.h" #include "mojo/public/cpp/bindings/binder_map.h" #include "net/base/escape.h" #include "net/ssl/ssl_cert_request_info.h" #include "ppapi/buildflags/buildflags.h" #include "ppapi/host/ppapi_host.h" #include "printing/buildflags/buildflags.h" #include "services/device/public/cpp/geolocation/location_provider.h" #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/resource_request_body.h" #include "services/network/public/cpp/self_deleting_url_loader_factory.h" #include "shell/app/electron_crash_reporter_client.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_crash_reporter.h" #include "shell/browser/api/electron_api_protocol.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/api/electron_api_web_request.h" #include "shell/browser/badging/badge_manager.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_handler_impl.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/electron_quota_permission_context.h" #include "shell/browser/electron_speech_recognition_manager_delegate.h" #include "shell/browser/font_defaults.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/native_window.h" #include "shell/browser/net/network_context_service.h" #include "shell/browser/net/network_context_service_factory.h" #include "shell/browser/net/proxying_url_loader_factory.h" #include "shell/browser/net/proxying_websocket.h" #include "shell/browser/net/system_network_context_manager.h" #include "shell/browser/network_hints_handler_impl.h" #include "shell/browser/notifications/notification_presenter.h" #include "shell/browser/notifications/platform_notification_service.h" #include "shell/browser/protocol_registry.h" #include "shell/browser/serial/electron_serial_delegate.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/window_list.h" #include "shell/common/api/api.mojom.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/logging.h" #include "shell/common/options_switches.h" #include "shell/common/platform_util.h" #include "third_party/blink/public/common/loader/url_loader_throttle.h" #include "third_party/blink/public/common/tokens/tokens.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/mojom/badging/badging.mojom.h" #include "ui/base/resource/resource_bundle.h" #include "ui/native_theme/native_theme.h" #include "v8/include/v8.h" #if BUILDFLAG(IS_WIN) #include "sandbox/win/src/sandbox_policy.h" #endif #if BUILDFLAG(USE_NSS_CERTS) #include "net/ssl/client_cert_store_nss.h" #elif BUILDFLAG(IS_WIN) #include "net/ssl/client_cert_store_win.h" #elif BUILDFLAG(IS_MAC) #include "net/ssl/client_cert_store_mac.h" #elif defined(USE_OPENSSL) #include "net/ssl/client_cert_store.h" #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" // nogncheck #include "components/spellcheck/common/spellcheck.mojom.h" // nogncheck #endif #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #include "shell/browser/fake_location_provider.h" #endif // BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "chrome/common/webui_url_constants.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/file_url_loader.h" #include "content/public/browser/web_ui_url_loader_factory.h" #include "extensions/browser/api/mime_handler_private/mime_handler_private.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_message_filter.h" #include "extensions/browser/extension_navigation_throttle.h" #include "extensions/browser/extension_navigation_ui_data.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_protocols.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extensions_browser_client.h" #include "extensions/browser/guest_view/extensions_guest_view.h" #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h" #include "extensions/browser/info_map.h" #include "extensions/browser/process_manager.h" #include "extensions/browser/process_map.h" #include "extensions/browser/url_loader_factory_manager.h" #include "extensions/common/api/mime_handler.mojom.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" #include "extensions/common/switches.h" #include "shell/browser/extensions/electron_extension_message_filter.h" #include "shell/browser/extensions/electron_extension_system.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h" #endif #if BUILDFLAG(ENABLE_PLUGINS) #include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h" // nogncheck #include "shell/browser/plugins/plugin_utils.h" #endif #if BUILDFLAG(IS_MAC) #include "content/common/mac_helpers.h" #include "content/public/common/child_process_host.h" #endif #if BUILDFLAG(IS_LINUX) && !defined(MAS_BUILD) #include "base/debug/leak_annotations.h" #include "components/crash/content/browser/crash_handler_host_linux.h" #include "components/crash/core/app/breakpad_linux.h" // nogncheck #include "components/crash/core/app/crash_switches.h" // nogncheck #include "components/crash/core/app/crashpad.h" // nogncheck #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) && BUILDFLAG(IS_WIN) #include "chrome/browser/ui/views/overlay/document_overlay_window_views.h" #include "chrome/browser/ui/views/overlay/video_overlay_window_views.h" #include "shell/browser/browser.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/win/shell.h" #include "ui/views/widget/widget.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "shell/browser/printing/print_view_manager_electron.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #endif using content::BrowserThread; namespace electron { namespace { ElectronBrowserClient* g_browser_client = nullptr; base::LazyInstance<std::string>::DestructorAtExit g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER; base::NoDestructor<std::string> g_application_locale; void SetApplicationLocaleOnIOThread(const std::string& locale) { DCHECK_CURRENTLY_ON(BrowserThread::IO); g_io_thread_application_locale.Get() = locale; } void BindNetworkHintsHandler( content::RenderFrameHost* frame_host, mojo::PendingReceiver<network_hints::mojom::NetworkHintsHandler> receiver) { NetworkHintsHandlerImpl::Create(frame_host, std::move(receiver)); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions // below. Extension, and isolated apps require different privileges to be // granted to their RenderProcessHosts. This classification allows us to make // sure URLs are served by hosts with the right set of privileges. enum class RenderProcessHostPrivilege { kNormal, kHosted, kIsolated, kExtension, }; // Copied from chrome/browser/extensions/extension_util.cc. bool AllowFileAccess(const std::string& extension_id, content::BrowserContext* context) { return base::CommandLine::ForCurrentProcess()->HasSwitch( ::switches::kDisableExtensionsFileAccessCheck) || extensions::ExtensionPrefs::Get(context)->AllowFileAccess( extension_id); } RenderProcessHostPrivilege GetPrivilegeRequiredByUrl( const GURL& url, extensions::ExtensionRegistry* registry) { // Default to a normal renderer cause it is lower privileged. This should only // occur if the URL on a site instance is either malformed, or uninitialized. // If it is malformed, then there is no need for better privileges anyways. // If it is uninitialized, but eventually settles on being an a scheme other // than normal webrenderer, the navigation logic will correct us out of band // anyways. if (!url.is_valid()) return RenderProcessHostPrivilege::kNormal; if (!url.SchemeIs(extensions::kExtensionScheme)) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } RenderProcessHostPrivilege GetProcessPrivilege( content::RenderProcessHost* process_host, extensions::ProcessMap* process_map, extensions::ExtensionRegistry* registry) { std::set<std::string> extension_ids = process_map->GetExtensionsInProcess(process_host->GetID()); if (extension_ids.empty()) return RenderProcessHostPrivilege::kNormal; return RenderProcessHostPrivilege::kExtension; } const extensions::Extension* GetEnabledExtensionFromEffectiveURL( content::BrowserContext* context, const GURL& effective_url) { if (!effective_url.SchemeIs(extensions::kExtensionScheme)) return nullptr; extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(context); if (!registry) return nullptr; return registry->enabled_extensions().GetByID(effective_url.host()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(IS_LINUX) breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost( const std::string& process_type) { base::FilePath dumps_path; base::PathService::Get(electron::DIR_CRASH_DUMPS, &dumps_path); { ANNOTATE_SCOPED_MEMORY_LEAK; bool upload = ElectronCrashReporterClient::Get()->GetCollectStatsConsent(); breakpad::CrashHandlerHostLinux* crash_handler = new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload); crash_handler->StartUploaderThread(); return crash_handler; } } int GetCrashSignalFD(const base::CommandLine& command_line) { if (crash_reporter::IsCrashpadEnabled()) { int fd; pid_t pid; return crash_reporter::GetHandlerSocket(&fd, &pid) ? fd : -1; } // Extensions have the same process type as renderers. if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost("extension"); return crash_handler->GetDeathSignalSocket(); } std::string process_type = command_line.GetSwitchValueASCII(::switches::kProcessType); if (process_type == ::switches::kRendererProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == ::switches::kPpapiPluginProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == ::switches::kGpuProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } if (process_type == ::switches::kUtilityProcess) { static breakpad::CrashHandlerHostLinux* crash_handler = nullptr; if (!crash_handler) crash_handler = CreateCrashHandlerHost(process_type); return crash_handler->GetDeathSignalSocket(); } return -1; } #endif // BUILDFLAG(IS_LINUX) } // namespace // static ElectronBrowserClient* ElectronBrowserClient::Get() { return g_browser_client; } // static void ElectronBrowserClient::SetApplicationLocale(const std::string& locale) { if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) || !base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) { g_io_thread_application_locale.Get() = locale; } *g_application_locale = locale; } ElectronBrowserClient::ElectronBrowserClient() { DCHECK(!g_browser_client); g_browser_client = this; } ElectronBrowserClient::~ElectronBrowserClient() { DCHECK(g_browser_client); g_browser_client = nullptr; } content::WebContents* ElectronBrowserClient::GetWebContentsFromProcessID( int process_id) { // If the process is a pending process, we should use the web contents // for the frame host passed into RegisterPendingProcess. const auto iter = pending_processes_.find(process_id); if (iter != std::end(pending_processes_)) return iter->second; // Certain render process will be created with no associated render view, // for example: ServiceWorker. return WebContentsPreferences::GetWebContentsFromProcessID(process_id); } content::SiteInstance* ElectronBrowserClient::GetSiteInstanceFromAffinity( content::BrowserContext* browser_context, const GURL& url, content::RenderFrameHost* rfh) const { return nullptr; } bool ElectronBrowserClient::IsRendererSubFrame(int process_id) const { return base::Contains(renderer_is_subframe_, process_id); } void ElectronBrowserClient::RenderProcessWillLaunch( content::RenderProcessHost* host) { // When a render process is crashed, it might be reused. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) int process_id = host->GetID(); auto* browser_context = host->GetBrowserContext(); host->AddFilter( new extensions::ExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new ElectronExtensionMessageFilter(process_id, browser_context)); host->AddFilter( new extensions::MessagingAPIMessageFilter(process_id, browser_context)); #endif // ensure the ProcessPreferences is removed later host->AddObserver(this); } content::SpeechRecognitionManagerDelegate* ElectronBrowserClient::CreateSpeechRecognitionManagerDelegate() { return new ElectronSpeechRecognitionManagerDelegate; } content::TtsPlatform* ElectronBrowserClient::GetTtsPlatform() { return nullptr; } void ElectronBrowserClient::OverrideWebkitPrefs( content::WebContents* web_contents, blink::web_pref::WebPreferences* prefs) { prefs->javascript_enabled = true; prefs->web_security_enabled = true; prefs->plugins_enabled = true; prefs->dom_paste_enabled = true; prefs->allow_scripts_to_close_windows = true; prefs->javascript_can_access_clipboard = true; prefs->local_storage_enabled = true; prefs->databases_enabled = true; prefs->allow_universal_access_from_file_urls = true; prefs->allow_file_access_from_file_urls = true; prefs->webgl1_enabled = true; prefs->webgl2_enabled = true; prefs->allow_running_insecure_content = false; prefs->default_minimum_page_scale_factor = 1.f; prefs->default_maximum_page_scale_factor = 1.f; prefs->navigate_on_drag_drop = false; #if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) prefs->picture_in_picture_enabled = false; #endif ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi(); prefs->preferred_color_scheme = native_theme->ShouldUseDarkColors() ? blink::mojom::PreferredColorScheme::kDark : blink::mojom::PreferredColorScheme::kLight; auto preloads = SessionPreferences::GetValidPreloads(web_contents->GetBrowserContext()); if (!preloads.empty()) prefs->preloads = preloads; SetFontDefaults(prefs); // Custom preferences of guest page. auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) { web_preferences->OverrideWebkitPrefs(prefs); } } void ElectronBrowserClient::RegisterPendingSiteInstance( content::RenderFrameHost* rfh, content::SiteInstance* pending_site_instance) { // Remember the original web contents for the pending renderer process. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* pending_process = pending_site_instance->GetProcess(); pending_processes_[pending_process->GetID()] = web_contents; if (rfh->GetParent()) renderer_is_subframe_.insert(pending_process->GetID()); else renderer_is_subframe_.erase(pending_process->GetID()); } void ElectronBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { // Make sure we're about to launch a known executable { base::ThreadRestrictions::ScopedAllowIO allow_io; base::FilePath child_path; base::FilePath program = base::MakeAbsoluteFilePath(command_line->GetProgram()); #if BUILDFLAG(IS_MAC) auto renderer_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_RENDERER); auto gpu_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_GPU); #if BUILDFLAG(ENABLE_PLUGINS) auto plugin_child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_PLUGIN); #endif if (program != renderer_child_path && program != gpu_child_path #if BUILDFLAG(ENABLE_PLUGINS) && program != plugin_child_path #endif ) { child_path = content::ChildProcessHost::GetChildPath( content::ChildProcessHost::CHILD_NORMAL); CHECK_EQ(program, child_path) << "Aborted from launching unexpected helper executable"; } #else if (!base::PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) { CHECK(false) << "Unable to get child process binary name."; } SCOPED_CRASH_KEY_STRING256("ChildProcess", "child_process_exe", child_path.AsUTF8Unsafe()); SCOPED_CRASH_KEY_STRING256("ChildProcess", "program", program.AsUTF8Unsafe()); CHECK_EQ(program, child_path); #endif } std::string process_type = command_line->GetSwitchValueASCII(::switches::kProcessType); #if BUILDFLAG(IS_LINUX) bool enable_crash_reporter = false; if (crash_reporter::IsCrashpadEnabled()) { command_line->AppendSwitch(::switches::kEnableCrashpad); enable_crash_reporter = true; int fd; pid_t pid; if (crash_reporter::GetHandlerSocket(&fd, &pid)) { command_line->AppendSwitchASCII( crash_reporter::switches::kCrashpadHandlerPid, base::NumberToString(pid)); } } else { enable_crash_reporter = breakpad::IsCrashReporterEnabled(); } // Zygote Process gets booted before any JS runs, accessing GetClientId // will end up touching DIR_USER_DATA path provider and this will // configure default value because app.name from browser_init has // not run yet. if (enable_crash_reporter && process_type != ::switches::kZygoteProcess) { std::string switch_value = api::crash_reporter::GetClientId() + ",no_channel"; command_line->AppendSwitchASCII(::switches::kEnableCrashReporter, switch_value); if (!crash_reporter::IsCrashpadEnabled()) { for (const auto& pair : api::crash_reporter::GetGlobalCrashKeys()) { if (!switch_value.empty()) switch_value += ","; switch_value += pair.first; switch_value += "="; switch_value += pair.second; } command_line->AppendSwitchASCII(switches::kGlobalCrashKeys, switch_value); } } #endif // The zygote process is booted before JS runs, so DIR_USER_DATA isn't usable // at that time. It doesn't need --user-data-dir to be correct anyway, since // the zygote itself doesn't access anything in that directory. if (process_type != ::switches::kZygoteProcess) { base::FilePath user_data_dir; if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir)) command_line->AppendSwitchPath(::switches::kUserDataDir, user_data_dir); } if (process_type == ::switches::kUtilityProcess || process_type == ::switches::kRendererProcess) { // Copy following switches to child process. static const char* const kCommonSwitchNames[] = { switches::kStandardSchemes, switches::kEnableSandbox, switches::kSecureSchemes, switches::kBypassCSPSchemes, switches::kCORSSchemes, switches::kFetchSchemes, switches::kServiceWorkerSchemes, switches::kStreamingSchemes}; command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(), kCommonSwitchNames, base::size(kCommonSwitchNames)); } if (process_type == ::switches::kRendererProcess) { #if BUILDFLAG(IS_WIN) // Append --app-user-model-id. PWSTR current_app_id; if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) { command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id); CoTaskMemFree(current_app_id); } #endif if (delegate_) { auto app_path = static_cast<api::App*>(delegate_)->GetAppPath(); command_line->AppendSwitchPath(switches::kAppPath, app_path); } auto env = base::Environment::Create(); if (env->HasVar("ELECTRON_PROFILE_INIT_SCRIPTS")) { command_line->AppendSwitch("profile-electron-init"); } // Extension background pages don't have WebContentsPreferences, but they // support WebSQL by default. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) content::RenderProcessHost* process = content::RenderProcessHost::FromID(process_id); if (extensions::ProcessMap::Get(process->GetBrowserContext()) ->Contains(process_id)) command_line->AppendSwitch(switches::kEnableWebSQL); #endif content::WebContents* web_contents = GetWebContentsFromProcessID(process_id); if (web_contents) { auto* web_preferences = WebContentsPreferences::From(web_contents); if (web_preferences) web_preferences->AppendCommandLineSwitches( command_line, IsRendererSubFrame(process_id)); } } } void ElectronBrowserClient::DidCreatePpapiPlugin( content::BrowserPpapiHost* host) {} // attempt to get api key from env std::string ElectronBrowserClient::GetGeolocationApiKey() { auto env = base::Environment::Create(); std::string api_key; env->GetVar("GOOGLE_API_KEY", &api_key); return api_key; } scoped_refptr<content::QuotaPermissionContext> ElectronBrowserClient::CreateQuotaPermissionContext() { return base::MakeRefCounted<ElectronQuotaPermissionContext>(); } content::GeneratedCodeCacheSettings ElectronBrowserClient::GetGeneratedCodeCacheSettings( content::BrowserContext* context) { // TODO(deepak1556): Use platform cache directory. base::FilePath cache_path = context->GetPath(); // If we pass 0 for size, disk_cache will pick a default size using the // heuristics based on available disk size. These are implemented in // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc. return content::GeneratedCodeCacheSettings(true, 0, cache_path); } void ElectronBrowserClient::AllowCertificateError( content::WebContents* web_contents, int cert_error, const net::SSLInfo& ssl_info, const GURL& request_url, bool is_main_frame_request, bool strict_enforcement, base::OnceCallback<void(content::CertificateRequestResultType)> callback) { if (delegate_) { delegate_->AllowCertificateError(web_contents, cert_error, ssl_info, request_url, is_main_frame_request, strict_enforcement, std::move(callback)); } } base::OnceClosure ElectronBrowserClient::SelectClientCertificate( content::WebContents* web_contents, net::SSLCertRequestInfo* cert_request_info, net::ClientCertIdentityList client_certs, std::unique_ptr<content::ClientCertificateDelegate> delegate) { if (!client_certs.empty() && delegate_) { delegate_->SelectClientCertificate(web_contents, cert_request_info, std::move(client_certs), std::move(delegate)); } return base::OnceClosure(); } bool ElectronBrowserClient::CanCreateWindow( content::RenderFrameHost* opener, const GURL& opener_url, const GURL& opener_top_level_frame_url, const url::Origin& source_origin, content::mojom::WindowContainerType container_type, const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const blink::mojom::WindowFeatures& features, const std::string& raw_features, const scoped_refptr<network::ResourceRequestBody>& body, bool user_gesture, bool opener_suppressed, bool* no_javascript_access) { DCHECK_CURRENTLY_ON(BrowserThread::UI); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(opener); WebContentsPreferences* prefs = WebContentsPreferences::From(web_contents); if (prefs) { if (prefs->ShouldDisablePopups()) { // <webview> without allowpopups attribute should return // null from window.open calls return false; } else { *no_javascript_access = false; return true; } } if (delegate_) { return delegate_->CanCreateWindow( opener, opener_url, opener_top_level_frame_url, source_origin, container_type, target_url, referrer, frame_name, disposition, features, raw_features, body, user_gesture, opener_suppressed, no_javascript_access); } return false; } #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) std::unique_ptr<content::VideoOverlayWindow> ElectronBrowserClient::CreateWindowForVideoPictureInPicture( content::VideoPictureInPictureWindowController* controller) { auto overlay_window = content::VideoOverlayWindow::Create(controller); #if BUILDFLAG(IS_WIN) std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID(); if (!app_user_model_id.empty()) { auto* overlay_window_view = static_cast<VideoOverlayWindowViews*>(overlay_window.get()); ui::win::SetAppIdForWindow(app_user_model_id, overlay_window_view->GetNativeWindow() ->GetHost() ->GetAcceleratedWidget()); } #endif return overlay_window; } std::unique_ptr<content::DocumentOverlayWindow> ElectronBrowserClient::CreateWindowForDocumentPictureInPicture( content::DocumentPictureInPictureWindowController* controller) { auto overlay_window = content::DocumentOverlayWindow::Create(controller); #if BUILDFLAG(IS_WIN) std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID(); if (!app_user_model_id.empty()) { auto* overlay_window_view = static_cast<DocumentOverlayWindowViews*>(overlay_window.get()); ui::win::SetAppIdForWindow(app_user_model_id, overlay_window_view->GetNativeWindow() ->GetHost() ->GetAcceleratedWidget()); } #endif return overlay_window; } #endif void ElectronBrowserClient::GetAdditionalAllowedSchemesForFileSystem( std::vector<std::string>* additional_schemes) { auto schemes_list = api::GetStandardSchemes(); if (!schemes_list.empty()) additional_schemes->insert(additional_schemes->end(), schemes_list.begin(), schemes_list.end()); additional_schemes->push_back(content::kChromeDevToolsScheme); additional_schemes->push_back(content::kChromeUIScheme); } void ElectronBrowserClient::GetAdditionalWebUISchemes( std::vector<std::string>* additional_schemes) { additional_schemes->push_back(content::kChromeDevToolsScheme); } void ElectronBrowserClient::SiteInstanceGotProcess( content::SiteInstance* site_instance) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext()); if (!browser_context->IsOffTheRecord()) { extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); const extensions::Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL( site_instance->GetSiteURL()); if (!extension) return; extensions::ProcessMap::Get(browser_context) ->Insert(extension->id(), site_instance->GetProcess()->GetID(), site_instance->GetId()); } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) } bool ElectronBrowserClient::IsSuitableHost( content::RenderProcessHost* process_host, const GURL& site_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto* browser_context = process_host->GetBrowserContext(); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); extensions::ProcessMap* process_map = extensions::ProcessMap::Get(browser_context); // Otherwise, just make sure the process privilege matches the privilege // required by the site. RenderProcessHostPrivilege privilege_required = GetPrivilegeRequiredByUrl(site_url, registry); return GetProcessPrivilege(process_host, process_map, registry) == privilege_required; #else return content::ContentBrowserClient::IsSuitableHost(process_host, site_url); #endif } bool ElectronBrowserClient::ShouldUseProcessPerSite( content::BrowserContext* browser_context, const GURL& effective_url) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const extensions::Extension* extension = GetEnabledExtensionFromEffectiveURL(browser_context, effective_url); return extension != nullptr; #else return content::ContentBrowserClient::ShouldUseProcessPerSite(browser_context, effective_url); #endif } bool ElectronBrowserClient::ArePersistentMediaDeviceIDsAllowed( content::BrowserContext* browser_context, const GURL& scope, const net::SiteForCookies& site_for_cookies, const absl::optional<url::Origin>& top_frame_origin) { return true; } base::FilePath ElectronBrowserClient::GetLoggingFileName( const base::CommandLine& cmd_line) { return logging::GetLogFileName(cmd_line); } void ElectronBrowserClient::SiteInstanceDeleting( content::SiteInstance* site_instance) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // Don't do anything if we're shutting down. if (content::BrowserMainRunner::ExitedMainMessageLoop()) return; auto* browser_context = static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext()); if (!browser_context->IsOffTheRecord()) { // If this isn't an extension renderer there's nothing to do. extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser_context); const extensions::Extension* extension = registry->enabled_extensions().GetExtensionOrAppByURL( site_instance->GetSiteURL()); if (!extension) return; extensions::ProcessMap::Get(browser_context) ->Remove(extension->id(), site_instance->GetProcess()->GetID(), site_instance->GetId()); } #endif } std::unique_ptr<net::ClientCertStore> ElectronBrowserClient::CreateClientCertStore( content::BrowserContext* browser_context) { #if BUILDFLAG(USE_NSS_CERTS) return std::make_unique<net::ClientCertStoreNSS>( net::ClientCertStoreNSS::PasswordDelegateFactory()); #elif BUILDFLAG(IS_WIN) return std::make_unique<net::ClientCertStoreWin>(); #elif BUILDFLAG(IS_MAC) return std::make_unique<net::ClientCertStoreMac>(); #elif defined(USE_OPENSSL) return std::unique_ptr<net::ClientCertStore>(); #endif } std::unique_ptr<device::LocationProvider> ElectronBrowserClient::OverrideSystemLocationProvider() { #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER) return std::make_unique<FakeLocationProvider>(); #else return nullptr; #endif } void ElectronBrowserClient::ConfigureNetworkContextParams( content::BrowserContext* browser_context, bool in_memory, const base::FilePath& relative_partition_path, network::mojom::NetworkContextParams* network_context_params, cert_verifier::mojom::CertVerifierCreationParams* cert_verifier_creation_params) { DCHECK(browser_context); return NetworkContextServiceFactory::GetForContext(browser_context) ->ConfigureNetworkContextParams(network_context_params, cert_verifier_creation_params); } network::mojom::NetworkContext* ElectronBrowserClient::GetSystemNetworkContext() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(g_browser_process->system_network_context_manager()); return g_browser_process->system_network_context_manager()->GetContext(); } std::unique_ptr<content::BrowserMainParts> ElectronBrowserClient::CreateBrowserMainParts( content::MainFunctionParams params) { auto browser_main_parts = std::make_unique<ElectronBrowserMainParts>(std::move(params)); #if BUILDFLAG(IS_MAC) browser_main_parts_ = browser_main_parts.get(); #endif return browser_main_parts; } void ElectronBrowserClient::WebNotificationAllowed( content::RenderFrameHost* rfh, base::OnceCallback<void(bool, bool)> callback) { content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) { std::move(callback).Run(false, false); return; } auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) { std::move(callback).Run(false, false); return; } permission_helper->RequestWebNotificationPermission( base::BindOnce(std::move(callback), web_contents->IsAudioMuted())); } void ElectronBrowserClient::RenderProcessHostDestroyed( content::RenderProcessHost* host) { int process_id = host->GetID(); pending_processes_.erase(process_id); renderer_is_subframe_.erase(process_id); host->RemoveObserver(this); } void ElectronBrowserClient::RenderProcessReady( content::RenderProcessHost* host) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessReady(host); } } void ElectronBrowserClient::RenderProcessExited( content::RenderProcessHost* host, const content::ChildProcessTerminationInfo& info) { if (delegate_) { static_cast<api::App*>(delegate_)->RenderProcessExited(host); } } void OnOpenExternal(const GURL& escaped_url, bool allowed) { if (allowed) { platform_util::OpenExternal( escaped_url, platform_util::OpenExternalOptions(), base::DoNothing()); } } void HandleExternalProtocolInUI( const GURL& url, content::WebContents::OnceGetter web_contents_getter, bool has_user_gesture) { content::WebContents* web_contents = std::move(web_contents_getter).Run(); if (!web_contents) return; auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); if (!permission_helper) return; GURL escaped_url(net::EscapeExternalHandlerValue(url.spec())); auto callback = base::BindOnce(&OnOpenExternal, escaped_url); permission_helper->RequestOpenExternalPermission(std::move(callback), has_user_gesture, url); } bool ElectronBrowserClient::HandleExternalProtocol( const GURL& url, content::WebContents::Getter web_contents_getter, int child_id, int frame_tree_node_id, content::NavigationUIData* navigation_data, bool is_main_frame, network::mojom::WebSandboxFlags sandbox_flags, ui::PageTransition page_transition, bool has_user_gesture, const absl::optional<url::Origin>& initiating_origin, content::RenderFrameHost* initiator_document, mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) { base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&HandleExternalProtocolInUI, url, std::move(web_contents_getter), has_user_gesture)); return true; } std::vector<std::unique_ptr<content::NavigationThrottle>> ElectronBrowserClient::CreateThrottlesForNavigation( content::NavigationHandle* handle) { std::vector<std::unique_ptr<content::NavigationThrottle>> throttles; throttles.push_back(std::make_unique<ElectronNavigationThrottle>(handle)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) throttles.push_back( std::make_unique<extensions::ExtensionNavigationThrottle>(handle)); #endif return throttles; } content::MediaObserver* ElectronBrowserClient::GetMediaObserver() { return MediaCaptureDevicesDispatcher::GetInstance(); } std::unique_ptr<content::DevToolsManagerDelegate> ElectronBrowserClient::CreateDevToolsManagerDelegate() { return std::make_unique<DevToolsManagerDelegate>(); } NotificationPresenter* ElectronBrowserClient::GetNotificationPresenter() { if (!notification_presenter_) { notification_presenter_.reset(NotificationPresenter::Create()); } return notification_presenter_.get(); } content::PlatformNotificationService* ElectronBrowserClient::GetPlatformNotificationService() { if (!notification_service_) { notification_service_ = std::make_unique<PlatformNotificationService>(this); } return notification_service_.get(); } base::FilePath ElectronBrowserClient::GetDefaultDownloadDirectory() { base::FilePath download_path; if (base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_path)) return download_path; return base::FilePath(); } scoped_refptr<network::SharedURLLoaderFactory> ElectronBrowserClient::GetSystemSharedURLLoaderFactory() { if (!g_browser_process) return nullptr; return g_browser_process->shared_url_loader_factory(); } void ElectronBrowserClient::OnNetworkServiceCreated( network::mojom::NetworkService* network_service) { if (!g_browser_process) return; g_browser_process->system_network_context_manager()->OnNetworkServiceCreated( network_service); } std::vector<base::FilePath> ElectronBrowserClient::GetNetworkContextsParentDirectory() { base::FilePath user_data_dir; base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); DCHECK(!user_data_dir.empty()); return {user_data_dir}; } std::string ElectronBrowserClient::GetProduct() { return "Chrome/" CHROME_VERSION_STRING; } std::string ElectronBrowserClient::GetUserAgent() { if (user_agent_override_.empty()) return GetApplicationUserAgent(); return user_agent_override_; } void ElectronBrowserClient::SetUserAgent(const std::string& user_agent) { user_agent_override_ = user_agent; } void ElectronBrowserClient::RegisterNonNetworkNavigationURLLoaderFactories( int frame_tree_node_id, ukm::SourceIdObj ukm_source_id, NonNetworkURLLoaderFactoryMap* factories) { content::WebContents* web_contents = content::WebContents::FromFrameTreeNodeId(frame_tree_node_id); content::BrowserContext* context = web_contents->GetBrowserContext(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionNavigationURLLoaderFactory( context, ukm_source_id, false /* we don't support extensions::WebViewGuest */)); #endif // Always allow navigating to file:// URLs. auto* protocol_registry = ProtocolRegistry::FromBrowserContext(context); protocol_registry->RegisterURLLoaderFactories(factories, true /* allow_file_access */); } void ElectronBrowserClient:: RegisterNonNetworkWorkerMainResourceURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); // Workers are not allowed to request file:// URLs, there is no particular // reason for it, and we could consider supporting it in future. protocol_registry->RegisterURLLoaderFactories(factories, false /* allow_file_access */); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) namespace { // The FileURLLoaderFactory provided to the extension background pages. // Checks with the ChildProcessSecurityPolicy to validate the file access. class FileURLLoaderFactory : public network::SelfDeletingURLLoaderFactory { public: static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create( int child_id) { mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote; // The FileURLLoaderFactory will delete itself when there are no more // receivers - see the SelfDeletingURLLoaderFactory::OnDisconnect method. new FileURLLoaderFactory(child_id, pending_remote.InitWithNewPipeAndPassReceiver()); return pending_remote; } // disable copy FileURLLoaderFactory(const FileURLLoaderFactory&) = delete; FileURLLoaderFactory& operator=(const FileURLLoaderFactory&) = delete; private: explicit FileURLLoaderFactory( int child_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver) : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)), child_id_(child_id) {} ~FileURLLoaderFactory() override = default; // network::mojom::URLLoaderFactory: void CreateLoaderAndStart( mojo::PendingReceiver<network::mojom::URLLoader> loader, int32_t request_id, uint32_t options, const network::ResourceRequest& request, mojo::PendingRemote<network::mojom::URLLoaderClient> client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { if (!content::ChildProcessSecurityPolicy::GetInstance()->CanRequestURL( child_id_, request.url)) { mojo::Remote<network::mojom::URLLoaderClient>(std::move(client)) ->OnComplete( network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED)); return; } content::CreateFileURLLoaderBypassingSecurityChecks( request, std::move(loader), std::move(client), /*observer=*/nullptr, /* allow_directory_listing */ true); } int child_id_; }; } // namespace #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void ElectronBrowserClient::RegisterNonNetworkSubresourceURLLoaderFactories( int render_process_id, int render_frame_id, const absl::optional<url::Origin>& request_initiator_origin, NonNetworkURLLoaderFactoryMap* factories) { auto* render_process_host = content::RenderProcessHost::FromID(render_process_id); DCHECK(render_process_host); if (!render_process_host || !render_process_host->GetBrowserContext()) return; content::RenderFrameHost* frame_host = content::RenderFrameHost::FromID(render_process_id, render_frame_id); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(frame_host); // Allow accessing file:// subresources from non-file protocols if web // security is disabled. bool allow_file_access = false; if (web_contents) { const auto& web_preferences = web_contents->GetOrCreateWebPreferences(); if (!web_preferences.web_security_enabled) allow_file_access = true; } ProtocolRegistry::FromBrowserContext(render_process_host->GetBrowserContext()) ->RegisterURLLoaderFactories(factories, allow_file_access); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto factory = extensions::CreateExtensionURLLoaderFactory(render_process_id, render_frame_id); if (factory) factories->emplace(extensions::kExtensionScheme, std::move(factory)); if (!web_contents) return; extensions::ElectronExtensionWebContentsObserver* web_observer = extensions::ElectronExtensionWebContentsObserver::FromWebContents( web_contents); // There is nothing to do if no ElectronExtensionWebContentsObserver is // attached to the |web_contents|. if (!web_observer) return; const extensions::Extension* extension = web_observer->GetExtensionFromFrame(frame_host, false); if (!extension) return; // Support for chrome:// scheme if appropriate. if (extension->is_extension() && extensions::Manifest::IsComponentLocation(extension->location())) { // Components of chrome that are implemented as extensions or platform apps // are allowed to use chrome://resources/ and chrome://theme/ URLs. factories->emplace(content::kChromeUIScheme, content::CreateWebUIURLLoaderFactory( frame_host, content::kChromeUIScheme, {content::kChromeUIResourcesHost})); } // Extensions with the necessary permissions get access to file:// URLs that // gets approval from ChildProcessSecurityPolicy. Keep this logic in sync with // ExtensionWebContentsObserver::RenderFrameCreated. extensions::Manifest::Type type = extension->GetType(); if (type == extensions::Manifest::TYPE_EXTENSION && AllowFileAccess(extension->id(), web_contents->GetBrowserContext())) { factories->emplace(url::kFileScheme, FileURLLoaderFactory::Create(render_process_id)); } #endif } void ElectronBrowserClient:: RegisterNonNetworkServiceWorkerUpdateURLLoaderFactories( content::BrowserContext* browser_context, NonNetworkURLLoaderFactoryMap* factories) { DCHECK(browser_context); DCHECK(factories); #if BUILDFLAG(ENABLE_EXTENSIONS) factories->emplace( extensions::kExtensionScheme, extensions::CreateExtensionServiceWorkerScriptURLLoaderFactory( browser_context)); #endif // BUILDFLAG(ENABLE_EXTENSIONS) } bool ElectronBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel( base::StringPiece scheme, bool is_embedded_origin_secure) { if (is_embedded_origin_secure && scheme == content::kChromeUIScheme) return true; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) return scheme == extensions::kExtensionScheme; #else return false; #endif } bool ElectronBrowserClient::WillInterceptWebSocket( content::RenderFrameHost* frame) { if (!frame) return false; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); // NOTE: Some unit test environments do not initialize // BrowserContextKeyedAPI factories for e.g. WebRequest. if (!web_request.get()) return false; bool has_listener = web_request->HasListener(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) const auto* web_request_api = extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get( browser_context); if (web_request_api) has_listener |= web_request_api->MayHaveProxies(); #endif return has_listener; } void ElectronBrowserClient::CreateWebSocket( content::RenderFrameHost* frame, WebSocketFactory factory, const GURL& url, const net::SiteForCookies& site_for_cookies, const absl::optional<std::string>& user_agent, mojo::PendingRemote<network::mojom::WebSocketHandshakeClient> handshake_client) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto* browser_context = frame->GetProcess()->GetBrowserContext(); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); if (web_request_api && web_request_api->MayHaveProxies()) { web_request_api->ProxyWebSocket(frame, std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client)); return; } } #endif ProxyingWebSocket::StartProxying( web_request.get(), std::move(factory), url, site_for_cookies, user_agent, std::move(handshake_client), true, frame->GetProcess()->GetID(), frame->GetRoutingID(), frame->GetLastCommittedOrigin(), browser_context, &next_id_); } bool ElectronBrowserClient::WillCreateURLLoaderFactory( content::BrowserContext* browser_context, content::RenderFrameHost* frame_host, int render_process_id, URLLoaderFactoryType type, const url::Origin& request_initiator, absl::optional<int64_t> navigation_id, ukm::SourceIdObj ukm_source_id, mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver, mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>* header_client, bool* bypass_redirect_checks, bool* disable_secure_dns, network::mojom::URLLoaderFactoryOverridePtr* factory_override) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context); DCHECK(web_request.get()); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (!web_request->HasListener()) { auto* web_request_api = extensions::BrowserContextKeyedAPIFactory< extensions::WebRequestAPI>::Get(browser_context); DCHECK(web_request_api); bool use_proxy_for_web_request = web_request_api->MaybeProxyURLLoaderFactory( browser_context, frame_host, render_process_id, type, navigation_id, ukm_source_id, factory_receiver, header_client); if (bypass_redirect_checks) *bypass_redirect_checks = use_proxy_for_web_request; if (use_proxy_for_web_request) return true; } #endif auto proxied_receiver = std::move(*factory_receiver); mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote; *factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver(); // Required by WebRequestInfoInitParams. // // Note that in Electron we allow webRequest to capture requests sent from // browser process, so creation of |navigation_ui_data| is different from // Chromium which only does for renderer-initialized navigations. std::unique_ptr<extensions::ExtensionNavigationUIData> navigation_ui_data; if (navigation_id.has_value()) { navigation_ui_data = std::make_unique<extensions::ExtensionNavigationUIData>(); } mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient> header_client_receiver; if (header_client) header_client_receiver = header_client->InitWithNewPipeAndPassReceiver(); auto* protocol_registry = ProtocolRegistry::FromBrowserContext(browser_context); new ProxyingURLLoaderFactory( web_request.get(), protocol_registry->intercept_handlers(), render_process_id, frame_host ? frame_host->GetRoutingID() : MSG_ROUTING_NONE, frame_host ? frame_host->GetRenderViewHost()->GetRoutingID() : MSG_ROUTING_NONE, &next_id_, std::move(navigation_ui_data), std::move(navigation_id), std::move(proxied_receiver), std::move(target_factory_remote), std::move(header_client_receiver), type); if (bypass_redirect_checks) *bypass_redirect_checks = true; return true; } void ElectronBrowserClient::OverrideURLLoaderFactoryParams( content::BrowserContext* browser_context, const url::Origin& origin, bool is_for_isolated_world, network::mojom::URLLoaderFactoryParams* factory_params) { if (factory_params->top_frame_id) { // Bypass CORB and CORS when web security is disabled. auto* rfh = content::RenderFrameHost::FromFrameToken( factory_params->process_id, blink::LocalFrameToken(factory_params->top_frame_id.value())); auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); auto* prefs = WebContentsPreferences::From(web_contents); if (prefs && !prefs->IsWebSecurityEnabled()) { factory_params->is_corb_enabled = false; factory_params->disable_web_security = true; } } extensions::URLLoaderFactoryManager::OverrideURLLoaderFactoryParams( browser_context, origin, is_for_isolated_world, factory_params); } #if BUILDFLAG(IS_WIN) bool ElectronBrowserClient::PreSpawnChild(sandbox::TargetPolicy* policy, sandbox::mojom::Sandbox sandbox_type, ChildSpawnFlags flags) { // Allow crashpad to communicate via named pipe. sandbox::ResultCode result = policy->AddRule( sandbox::TargetPolicy::SUBSYS_FILES, sandbox::TargetPolicy::FILES_ALLOW_ANY, L"\\??\\pipe\\crashpad_*"); if (result != sandbox::SBOX_ALL_OK) return false; return true; } #endif // BUILDFLAG(IS_WIN) void ElectronBrowserClient:: RegisterAssociatedInterfaceBindersForRenderFrameHost( content::RenderFrameHost& render_frame_host, // NOLINT(runtime/references) blink::AssociatedInterfaceRegistry& associated_registry) { // NOLINT(runtime/references) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<electron::mojom::ElectronBrowser> receiver) { ElectronBrowserHandlerImpl::Create(render_frame_host, std::move(receiver)); }, &render_frame_host)); associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver> receiver) { AutofillDriverFactory::BindAutofillDriver(std::move(receiver), render_frame_host); }, &render_frame_host)); #if BUILDFLAG(ENABLE_PRINTING) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver) { PrintViewManagerElectron::BindPrintManagerHost(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_EXTENSIONS) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<extensions::mojom::LocalFrameHost> receiver) { extensions::ExtensionWebContentsObserver::BindLocalFrameHost( std::move(receiver), render_frame_host); }, &render_frame_host)); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) associated_registry.AddInterface(base::BindRepeating( [](content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<pdf::mojom::PdfService> receiver) { pdf::PDFWebContentsHelper::BindPdfService(std::move(receiver), render_frame_host); }, &render_frame_host)); #endif } std::string ElectronBrowserClient::GetApplicationLocale() { if (BrowserThread::CurrentlyOn(BrowserThread::IO)) return g_io_thread_application_locale.Get(); return *g_application_locale; } base::FilePath ElectronBrowserClient::GetFontLookupTableCacheDir() { base::FilePath user_data_dir; base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); DCHECK(!user_data_dir.empty()); return user_data_dir.Append(FILE_PATH_LITERAL("FontLookupTableCache")); } bool ElectronBrowserClient::ShouldEnableStrictSiteIsolation() { // Enable site isolation. It is off by default in Chromium <= 69. return true; } void ElectronBrowserClient::BindHostReceiverForRenderer( content::RenderProcessHost* render_process_host, mojo::GenericPendingReceiver receiver) { #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) if (auto host_receiver = receiver.As<spellcheck::mojom::SpellCheckHost>()) { SpellCheckHostChromeImpl::Create(render_process_host->GetID(), std::move(host_receiver)); return; } #endif } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void BindMimeHandlerService( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::MimeHandlerService> receiver) { content::WebContents* contents = content::WebContents::FromRenderFrameHost(frame_host); auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(contents); if (!guest_view) return; extensions::MimeHandlerServiceImpl::Create(guest_view->GetStreamWeakPtr(), std::move(receiver)); } void BindBeforeUnloadControl( content::RenderFrameHost* frame_host, mojo::PendingReceiver<extensions::mime_handler::BeforeUnloadControl> receiver) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host); if (!web_contents) return; auto* guest_view = extensions::MimeHandlerViewGuest::FromWebContents(web_contents); if (!guest_view) return; guest_view->FuseBeforeUnloadControl(std::move(receiver)); } #endif void ElectronBrowserClient::ExposeInterfacesToRenderer( service_manager::BinderRegistry* registry, blink::AssociatedInterfaceRegistry* associated_registry, content::RenderProcessHost* render_process_host) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) associated_registry->AddInterface(base::BindRepeating( &extensions::EventRouter::BindForRenderer, render_process_host->GetID())); associated_registry->AddInterface( base::BindRepeating(&extensions::ExtensionsGuestView::CreateForExtensions, render_process_host->GetID())); #endif } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForFrame( content::RenderFrameHost* render_frame_host, mojo::BinderMapWithContext<content::RenderFrameHost*>* map) { map->Add<network_hints::mojom::NetworkHintsHandler>( base::BindRepeating(&BindNetworkHintsHandler)); map->Add<blink::mojom::BadgeService>( base::BindRepeating(&badging::BadgeManager::BindFrameReceiver)); map->Add<blink::mojom::KeyboardLockService>(base::BindRepeating( &content::KeyboardLockServiceImpl::CreateMojoService)); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) map->Add<extensions::mime_handler::MimeHandlerService>( base::BindRepeating(&BindMimeHandlerService)); map->Add<extensions::mime_handler::BeforeUnloadControl>( base::BindRepeating(&BindBeforeUnloadControl)); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); if (!web_contents) return; const GURL& site = render_frame_host->GetSiteInstance()->GetSiteURL(); if (!site.SchemeIs(extensions::kExtensionScheme)) return; content::BrowserContext* browser_context = render_frame_host->GetProcess()->GetBrowserContext(); auto* extension = extensions::ExtensionRegistry::Get(browser_context) ->enabled_extensions() .GetByID(site.host()); if (!extension) return; extensions::ExtensionsBrowserClient::Get() ->RegisterBrowserInterfaceBindersForFrame(map, render_frame_host, extension); #endif } #if BUILDFLAG(IS_LINUX) void ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess( const base::CommandLine& command_line, int child_process_id, content::PosixFileDescriptorInfo* mappings) { int crash_signal_fd = GetCrashSignalFD(command_line); if (crash_signal_fd >= 0) { mappings->Share(kCrashDumpSignal, crash_signal_fd); } } #endif std::unique_ptr<content::LoginDelegate> ElectronBrowserClient::CreateLoginDelegate( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, const content::GlobalRequestID& request_id, bool is_main_frame, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) { return std::make_unique<LoginHandler>( auth_info, web_contents, is_main_frame, url, response_headers, first_auth_attempt, std::move(auth_required_callback)); } std::vector<std::unique_ptr<blink::URLLoaderThrottle>> ElectronBrowserClient::CreateURLLoaderThrottles( const network::ResourceRequest& request, content::BrowserContext* browser_context, const base::RepeatingCallback<content::WebContents*()>& wc_getter, content::NavigationUIData* navigation_ui_data, int frame_tree_node_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>( request.destination, frame_tree_node_id)); #endif return result; } base::flat_set<std::string> ElectronBrowserClient::GetPluginMimeTypesWithExternalHandlers( content::BrowserContext* browser_context) { base::flat_set<std::string> mime_types; #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) auto map = PluginUtils::GetMimeTypeToExtensionIdMap(browser_context); for (const auto& pair : map) mime_types.insert(pair.first); #endif return mime_types; } content::SerialDelegate* ElectronBrowserClient::GetSerialDelegate() { if (!serial_delegate_) serial_delegate_ = std::make_unique<ElectronSerialDelegate>(); return serial_delegate_.get(); } content::BluetoothDelegate* ElectronBrowserClient::GetBluetoothDelegate() { if (!bluetooth_delegate_) bluetooth_delegate_ = std::make_unique<ElectronBluetoothDelegate>(); return bluetooth_delegate_.get(); } void BindBadgeServiceForServiceWorker( const content::ServiceWorkerVersionBaseInfo& info, mojo::PendingReceiver<blink::mojom::BadgeService> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); content::RenderProcessHost* render_process_host = content::RenderProcessHost::FromID(info.process_id); if (!render_process_host) return; badging::BadgeManager::BindServiceWorkerReceiver( render_process_host, info.scope, std::move(receiver)); } void ElectronBrowserClient::RegisterBrowserInterfaceBindersForServiceWorker( mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>* map) { map->Add<blink::mojom::BadgeService>( base::BindRepeating(&BindBadgeServiceForServiceWorker)); } device::GeolocationManager* ElectronBrowserClient::GetGeolocationManager() { #if BUILDFLAG(IS_MAC) return browser_main_parts_->GetGeolocationManager(); #else return nullptr; #endif } content::HidDelegate* ElectronBrowserClient::GetHidDelegate() { if (!hid_delegate_) hid_delegate_ = std::make_unique<ElectronHidDelegate>(); return hid_delegate_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,976
[Bug]: BrowserWindow.maximize Doesn't Fire show Event for Unshown Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An unshown window becomes shown if `maximize()` is called, so a 'show' event should be fired. ### Actual Behavior A 'show' event is not fired. ### Testcase Gist URL https://gist.github.com/b86e40446891294b1d1f3cfc19202c89 ### Additional Information I've only tested this on Windows so far. On macOS, #32947 means the window isn't shown anyway, so this issue is not applicable there for the moment.
https://github.com/electron/electron/issues/32976
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-18T11:15:37Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_X11) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/window_state_watcher.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #endif #if defined(USE_OZONE) || defined(USE_X11) #include "ui/base/ui_base_features.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations)) { auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); } #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if defined(USE_X11) // Start monitoring window states. window_state_watcher_ = std::make_unique<WindowStateWatcher>(this); // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } #endif #if BUILDFLAG(IS_LINUX) if (parent) SetParentWindow(parent); #endif #if defined(USE_X11) // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_ && thick_frame_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; if (!thick_frame_ || !has_frame()) frame_style &= ~WS_CAPTION; ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_X11) const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_X11) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_X11) views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_X11) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_X11) auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_X11) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_X11) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_X11) // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); #else return false; #endif } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blured. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,976
[Bug]: BrowserWindow.maximize Doesn't Fire show Event for Unshown Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An unshown window becomes shown if `maximize()` is called, so a 'show' event should be fired. ### Actual Behavior A 'show' event is not fired. ### Testcase Gist URL https://gist.github.com/b86e40446891294b1d1f3cfc19202c89 ### Additional Information I've only tested this on Windows so far. On macOS, #32947 means the window isn't shown anyway, so this issue is not applicable there for the moment.
https://github.com/electron/electron/issues/32976
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-18T11:15:37Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); return; } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,976
[Bug]: BrowserWindow.maximize Doesn't Fire show Event for Unshown Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An unshown window becomes shown if `maximize()` is called, so a 'show' event should be fired. ### Actual Behavior A 'show' event is not fired. ### Testcase Gist URL https://gist.github.com/b86e40446891294b1d1f3cfc19202c89 ### Additional Information I've only tested this on Windows so far. On macOS, #32947 means the window isn't shown anyway, so this issue is not applicable there for the moment.
https://github.com/electron/electron/issues/32976
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-18T11:15:37Z
c++
2022-03-09T22:30:42Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,947
[Bug]: BrowserWindow.maximize Does Not Show Window on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? macOS ### Operating System Version macOS 11.6.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Maximizing a window which isn't being shown should show the window. According to the docs for `BrowserWindow.maximize()`: > Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. ### Actual Behavior On macOS, the window is not shown, but `window.isMaximized()` returns true, and a subsequent `window.show()` will show a maximized window as expected. ### Testcase Gist URL https://gist.github.com/09e5ef031f69be2cce1e23c5174d6e5b ### Additional Information Tested on Windows 10 and Ubuntu and it works as expected, so this looks to be just macOS.
https://github.com/electron/electron/issues/32947
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-17T06:18:21Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_X11) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/window_state_watcher.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #endif #if defined(USE_OZONE) || defined(USE_X11) #include "ui/base/ui_base_features.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations)) { auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); } #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if defined(USE_X11) // Start monitoring window states. window_state_watcher_ = std::make_unique<WindowStateWatcher>(this); // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } #endif #if BUILDFLAG(IS_LINUX) if (parent) SetParentWindow(parent); #endif #if defined(USE_X11) // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_ && thick_frame_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; if (!thick_frame_ || !has_frame()) frame_style &= ~WS_CAPTION; ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_X11) const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_X11) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_X11) views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_X11) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_X11) auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_X11) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_X11) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_X11) // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); #else return false; #endif } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blured. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,947
[Bug]: BrowserWindow.maximize Does Not Show Window on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? macOS ### Operating System Version macOS 11.6.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Maximizing a window which isn't being shown should show the window. According to the docs for `BrowserWindow.maximize()`: > Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. ### Actual Behavior On macOS, the window is not shown, but `window.isMaximized()` returns true, and a subsequent `window.show()` will show a maximized window as expected. ### Testcase Gist URL https://gist.github.com/09e5ef031f69be2cce1e23c5174d6e5b ### Additional Information Tested on Windows 10 and Ubuntu and it works as expected, so this looks to be just macOS.
https://github.com/electron/electron/issues/32947
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-17T06:18:21Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); return; } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,947
[Bug]: BrowserWindow.maximize Does Not Show Window on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? macOS ### Operating System Version macOS 11.6.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Maximizing a window which isn't being shown should show the window. According to the docs for `BrowserWindow.maximize()`: > Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. ### Actual Behavior On macOS, the window is not shown, but `window.isMaximized()` returns true, and a subsequent `window.show()` will show a maximized window as expected. ### Testcase Gist URL https://gist.github.com/09e5ef031f69be2cce1e23c5174d6e5b ### Additional Information Tested on Windows 10 and Ubuntu and it works as expected, so this looks to be just macOS.
https://github.com/electron/electron/issues/32947
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-17T06:18:21Z
c++
2022-03-09T22:30:42Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,976
[Bug]: BrowserWindow.maximize Doesn't Fire show Event for Unshown Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An unshown window becomes shown if `maximize()` is called, so a 'show' event should be fired. ### Actual Behavior A 'show' event is not fired. ### Testcase Gist URL https://gist.github.com/b86e40446891294b1d1f3cfc19202c89 ### Additional Information I've only tested this on Windows so far. On macOS, #32947 means the window isn't shown anyway, so this issue is not applicable there for the moment.
https://github.com/electron/electron/issues/32976
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-18T11:15:37Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_X11) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/window_state_watcher.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #endif #if defined(USE_OZONE) || defined(USE_X11) #include "ui/base/ui_base_features.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations)) { auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); } #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if defined(USE_X11) // Start monitoring window states. window_state_watcher_ = std::make_unique<WindowStateWatcher>(this); // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } #endif #if BUILDFLAG(IS_LINUX) if (parent) SetParentWindow(parent); #endif #if defined(USE_X11) // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_ && thick_frame_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; if (!thick_frame_ || !has_frame()) frame_style &= ~WS_CAPTION; ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_X11) const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_X11) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_X11) views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_X11) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_X11) auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_X11) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_X11) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_X11) // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); #else return false; #endif } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blured. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,976
[Bug]: BrowserWindow.maximize Doesn't Fire show Event for Unshown Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An unshown window becomes shown if `maximize()` is called, so a 'show' event should be fired. ### Actual Behavior A 'show' event is not fired. ### Testcase Gist URL https://gist.github.com/b86e40446891294b1d1f3cfc19202c89 ### Additional Information I've only tested this on Windows so far. On macOS, #32947 means the window isn't shown anyway, so this issue is not applicable there for the moment.
https://github.com/electron/electron/issues/32976
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-18T11:15:37Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); return; } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,976
[Bug]: BrowserWindow.maximize Doesn't Fire show Event for Unshown Window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior An unshown window becomes shown if `maximize()` is called, so a 'show' event should be fired. ### Actual Behavior A 'show' event is not fired. ### Testcase Gist URL https://gist.github.com/b86e40446891294b1d1f3cfc19202c89 ### Additional Information I've only tested this on Windows so far. On macOS, #32947 means the window isn't shown anyway, so this issue is not applicable there for the moment.
https://github.com/electron/electron/issues/32976
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-18T11:15:37Z
c++
2022-03-09T22:30:42Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,947
[Bug]: BrowserWindow.maximize Does Not Show Window on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? macOS ### Operating System Version macOS 11.6.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Maximizing a window which isn't being shown should show the window. According to the docs for `BrowserWindow.maximize()`: > Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. ### Actual Behavior On macOS, the window is not shown, but `window.isMaximized()` returns true, and a subsequent `window.show()` will show a maximized window as expected. ### Testcase Gist URL https://gist.github.com/09e5ef031f69be2cce1e23c5174d6e5b ### Additional Information Tested on Windows 10 and Ubuntu and it works as expected, so this looks to be just macOS.
https://github.com/electron/electron/issues/32947
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-17T06:18:21Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/native_window_features.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_X11) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/window_state_watcher.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #endif #if defined(USE_OZONE) || defined(USE_X11) #include "ui/base/ui_base_features.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; if (base::FeatureList::IsEnabled(features::kWaylandWindowDecorations)) { auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); } #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if defined(USE_X11) // Start monitoring window states. window_state_watcher_ = std::make_unique<WindowStateWatcher>(this); // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } #endif #if BUILDFLAG(IS_LINUX) if (parent) SetParentWindow(parent); #endif #if defined(USE_X11) // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_ && thick_frame_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; if (!thick_frame_ || !has_frame()) frame_style &= ~WS_CAPTION; ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_X11) const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_X11) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_X11) views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_X11) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_X11) auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_X11) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_X11) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_X11) // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); #else return false; #endif } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blured. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,947
[Bug]: BrowserWindow.maximize Does Not Show Window on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? macOS ### Operating System Version macOS 11.6.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Maximizing a window which isn't being shown should show the window. According to the docs for `BrowserWindow.maximize()`: > Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. ### Actual Behavior On macOS, the window is not shown, but `window.isMaximized()` returns true, and a subsequent `window.show()` will show a maximized window as expected. ### Testcase Gist URL https://gist.github.com/09e5ef031f69be2cce1e23c5174d6e5b ### Additional Information Tested on Windows 10 and Ubuntu and it works as expected, so this looks to be just macOS.
https://github.com/electron/electron/issues/32947
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-17T06:18:21Z
c++
2022-03-09T22:30:42Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); return; } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,947
[Bug]: BrowserWindow.maximize Does Not Show Window on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220209 ### What operating system are you using? macOS ### Operating System Version macOS 11.6.2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Maximizing a window which isn't being shown should show the window. According to the docs for `BrowserWindow.maximize()`: > Maximizes the window. This will also show (but not focus) the window if it isn't being displayed already. ### Actual Behavior On macOS, the window is not shown, but `window.isMaximized()` returns true, and a subsequent `window.show()` will show a maximized window as expected. ### Testcase Gist URL https://gist.github.com/09e5ef031f69be2cce1e23c5174d6e5b ### Additional Information Tested on Windows 10 and Ubuntu and it works as expected, so this looks to be just macOS.
https://github.com/electron/electron/issues/32947
https://github.com/electron/electron/pull/32979
86e746c36b20c54c8e77d3d65bc9470b247b232c
e589e9b259ecad5a2f2f47f0b8d40618d1c54601
2022-02-17T06:18:21Z
c++
2022-03-09T22:30:42Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as os from 'os'; import * as qs from 'querystring'; import * as http from 'http'; import * as semver from 'semver'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', () => { w.show(); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', () => { w.show(); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.blur()', () => { it('removes focus from window', () => { w.blur(); expect(w.isFocused()).to.equal(false); }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { w.show(); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(process.platform === 'win32' || (process.platform === 'darwin' && semver.gte(os.release(), '14.0.0')))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); await w.maximize(); const max = await w.isMaximized(); expect(max).to.equal(true); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(closeAllWindows); afterEach(() => { ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isoalted renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true } } })); w.webContents.once('new-window', (event, url, frameName, disposition, options) => { options.show = false; }); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to true and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.true('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
33,049
[Bug]: Adding/Removing Display Changes Window Size
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Adding or removing a display will not change the size of a `BrowserWindow`. ### Actual Behavior Adding or removing a display does change the size of a `BrowserWindow`. ### Testcase Gist URL https://gist.github.com/7f8c673311b123fa4f7fe3444b4d0fea ### Additional Information Gist of course will only work if you have a second monitor to test with - it uses the 'display-added' event. On Windows the width and height of a window shrinks by 1 pixel every time a display is added or removed. Other platforms are not affected.
https://github.com/electron/electron/issues/33049
https://github.com/electron/electron/pull/33109
dc63b8e7f478ad87bcde0406508c1fbbcf4b872c
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
2022-02-23T07:17:04Z
c++
2022-03-11T17:19:51Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cfisobjc.patch mas-cgdisplayusesforcetogray.patch mas-audiodeviceduck.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_abort_report_np.patch mas_avoid_usage_of_pthread_fchdir_np.patch mas_avoid_usage_of_setapplicationisdaemon_and.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch chore_use_electron_resources_not_chrome_for_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch ui_gtk_public_header.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch fix_use_electron_generated_resources.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch mas_gate_private_enterprise_APIs.patch load_v8_snapshot_in_browser_process.patch fix_patch_out_permissions_checks_in_exclusive_access.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch feat_add_data_transfer_to_requestsingleinstancelock.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch build_disable_thin_lto_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch
closed
electron/electron
https://github.com/electron/electron
33,049
[Bug]: Adding/Removing Display Changes Window Size
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Adding or removing a display will not change the size of a `BrowserWindow`. ### Actual Behavior Adding or removing a display does change the size of a `BrowserWindow`. ### Testcase Gist URL https://gist.github.com/7f8c673311b123fa4f7fe3444b4d0fea ### Additional Information Gist of course will only work if you have a second monitor to test with - it uses the 'display-added' event. On Windows the width and height of a window shrinks by 1 pixel every time a display is added or removed. Other platforms are not affected.
https://github.com/electron/electron/issues/33049
https://github.com/electron/electron/pull/33109
dc63b8e7f478ad87bcde0406508c1fbbcf4b872c
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
2022-02-23T07:17:04Z
c++
2022-03-11T17:19:51Z
patches/chromium/remove_incorrect_width_height_adjustments.patch
closed
electron/electron
https://github.com/electron/electron
33,049
[Bug]: Adding/Removing Display Changes Window Size
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Adding or removing a display will not change the size of a `BrowserWindow`. ### Actual Behavior Adding or removing a display does change the size of a `BrowserWindow`. ### Testcase Gist URL https://gist.github.com/7f8c673311b123fa4f7fe3444b4d0fea ### Additional Information Gist of course will only work if you have a second monitor to test with - it uses the 'display-added' event. On Windows the width and height of a window shrinks by 1 pixel every time a display is added or removed. Other platforms are not affected.
https://github.com/electron/electron/issues/33049
https://github.com/electron/electron/pull/33109
dc63b8e7f478ad87bcde0406508c1fbbcf4b872c
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
2022-02-23T07:17:04Z
c++
2022-03-11T17:19:51Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cfisobjc.patch mas-cgdisplayusesforcetogray.patch mas-audiodeviceduck.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_abort_report_np.patch mas_avoid_usage_of_pthread_fchdir_np.patch mas_avoid_usage_of_setapplicationisdaemon_and.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch chore_use_electron_resources_not_chrome_for_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch ui_gtk_public_header.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch fix_use_electron_generated_resources.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch mas_gate_private_enterprise_APIs.patch load_v8_snapshot_in_browser_process.patch fix_patch_out_permissions_checks_in_exclusive_access.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch feat_add_data_transfer_to_requestsingleinstancelock.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch build_disable_thin_lto_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch
closed
electron/electron
https://github.com/electron/electron
33,049
[Bug]: Adding/Removing Display Changes Window Size
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.0-nightly.20220207 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Adding or removing a display will not change the size of a `BrowserWindow`. ### Actual Behavior Adding or removing a display does change the size of a `BrowserWindow`. ### Testcase Gist URL https://gist.github.com/7f8c673311b123fa4f7fe3444b4d0fea ### Additional Information Gist of course will only work if you have a second monitor to test with - it uses the 'display-added' event. On Windows the width and height of a window shrinks by 1 pixel every time a display is added or removed. Other platforms are not affected.
https://github.com/electron/electron/issues/33049
https://github.com/electron/electron/pull/33109
dc63b8e7f478ad87bcde0406508c1fbbcf4b872c
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
2022-02-23T07:17:04Z
c++
2022-03-11T17:19:51Z
patches/chromium/remove_incorrect_width_height_adjustments.patch
closed
electron/electron
https://github.com/electron/electron
31,675
[Bug]: Network service crashed, restarting service.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.0.2 ### What operating system are you using? Ubuntu ### Operating System Version Linux rrouwprlc0068 5.4.0-89-generic #100-Ubuntu SMP Fri Sep 24 14:50:10 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux, Ubuntu 20.04.3 LTS, GNOME Version 3.36.8, OS Type 64-bit ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Network service should not crash and the error `[15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service.`, to not appear in the logs. ### Actual Behavior Sporadically, when I run Electron inside a Docker container, I get the following error: [15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service. Which causes partially rendering of the front-end application that is loaded with `win.loadURL` on localhost. The issue seems very similar to https://bbs.archlinux.org/viewtopic.php?id=268123, but nothing from the suggestions works consinstently. Also, when closing the Electron window, I get an error Error: ERR_FAILED (-2) loading 'https://localhost:{port}/{path_to}/index.html' at rejectAndCleanup (node:electron/js2c/browser_init:165:7486) at Object.stopLoadingListener (node:electron/js2c/browser_init:165:7861) at Object.emit (node:events:394:28) { errno: -2, code: 'ERR_FAILED', url: 'https://localhost:{port}/{path_to}/index.html' } [EOL] Which is caught inside the main.js when executing await `win.loadURL(url)` Also, in the browser window console, there is an error: ERROR Error: Uncaught (in promise): ChunkLoadError: Loading chunk 108 failed. (timeout: https://localhost:{port}/{path_to}/108.da4993913b4a27951976.js) ChunkLoadError: Loading chunk 108 failed. Any ideas on the issue? ### Testcase Gist URL _No response_ ### Additional Information Chromedriver 95.0.0 v
https://github.com/electron/electron/issues/31675
https://github.com/electron/electron/pull/33204
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
cdc27a3793958de4a2c06e7fce16244b6f0cb354
2021-11-02T16:03:22Z
c++
2022-03-11T19:35:48Z
patches/chromium/expose_setuseragent_on_networkcontext.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Apthorp <[email protected]> Date: Wed, 28 Aug 2019 12:21:25 -0700 Subject: expose SetUserAgent on NetworkContext Applying https://chromium-review.googlesource.com/c/chromium/src/+/1585083 before it's merged. There may end up being a better way of doing this, or the patch may be merged upstream, at which point this patch should be removed. diff --git a/net/url_request/static_http_user_agent_settings.h b/net/url_request/static_http_user_agent_settings.h index 14c71cc69388da46f62d9835e2a06fef0870da02..9481ea08401ae29ae9c1d960491b05b364257cc8 100644 --- a/net/url_request/static_http_user_agent_settings.h +++ b/net/url_request/static_http_user_agent_settings.h @@ -30,13 +30,17 @@ class NET_EXPORT StaticHttpUserAgentSettings : public HttpUserAgentSettings { accept_language_ = new_accept_language; } + void set_user_agent(const std::string& new_user_agent) { + user_agent_ = new_user_agent; + } + // HttpUserAgentSettings implementation std::string GetAcceptLanguage() const override; std::string GetUserAgent() const override; private: std::string accept_language_; - const std::string user_agent_; + std::string user_agent_; }; } // namespace net diff --git a/services/network/network_context.cc b/services/network/network_context.cc index ca62a13420aa9c114c00054bbe1215f96285a4e9..01be46b1eaed2aadfd24eac9d102da99521b175c 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc @@ -1331,6 +1331,13 @@ void NetworkContext::SetNetworkConditions( std::move(network_conditions)); } +void NetworkContext::SetUserAgent(const std::string& new_user_agent) { + // This may only be called on NetworkContexts created with a constructor that + // calls ApplyContextParamsToBuilder. + DCHECK(user_agent_settings_); + user_agent_settings_->set_user_agent(new_user_agent); +} + void NetworkContext::SetAcceptLanguage(const std::string& new_accept_language) { // This may only be called on NetworkContexts created with the constructor // that calls MakeURLRequestContext(). diff --git a/services/network/network_context.h b/services/network/network_context.h index e412608e7720004462c48698c8ec39602b2b900e..46c00e0da6beb0c2e689475fc4b9927085414e1a 100644 --- a/services/network/network_context.h +++ b/services/network/network_context.h @@ -282,6 +282,7 @@ class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext void CloseIdleConnections(CloseIdleConnectionsCallback callback) override; void SetNetworkConditions(const base::UnguessableToken& throttling_profile_id, mojom::NetworkConditionsPtr conditions) override; + void SetUserAgent(const std::string& new_user_agent) override; void SetAcceptLanguage(const std::string& new_accept_language) override; void SetEnableReferrers(bool enable_referrers) override; #if BUILDFLAG(IS_CHROMEOS) diff --git a/services/network/public/mojom/network_context.mojom b/services/network/public/mojom/network_context.mojom index fa56cfed3703664232843ad26028096d95dca253..9852498e93939796e7ba6f80efcc7b2d827187ac 100644 --- a/services/network/public/mojom/network_context.mojom +++ b/services/network/public/mojom/network_context.mojom @@ -1067,6 +1067,9 @@ interface NetworkContext { SetNetworkConditions(mojo_base.mojom.UnguessableToken throttling_profile_id, NetworkConditions? conditions); + // Updates the user agent to be used for requests. + SetUserAgent(string new_user_agent); + // Updates the Accept-Language header to be used for requests. SetAcceptLanguage(string new_accept_language); diff --git a/services/network/test/test_network_context.h b/services/network/test/test_network_context.h index d143a82b1fd021bb03b760b91e87c7714f5395b9..3c18369ff3ab80430e21caac03373605dad64a88 100644 --- a/services/network/test/test_network_context.h +++ b/services/network/test/test_network_context.h @@ -136,6 +136,7 @@ class TestNetworkContext : public mojom::NetworkContext { void CloseIdleConnections(CloseIdleConnectionsCallback callback) override {} void SetNetworkConditions(const base::UnguessableToken& throttling_profile_id, mojom::NetworkConditionsPtr conditions) override {} + void SetUserAgent(const std::string& new_user_agent) override {} void SetAcceptLanguage(const std::string& new_accept_language) override {} void SetEnableReferrers(bool enable_referrers) override {} #if BUILDFLAG(IS_CHROMEOS)
closed
electron/electron
https://github.com/electron/electron
31,675
[Bug]: Network service crashed, restarting service.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.0.2 ### What operating system are you using? Ubuntu ### Operating System Version Linux rrouwprlc0068 5.4.0-89-generic #100-Ubuntu SMP Fri Sep 24 14:50:10 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux, Ubuntu 20.04.3 LTS, GNOME Version 3.36.8, OS Type 64-bit ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Network service should not crash and the error `[15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service.`, to not appear in the logs. ### Actual Behavior Sporadically, when I run Electron inside a Docker container, I get the following error: [15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service. Which causes partially rendering of the front-end application that is loaded with `win.loadURL` on localhost. The issue seems very similar to https://bbs.archlinux.org/viewtopic.php?id=268123, but nothing from the suggestions works consinstently. Also, when closing the Electron window, I get an error Error: ERR_FAILED (-2) loading 'https://localhost:{port}/{path_to}/index.html' at rejectAndCleanup (node:electron/js2c/browser_init:165:7486) at Object.stopLoadingListener (node:electron/js2c/browser_init:165:7861) at Object.emit (node:events:394:28) { errno: -2, code: 'ERR_FAILED', url: 'https://localhost:{port}/{path_to}/index.html' } [EOL] Which is caught inside the main.js when executing await `win.loadURL(url)` Also, in the browser window console, there is an error: ERROR Error: Uncaught (in promise): ChunkLoadError: Loading chunk 108 failed. (timeout: https://localhost:{port}/{path_to}/108.da4993913b4a27951976.js) ChunkLoadError: Loading chunk 108 failed. Any ideas on the issue? ### Testcase Gist URL _No response_ ### Additional Information Chromedriver 95.0.0 v
https://github.com/electron/electron/issues/31675
https://github.com/electron/electron/pull/33204
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
cdc27a3793958de4a2c06e7fce16244b6f0cb354
2021-11-02T16:03:22Z
c++
2022-03-11T19:35:48Z
patches/chromium/network_service_allow_remote_certificate_verification_logic.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Apthorp <[email protected]> Date: Wed, 8 May 2019 17:25:55 -0700 Subject: network_service_allow_remote_certificate_verification_logic.patch This adds a callback from the network service that's used to implement session.setCertificateVerifyCallback. diff --git a/services/network/network_context.cc b/services/network/network_context.cc index 8ff62f92ed6efdbfc18db53db3c5bb59c1acfe34..ca62a13420aa9c114c00054bbe1215f96285a4e9 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc @@ -126,6 +126,11 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" +// Electron +#include "net/cert/caching_cert_verifier.h" +#include "net/cert/cert_verify_proc.h" +#include "net/cert/multi_threaded_cert_verifier.h" + #if BUILDFLAG(IS_CT_SUPPORTED) #include "components/certificate_transparency/chrome_ct_policy_enforcer.h" #include "components/certificate_transparency/chrome_require_ct_delegate.h" @@ -433,6 +438,79 @@ bool GetFullDataFilePath( } // namespace +class RemoteCertVerifier : public net::CertVerifier { + public: + RemoteCertVerifier(std::unique_ptr<net::CertVerifier> upstream): upstream_(std::move(upstream)) { + } + ~RemoteCertVerifier() override = default; + + void Bind( + mojo::PendingRemote<mojom::CertVerifierClient> client_info) { + client_.reset(); + if (client_info.is_valid()) { + client_.Bind(std::move(client_info)); + } + } + + // CertVerifier implementation + int Verify(const RequestParams& params, + net::CertVerifyResult* verify_result, + net::CompletionOnceCallback callback, + std::unique_ptr<Request>* out_req, + const net::NetLogWithSource& net_log) override { + out_req->reset(); + + net::CompletionOnceCallback callback2 = base::BindOnce( + &RemoteCertVerifier::OnRequestFinished, base::Unretained(this), + params, std::move(callback), verify_result); + int result = upstream_->Verify(params, verify_result, + std::move(callback2), out_req, net_log); + if (result != net::ERR_IO_PENDING) { + // Synchronous completion + } + + return result; + } + + + void SetConfig(const Config& config) override { + upstream_->SetConfig(config); + } + + void OnRequestFinished(const RequestParams& params, net::CompletionOnceCallback callback, net::CertVerifyResult* verify_result, int error) { + if (client_.is_bound()) { + client_->Verify(error, *verify_result, params.certificate(), + params.hostname(), params.flags(), params.ocsp_response(), + base::BindOnce(&RemoteCertVerifier::OnRemoteResponse, + base::Unretained(this), params, verify_result, error, + std::move(callback))); + } else { + std::move(callback).Run(error); + } + } + + void OnRemoteResponse( + const RequestParams& params, + net::CertVerifyResult* verify_result, + int error, + net::CompletionOnceCallback callback, + int error2, + const net::CertVerifyResult& verify_result2) { + if (error2 == net::ERR_ABORTED) { + // use the default + std::move(callback).Run(error); + } else { + // use the override + verify_result->Reset(); + verify_result->verified_cert = verify_result2.verified_cert; + std::move(callback).Run(error2); + } + } + private: + std::unique_ptr<net::CertVerifier> upstream_; + mojo::Remote<mojom::CertVerifierClient> client_; +}; + constexpr uint32_t NetworkContext::kMaxOutstandingRequestsPerProcess; NetworkContext::PendingCertVerify::PendingCertVerify() = default; @@ -671,6 +749,13 @@ void NetworkContext::SetClient( client_.Bind(std::move(client)); } +void NetworkContext::SetCertVerifierClient( + mojo::PendingRemote<mojom::CertVerifierClient> client) { + if (remote_cert_verifier_) { + remote_cert_verifier_->Bind(std::move(client)); + } +} + void NetworkContext::CreateURLLoaderFactory( mojo::PendingReceiver<mojom::URLLoaderFactory> receiver, mojom::URLLoaderFactoryParamsPtr params) { @@ -2226,6 +2311,9 @@ URLRequestContextOwner NetworkContext::MakeURLRequestContext( std::move(cert_verifier)); cert_verifier = base::WrapUnique(cert_verifier_with_trust_anchors_); #endif // BUILDFLAG(IS_CHROMEOS) + auto remote_cert_verifier = std::make_unique<RemoteCertVerifier>(std::move(cert_verifier)); + remote_cert_verifier_ = remote_cert_verifier.get(); + cert_verifier = std::make_unique<net::CachingCertVerifier>(std::move(remote_cert_verifier)); } builder.SetCertVerifier(IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( diff --git a/services/network/network_context.h b/services/network/network_context.h index 6de81678e62d6921d0df5944ab01705402caa568..e412608e7720004462c48698c8ec39602b2b900e 100644 --- a/services/network/network_context.h +++ b/services/network/network_context.h @@ -105,6 +105,7 @@ class URLMatcher; namespace network { class CertVerifierWithTrustAnchors; +class RemoteCertVerifier; class CookieManager; class ExpectCTReporter; class HostResolver; @@ -220,6 +221,8 @@ class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext void CreateURLLoaderFactory( mojo::PendingReceiver<mojom::URLLoaderFactory> receiver, mojom::URLLoaderFactoryParamsPtr params) override; + void SetCertVerifierClient( + mojo::PendingRemote<mojom::CertVerifierClient> client) override; void ResetURLLoaderFactories() override; void GetCookieManager( mojo::PendingReceiver<mojom::CookieManager> receiver) override; @@ -793,6 +796,8 @@ class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext CertVerifierWithTrustAnchors* cert_verifier_with_trust_anchors_ = nullptr; #endif + RemoteCertVerifier* remote_cert_verifier_ = nullptr; + // CertNetFetcher used by the context's CertVerifier. May be nullptr if // CertNetFetcher is not used by the current platform, or if the actual // net::CertVerifier is instantiated outside of the network service. diff --git a/services/network/public/mojom/network_context.mojom b/services/network/public/mojom/network_context.mojom index 9cd06ee552f8e592dd9efd1e73b10e5998559c04..fa56cfed3703664232843ad26028096d95dca253 100644 --- a/services/network/public/mojom/network_context.mojom +++ b/services/network/public/mojom/network_context.mojom @@ -277,6 +277,17 @@ struct NetworkContextFilePaths { bool trigger_migration = false; }; +interface CertVerifierClient { + Verify( + int32 default_error, + CertVerifyResult default_result, + X509Certificate certificate, + string hostname, + int32 flags, + string? ocsp_response + ) => (int32 error_code, CertVerifyResult result); +}; + // Parameters for constructing a network context. struct NetworkContextParams { // The user agent string. @@ -807,6 +818,9 @@ interface NetworkContext { // Sets a client for this network context. SetClient(pending_remote<NetworkContextClient> client); + // Sets a certificate verifier client for this network context. + SetCertVerifierClient(pending_remote<CertVerifierClient>? client); + // Creates a new URLLoaderFactory with the given |params|. CreateURLLoaderFactory(pending_receiver<URLLoaderFactory> url_loader_factory, URLLoaderFactoryParams params);
closed
electron/electron
https://github.com/electron/electron
31,675
[Bug]: Network service crashed, restarting service.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.0.2 ### What operating system are you using? Ubuntu ### Operating System Version Linux rrouwprlc0068 5.4.0-89-generic #100-Ubuntu SMP Fri Sep 24 14:50:10 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux, Ubuntu 20.04.3 LTS, GNOME Version 3.36.8, OS Type 64-bit ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Network service should not crash and the error `[15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service.`, to not appear in the logs. ### Actual Behavior Sporadically, when I run Electron inside a Docker container, I get the following error: [15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service. Which causes partially rendering of the front-end application that is loaded with `win.loadURL` on localhost. The issue seems very similar to https://bbs.archlinux.org/viewtopic.php?id=268123, but nothing from the suggestions works consinstently. Also, when closing the Electron window, I get an error Error: ERR_FAILED (-2) loading 'https://localhost:{port}/{path_to}/index.html' at rejectAndCleanup (node:electron/js2c/browser_init:165:7486) at Object.stopLoadingListener (node:electron/js2c/browser_init:165:7861) at Object.emit (node:events:394:28) { errno: -2, code: 'ERR_FAILED', url: 'https://localhost:{port}/{path_to}/index.html' } [EOL] Which is caught inside the main.js when executing await `win.loadURL(url)` Also, in the browser window console, there is an error: ERROR Error: Uncaught (in promise): ChunkLoadError: Loading chunk 108 failed. (timeout: https://localhost:{port}/{path_to}/108.da4993913b4a27951976.js) ChunkLoadError: Loading chunk 108 failed. Any ideas on the issue? ### Testcase Gist URL _No response_ ### Additional Information Chromedriver 95.0.0 v
https://github.com/electron/electron/issues/31675
https://github.com/electron/electron/pull/33204
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
cdc27a3793958de4a2c06e7fce16244b6f0cb354
2021-11-02T16:03:22Z
c++
2022-03-11T19:35:48Z
patches/chromium/expose_setuseragent_on_networkcontext.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Apthorp <[email protected]> Date: Wed, 28 Aug 2019 12:21:25 -0700 Subject: expose SetUserAgent on NetworkContext Applying https://chromium-review.googlesource.com/c/chromium/src/+/1585083 before it's merged. There may end up being a better way of doing this, or the patch may be merged upstream, at which point this patch should be removed. diff --git a/net/url_request/static_http_user_agent_settings.h b/net/url_request/static_http_user_agent_settings.h index 14c71cc69388da46f62d9835e2a06fef0870da02..9481ea08401ae29ae9c1d960491b05b364257cc8 100644 --- a/net/url_request/static_http_user_agent_settings.h +++ b/net/url_request/static_http_user_agent_settings.h @@ -30,13 +30,17 @@ class NET_EXPORT StaticHttpUserAgentSettings : public HttpUserAgentSettings { accept_language_ = new_accept_language; } + void set_user_agent(const std::string& new_user_agent) { + user_agent_ = new_user_agent; + } + // HttpUserAgentSettings implementation std::string GetAcceptLanguage() const override; std::string GetUserAgent() const override; private: std::string accept_language_; - const std::string user_agent_; + std::string user_agent_; }; } // namespace net diff --git a/services/network/network_context.cc b/services/network/network_context.cc index ca62a13420aa9c114c00054bbe1215f96285a4e9..01be46b1eaed2aadfd24eac9d102da99521b175c 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc @@ -1331,6 +1331,13 @@ void NetworkContext::SetNetworkConditions( std::move(network_conditions)); } +void NetworkContext::SetUserAgent(const std::string& new_user_agent) { + // This may only be called on NetworkContexts created with a constructor that + // calls ApplyContextParamsToBuilder. + DCHECK(user_agent_settings_); + user_agent_settings_->set_user_agent(new_user_agent); +} + void NetworkContext::SetAcceptLanguage(const std::string& new_accept_language) { // This may only be called on NetworkContexts created with the constructor // that calls MakeURLRequestContext(). diff --git a/services/network/network_context.h b/services/network/network_context.h index e412608e7720004462c48698c8ec39602b2b900e..46c00e0da6beb0c2e689475fc4b9927085414e1a 100644 --- a/services/network/network_context.h +++ b/services/network/network_context.h @@ -282,6 +282,7 @@ class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext void CloseIdleConnections(CloseIdleConnectionsCallback callback) override; void SetNetworkConditions(const base::UnguessableToken& throttling_profile_id, mojom::NetworkConditionsPtr conditions) override; + void SetUserAgent(const std::string& new_user_agent) override; void SetAcceptLanguage(const std::string& new_accept_language) override; void SetEnableReferrers(bool enable_referrers) override; #if BUILDFLAG(IS_CHROMEOS) diff --git a/services/network/public/mojom/network_context.mojom b/services/network/public/mojom/network_context.mojom index fa56cfed3703664232843ad26028096d95dca253..9852498e93939796e7ba6f80efcc7b2d827187ac 100644 --- a/services/network/public/mojom/network_context.mojom +++ b/services/network/public/mojom/network_context.mojom @@ -1067,6 +1067,9 @@ interface NetworkContext { SetNetworkConditions(mojo_base.mojom.UnguessableToken throttling_profile_id, NetworkConditions? conditions); + // Updates the user agent to be used for requests. + SetUserAgent(string new_user_agent); + // Updates the Accept-Language header to be used for requests. SetAcceptLanguage(string new_accept_language); diff --git a/services/network/test/test_network_context.h b/services/network/test/test_network_context.h index d143a82b1fd021bb03b760b91e87c7714f5395b9..3c18369ff3ab80430e21caac03373605dad64a88 100644 --- a/services/network/test/test_network_context.h +++ b/services/network/test/test_network_context.h @@ -136,6 +136,7 @@ class TestNetworkContext : public mojom::NetworkContext { void CloseIdleConnections(CloseIdleConnectionsCallback callback) override {} void SetNetworkConditions(const base::UnguessableToken& throttling_profile_id, mojom::NetworkConditionsPtr conditions) override {} + void SetUserAgent(const std::string& new_user_agent) override {} void SetAcceptLanguage(const std::string& new_accept_language) override {} void SetEnableReferrers(bool enable_referrers) override {} #if BUILDFLAG(IS_CHROMEOS)
closed
electron/electron
https://github.com/electron/electron
31,675
[Bug]: Network service crashed, restarting service.
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 15.0.2 ### What operating system are you using? Ubuntu ### Operating System Version Linux rrouwprlc0068 5.4.0-89-generic #100-Ubuntu SMP Fri Sep 24 14:50:10 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux, Ubuntu 20.04.3 LTS, GNOME Version 3.36.8, OS Type 64-bit ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Network service should not crash and the error `[15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service.`, to not appear in the logs. ### Actual Behavior Sporadically, when I run Electron inside a Docker container, I get the following error: [15:1102/154337.143944:ERROR:network_service_instance_impl.cc(333)] Network service crashed, restarting service. Which causes partially rendering of the front-end application that is loaded with `win.loadURL` on localhost. The issue seems very similar to https://bbs.archlinux.org/viewtopic.php?id=268123, but nothing from the suggestions works consinstently. Also, when closing the Electron window, I get an error Error: ERR_FAILED (-2) loading 'https://localhost:{port}/{path_to}/index.html' at rejectAndCleanup (node:electron/js2c/browser_init:165:7486) at Object.stopLoadingListener (node:electron/js2c/browser_init:165:7861) at Object.emit (node:events:394:28) { errno: -2, code: 'ERR_FAILED', url: 'https://localhost:{port}/{path_to}/index.html' } [EOL] Which is caught inside the main.js when executing await `win.loadURL(url)` Also, in the browser window console, there is an error: ERROR Error: Uncaught (in promise): ChunkLoadError: Loading chunk 108 failed. (timeout: https://localhost:{port}/{path_to}/108.da4993913b4a27951976.js) ChunkLoadError: Loading chunk 108 failed. Any ideas on the issue? ### Testcase Gist URL _No response_ ### Additional Information Chromedriver 95.0.0 v
https://github.com/electron/electron/issues/31675
https://github.com/electron/electron/pull/33204
bbb79880f7016c156c8fad3c08b59caa0eedd8a7
cdc27a3793958de4a2c06e7fce16244b6f0cb354
2021-11-02T16:03:22Z
c++
2022-03-11T19:35:48Z
patches/chromium/network_service_allow_remote_certificate_verification_logic.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Apthorp <[email protected]> Date: Wed, 8 May 2019 17:25:55 -0700 Subject: network_service_allow_remote_certificate_verification_logic.patch This adds a callback from the network service that's used to implement session.setCertificateVerifyCallback. diff --git a/services/network/network_context.cc b/services/network/network_context.cc index 8ff62f92ed6efdbfc18db53db3c5bb59c1acfe34..ca62a13420aa9c114c00054bbe1215f96285a4e9 100644 --- a/services/network/network_context.cc +++ b/services/network/network_context.cc @@ -126,6 +126,11 @@ #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" +// Electron +#include "net/cert/caching_cert_verifier.h" +#include "net/cert/cert_verify_proc.h" +#include "net/cert/multi_threaded_cert_verifier.h" + #if BUILDFLAG(IS_CT_SUPPORTED) #include "components/certificate_transparency/chrome_ct_policy_enforcer.h" #include "components/certificate_transparency/chrome_require_ct_delegate.h" @@ -433,6 +438,79 @@ bool GetFullDataFilePath( } // namespace +class RemoteCertVerifier : public net::CertVerifier { + public: + RemoteCertVerifier(std::unique_ptr<net::CertVerifier> upstream): upstream_(std::move(upstream)) { + } + ~RemoteCertVerifier() override = default; + + void Bind( + mojo::PendingRemote<mojom::CertVerifierClient> client_info) { + client_.reset(); + if (client_info.is_valid()) { + client_.Bind(std::move(client_info)); + } + } + + // CertVerifier implementation + int Verify(const RequestParams& params, + net::CertVerifyResult* verify_result, + net::CompletionOnceCallback callback, + std::unique_ptr<Request>* out_req, + const net::NetLogWithSource& net_log) override { + out_req->reset(); + + net::CompletionOnceCallback callback2 = base::BindOnce( + &RemoteCertVerifier::OnRequestFinished, base::Unretained(this), + params, std::move(callback), verify_result); + int result = upstream_->Verify(params, verify_result, + std::move(callback2), out_req, net_log); + if (result != net::ERR_IO_PENDING) { + // Synchronous completion + } + + return result; + } + + + void SetConfig(const Config& config) override { + upstream_->SetConfig(config); + } + + void OnRequestFinished(const RequestParams& params, net::CompletionOnceCallback callback, net::CertVerifyResult* verify_result, int error) { + if (client_.is_bound()) { + client_->Verify(error, *verify_result, params.certificate(), + params.hostname(), params.flags(), params.ocsp_response(), + base::BindOnce(&RemoteCertVerifier::OnRemoteResponse, + base::Unretained(this), params, verify_result, error, + std::move(callback))); + } else { + std::move(callback).Run(error); + } + } + + void OnRemoteResponse( + const RequestParams& params, + net::CertVerifyResult* verify_result, + int error, + net::CompletionOnceCallback callback, + int error2, + const net::CertVerifyResult& verify_result2) { + if (error2 == net::ERR_ABORTED) { + // use the default + std::move(callback).Run(error); + } else { + // use the override + verify_result->Reset(); + verify_result->verified_cert = verify_result2.verified_cert; + std::move(callback).Run(error2); + } + } + private: + std::unique_ptr<net::CertVerifier> upstream_; + mojo::Remote<mojom::CertVerifierClient> client_; +}; + constexpr uint32_t NetworkContext::kMaxOutstandingRequestsPerProcess; NetworkContext::PendingCertVerify::PendingCertVerify() = default; @@ -671,6 +749,13 @@ void NetworkContext::SetClient( client_.Bind(std::move(client)); } +void NetworkContext::SetCertVerifierClient( + mojo::PendingRemote<mojom::CertVerifierClient> client) { + if (remote_cert_verifier_) { + remote_cert_verifier_->Bind(std::move(client)); + } +} + void NetworkContext::CreateURLLoaderFactory( mojo::PendingReceiver<mojom::URLLoaderFactory> receiver, mojom::URLLoaderFactoryParamsPtr params) { @@ -2226,6 +2311,9 @@ URLRequestContextOwner NetworkContext::MakeURLRequestContext( std::move(cert_verifier)); cert_verifier = base::WrapUnique(cert_verifier_with_trust_anchors_); #endif // BUILDFLAG(IS_CHROMEOS) + auto remote_cert_verifier = std::make_unique<RemoteCertVerifier>(std::move(cert_verifier)); + remote_cert_verifier_ = remote_cert_verifier.get(); + cert_verifier = std::make_unique<net::CachingCertVerifier>(std::move(remote_cert_verifier)); } builder.SetCertVerifier(IgnoreErrorsCertVerifier::MaybeWrapCertVerifier( diff --git a/services/network/network_context.h b/services/network/network_context.h index 6de81678e62d6921d0df5944ab01705402caa568..e412608e7720004462c48698c8ec39602b2b900e 100644 --- a/services/network/network_context.h +++ b/services/network/network_context.h @@ -105,6 +105,7 @@ class URLMatcher; namespace network { class CertVerifierWithTrustAnchors; +class RemoteCertVerifier; class CookieManager; class ExpectCTReporter; class HostResolver; @@ -220,6 +221,8 @@ class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext void CreateURLLoaderFactory( mojo::PendingReceiver<mojom::URLLoaderFactory> receiver, mojom::URLLoaderFactoryParamsPtr params) override; + void SetCertVerifierClient( + mojo::PendingRemote<mojom::CertVerifierClient> client) override; void ResetURLLoaderFactories() override; void GetCookieManager( mojo::PendingReceiver<mojom::CookieManager> receiver) override; @@ -793,6 +796,8 @@ class COMPONENT_EXPORT(NETWORK_SERVICE) NetworkContext CertVerifierWithTrustAnchors* cert_verifier_with_trust_anchors_ = nullptr; #endif + RemoteCertVerifier* remote_cert_verifier_ = nullptr; + // CertNetFetcher used by the context's CertVerifier. May be nullptr if // CertNetFetcher is not used by the current platform, or if the actual // net::CertVerifier is instantiated outside of the network service. diff --git a/services/network/public/mojom/network_context.mojom b/services/network/public/mojom/network_context.mojom index 9cd06ee552f8e592dd9efd1e73b10e5998559c04..fa56cfed3703664232843ad26028096d95dca253 100644 --- a/services/network/public/mojom/network_context.mojom +++ b/services/network/public/mojom/network_context.mojom @@ -277,6 +277,17 @@ struct NetworkContextFilePaths { bool trigger_migration = false; }; +interface CertVerifierClient { + Verify( + int32 default_error, + CertVerifyResult default_result, + X509Certificate certificate, + string hostname, + int32 flags, + string? ocsp_response + ) => (int32 error_code, CertVerifyResult result); +}; + // Parameters for constructing a network context. struct NetworkContextParams { // The user agent string. @@ -807,6 +818,9 @@ interface NetworkContext { // Sets a client for this network context. SetClient(pending_remote<NetworkContextClient> client); + // Sets a certificate verifier client for this network context. + SetCertVerifierClient(pending_remote<CertVerifierClient>? client); + // Creates a new URLLoaderFactory with the given |params|. CreateURLLoaderFactory(pending_receiver<URLLoaderFactory> url_loader_factory, URLLoaderFactoryParams params);
closed
electron/electron
https://github.com/electron/electron
32,867
[Bug]: Fiddle in Inter-Process Communication Documentation not working and code missing an import
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.8 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 16.0.8 ### Expected Behavior Fiddle in the Electron Documentation at https://www.electronjs.org/docs/latest/tutorial/ipc#pattern-3-main-to-renderer should load successfully and should include "ipcMain" in the imports of "main.js". ### Actual Behavior Fiddle will not load and when copying the code manually running the code will result in an Error since "ipcMain" is missing in the import of "main.js". ### Testcase Gist URL _No response_ ### Additional Information Couldn't find a seperate issue board for the documentation, so I posted this here.
https://github.com/electron/electron/issues/32867
https://github.com/electron/electron/pull/33262
02fe2455216578815d6300ba2a44d462a840142d
b27401172033e7c8fac38d3b2d784fe8f9a481b2
2022-02-11T10:35:39Z
c++
2022-03-16T15:01:29Z
docs/fiddles/ipc/pattern-3/renderer.js
const counter = document.getElementById('counter') window.electronAPI.handleCounter((event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue event.reply('counter-value', newValue) })
closed
electron/electron
https://github.com/electron/electron
32,867
[Bug]: Fiddle in Inter-Process Communication Documentation not working and code missing an import
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.8 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 16.0.8 ### Expected Behavior Fiddle in the Electron Documentation at https://www.electronjs.org/docs/latest/tutorial/ipc#pattern-3-main-to-renderer should load successfully and should include "ipcMain" in the imports of "main.js". ### Actual Behavior Fiddle will not load and when copying the code manually running the code will result in an Error since "ipcMain" is missing in the import of "main.js". ### Testcase Gist URL _No response_ ### Additional Information Couldn't find a seperate issue board for the documentation, so I posted this here.
https://github.com/electron/electron/issues/32867
https://github.com/electron/electron/pull/33262
02fe2455216578815d6300ba2a44d462a840142d
b27401172033e7c8fac38d3b2d784fe8f9a481b2
2022-02-11T10:35:39Z
c++
2022-03-16T15:01:29Z
docs/tutorial/ipc.md
--- title: Inter-Process Communication description: Use the ipcMain and ipcRenderer modules to communicate between Electron processes slug: ipc hide_title: false --- # Inter-Process Communication Inter-process communication (IPC) is a key part of building feature-rich desktop applications in Electron. Because the main and renderer processes have different responsibilities in Electron's process model, IPC is the only way to perform many common tasks, such as calling a native API from your UI or triggering changes in your web contents from native menus. ## IPC channels In Electron, processes communicate by passing messages through developer-defined "channels" with the [`ipcMain`] and [`ipcRenderer`] modules. These channels are **arbitrary** (you can name them anything you want) and **bidirectional** (you can use the same channel name for both modules). In this guide, we'll be going over some fundamental IPC patterns with concrete examples that you can use as a reference for your app code. ## Understanding context-isolated processes Before proceeding to implementation details, you should be familiar with the idea of using a [preload script] to import Node.js and Electron modules in a context-isolated renderer process. * For a full overview of Electron's process model, you can read the [process model docs]. * For a primer into exposing APIs from your preload script using the `contextBridge` module, check out the [context isolation tutorial]. ## Pattern 1: Renderer to main (one-way) To fire a one-way IPC message from a renderer process to the main process, you can use the [`ipcRenderer.send`] API to send a message that is then received by the [`ipcMain.on`] API. You usually use this pattern to call a main process API from your web contents. We'll demonstrate this pattern by creating a simple app that can programmatically change its window title. For this demo, you'll need to add code to your main process, your renderer process, and a preload script. The full code is below, but we'll be explaining each file individually in the following sections. ```fiddle docs/fiddles/ipc/pattern-1 ``` ### 1. Listen for events with `ipcMain.on` In the main process, set an IPC listener on the `set-title` channel with the `ipcMain.on` API: ```javascript {6-10,22} title='main.js (Main Process)' const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path') //... function handleSetTitle (event, title) { const webContents = event.sender const win = BrowserWindow.fromWebContents(webContents) win.setTitle(title) } function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { ipcMain.on('set-title', handleSetTitle) createWindow() } //... ``` The above `handleSetTitle` callback has two parameters: an [IpcMainEvent] structure and a `title` string. Whenever a message comes through the `set-title` channel, this function will find the BrowserWindow instance attached to the message sender and use the `win.setTitle` API on it. :::info Make sure you're loading the `index.html` and `preload.js` entry points for the following steps! ::: ### 2. Expose `ipcRenderer.send` via preload To send messages to the listener created above, you can use the `ipcRenderer.send` API. By default, the renderer process has no Node.js or Electron module access. As an app developer, you need to choose which APIs to expose from your preload script using the `contextBridge` API. In your preload script, add the following code, which will expose a global `window.electronAPI` variable to your renderer process. ```javascript title='preload.js (Preload Script)' const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { setTitle: (title) => ipcRenderer.send('set-title', title) }) ``` At this point, you'll be able to use the `window.electronAPI.setTitle()` function in the renderer process. :::caution Security warning We don't directly expose the whole `ipcRenderer.send` API for [security reasons]. Make sure to limit the renderer's access to Electron APIs as much as possible. ::: ### 3. Build the renderer process UI In our BrowserWindow's loaded HTML file, add a basic user interface consisting of a text input and a button: ```html {11-12} title='index.html' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Hello World!</title> </head> <body> Title: <input id="title"/> <button id="btn" type="button">Set</button> <script src="./renderer.js"></script> </body> </html> ``` To make these elements interactive, we'll be adding a few lines of code in the imported `renderer.js` file that leverages the `window.electronAPI` functionality exposed from the preload script: ```javascript title='renderer.js (Renderer Process)' const setButton = document.getElementById('btn') const titleInput = document.getElementById('title') setButton.addEventListener('click', () => { const title = titleInput.value window.electronAPI.setTitle(title) }); ``` At this point, your demo should be fully functional. Try using the input field and see what happens to your BrowserWindow title! ## Pattern 2: Renderer to main (two-way) A common application for two-way IPC is calling a main process module from your renderer process code and waiting for a result. This can be done by using [`ipcRenderer.invoke`] paired with [`ipcMain.handle`]. In the following example, we'll be opening a native file dialog from the renderer process and returning the selected file's path. For this demo, you'll need to add code to your main process, your renderer process, and a preload script. The full code is below, but we'll be explaining each file individually in the following sections. ```fiddle docs/fiddles/ipc/pattern-2 ``` ### 1. Listen for events with `ipcMain.handle` In the main process, we'll be creating a `handleFileOpen()` function that calls `dialog.showOpenDialog` and returns the value of the file path selected by the user. This function is used as a callback whenever an `ipcRender.invoke` message is sent through the `dialog:openFile` channel from the renderer process. The return value is then returned as a Promise to the original `invoke` call. :::caution A word on error handling Errors thrown through `handle` in the main process are not transparent as they are serialized and only the `message` property from the original error is provided to the renderer process. Please refer to [#24427](https://github.com/electron/electron/issues/24427) for details. ::: ```javascript {6-13,25} title='main.js (Main Process)' const { BrowserWindow, dialog, ipcMain } = require('electron') const path = require('path') //... async function handleFileOpen() { const { canceled, filePaths } = await dialog.showOpenDialog() if (canceled) { return } else { return filePaths[0] } } function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.loadFile('index.html') } app.whenReady(() => { ipcMain.handle('dialog:openFile', handleFileOpen) createWindow() }) //... ``` :::tip on channel names The `dialog:` prefix on the IPC channel name has no effect on the code. It only serves as a namespace that helps with code readability. ::: :::info Make sure you're loading the `index.html` and `preload.js` entry points for the following steps! ::: ### 2. Expose `ipcRenderer.invoke` via preload In the preload script, we expose a one-line `openFile` function that calls and returns the value of `ipcRenderer.invoke('dialog:openFile')`. We'll be using this API in the next step to call the native dialog from our renderer's user interface. ```javascript title='preload.js (Preload Script)' const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { openFile: () => ipcRenderer.invoke('dialog:openFile') }) ``` :::caution Security warning We don't directly expose the whole `ipcRenderer.invoke` API for [security reasons]. Make sure to limit the renderer's access to Electron APIs as much as possible. ::: ### 3. Build the renderer process UI Finally, let's build the HTML file that we load into our BrowserWindow. ```html {10-11} title='index.html' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Dialog</title> </head> <body> <button type="button" id="btn">Open a File</button> File path: <strong id="filePath"></strong> <script src='./renderer.js'></script> </body> </html> ``` The UI consists of a single `#btn` button element that will be used to trigger our preload API, and a `#filePath` element that will be used to display the path of the selected file. Making these pieces work will take a few lines of code in the renderer process script: ```javascript title='renderer.js (Renderer Process)' const btn = document.getElementById('btn') const filePathElement = document.getElementById('filePath') btn.addEventListener('click', async () => { const filePath = await window.electronAPI.openFile() filePathElement.innerText = filePath }) ``` In the above snippet, we listen for clicks on the `#btn` button, and call our `window.electronAPI.openFile()` API to activate the native Open File dialog. We then display the selected file path in the `#filePath` element. ### Note: legacy approaches The `ipcRenderer.invoke` API was added in Electron 7 as a developer-friendly way to tackle two-way IPC from the renderer process. However, there exist a couple alternative approaches to this IPC pattern. :::warning Avoid legacy approaches if possible We recommend using `ipcRenderer.invoke` whenever possible. The following two-way renderer-to-main patterns are documented for historical purposes. ::: :::info For the following examples, we're calling `ipcRenderer` directly from the preload script to keep the code samples small. ::: #### Using `ipcRenderer.send` The `ipcRenderer.send` API that we used for single-way communication can also be leveraged to perform two-way communication. This was the recommended way for asynchronous two-way communication via IPC prior to Electron 7. ```javascript title='preload.js (Preload Script)' // You can also put expose this code to the renderer // process with the `contextBridge` API const { ipcRenderer } = require('electron') ipcRenderer.on('asynchronous-reply', (_event, arg) => { console.log(arg) // prints "pong" in the DevTools console }) ipcRenderer.send('asynchronous-message', 'ping') ``` ```javascript title='main.js (Main Process)' ipcMain.on('asynchronous-message', (event, arg) => { console.log(arg) // prints "ping" in the Node console // works like `send`, but returning a message back // to the renderer that sent the original message event.reply('asynchronous-reply', 'pong') }) ``` There are a couple downsides to this approach: * You need to set up a second `ipcRenderer.on` listener to handle the response in the renderer process. With `invoke`, you get the response value returned as a Promise to the original API call. * There's no obvious way to pair the `asynchronous-reply` message to the original `asynchronous-message` one. If you have very frequent messages going back and forth through these channels, you would need to add additional app code to track each call and response individually. #### Using `ipcRenderer.sendSync` The `ipcRenderer.sendSync` API sends a message to the main process and waits _synchronously_ for a response. ```javascript title='main.js (Main Process)' const { ipcMain } = require('electron') ipcMain.on('synchronous-message', (event, arg) => { console.log(arg) // prints "ping" in the Node console event.returnValue = 'pong' }) ``` ```javascript title='preload.js (Preload Script)' // You can also put expose this code to the renderer // process with the `contextBridge` API const { ipcRenderer } = require('electron') const result = ipcRenderer.sendSync('synchronous-message', 'ping') console.log(result) // prints "pong" in the DevTools console ``` The structure of this code is very similar to the `invoke` model, but we recommend **avoiding this API** for performance reasons. Its synchronous nature means that it'll block the renderer process until a reply is received. ## Pattern 3: Main to renderer When sending a message from the main process to a renderer process, you need to specify which renderer is receiving the message. Messages need to be sent to a renderer process via its [`WebContents`] instance. This WebContents instance contains a [`send`][webcontents-send] method that can be used in the same way as `ipcRenderer.send`. To demonstrate this pattern, we'll be building a number counter controlled by the native operating system menu. For this demo, you'll need to add code to your main process, your renderer process, and a preload script. The full code is below, but we'll be explaining each file individually in the following sections. ```fiddle docs/fiddles/ipc/pattern-3 ``` ### 1. Send messages with the `webContents` module For this demo, we'll need to first build a custom menu in the main process using Electron's `Menu` module that uses the `webContents.send` API to send an IPC message from the main process to the target renderer. ```javascript {11-26} title='main.js (Main Process)' const {app, BrowserWindow, Menu} = require('electron') const path = require('path') function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) const menu = Menu.buildFromTemplate([ { label: app.name, submenu: [ { click: () => mainWindow.webContents.send('update-counter', 1), label: 'Increment', }, { click: () => mainWindow.webContents.send('update-counter', -1), label: 'Decrement', } ] } ]) Menu.setApplicationMenu(menu) mainWindow.loadFile('index.html') } //... ``` For the purposes of the tutorial, it's important to note that the `click` handler sends a message (either `1` or `-1`) to the renderer process through the `counter` channel. ```javascript click: () => mainWindow.webContents.send('update-counter', -1) ``` :::info Make sure you're loading the `index.html` and `preload.js` entry points for the following steps! ::: ### 2. Expose `ipcRenderer.on` via preload Like in the previous renderer-to-main example, we use the `contextBridge` and `ipcRenderer` modules in the preload script to expose IPC functionality to the renderer process: ```javascript title='preload.js (Preload Script)' const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { onUpdateCounter: (callback) => ipcRenderer.on('update-counter', callback) }) ``` After loading the preload script, your renderer process should have access to the `window.electronAPI.onUpdateCounter()` listener function. :::caution Security warning We don't directly expose the whole `ipcRenderer.on` API for [security reasons]. Make sure to limit the renderer's access to Electron APIs as much as possible. ::: :::info In the case of this minimal example, you can call `ipcRenderer.on` directly in the preload script rather than exposing it over the context bridge. ```javascript title='preload.js (Preload Script)' const { ipcRenderer } = require('electron') window.addEventListener('DOMContentLoaded', () => { const counter = document.getElementById('counter') ipcRenderer.on('update-counter', (_event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue }) }) ``` However, this approach has limited flexibility compared to exposing your preload APIs over the context bridge, since your listener can't directly interact with your renderer code. ::: ### 3. Build the renderer process UI To tie it all together, we'll create an interface in the loaded HTML file that contains a `#counter` element that we'll use to display the values: ```html {10} title='index.html' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Menu Counter</title> </head> <body> Current value: <strong id="counter">0</strong> <script src="./renderer.js"></script> </body> </html> ``` Finally, to make the values update in the HTML document, we'll add a few lines of DOM manipulation so that the value of the `#counter` element is updated whenever we fire an `update-counter` event. ```javascript title='renderer.js (Renderer Process)' const counter = document.getElementById('counter') window.electronAPI.onUpdateCounter((_event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue }) ``` In the above code, we're passing in a callback to the `window.electronAPI.onUpdateCounter` function exposed from our preload script. The second `value` parameter corresponds to the `1` or `-1` we were passing in from the `webContents.send` call from the native menu. ### Optional: returning a reply There's no equivalent for `ipcRenderer.invoke` for main-to-renderer IPC. Instead, you can send a reply back to the main process from within the `ipcRenderer.on` callback. We can demonstrate this with slight modifications to the code from the previous example. In the renderer process, use the `event` parameter to send a reply back to the main process through the `counter-value` channel. ```javascript title='renderer.js (Renderer Process)' const counter = document.getElementById('counter') window.electronAPI.onUpdateCounter((event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue event.reply('counter-value', newValue) }) ``` In the main process, listen for `counter-value` events and handle them appropriately. ```javascript title='main.js (Main Process)' //... ipcMain.on('counter-value', (_event, value) => { console.log(value) // will print value to Node console }) //... ``` ## Pattern 4: Renderer to renderer There's no direct way to send messages between renderer processes in Electron using the `ipcMain` and `ipcRenderer` modules. To achieve this, you have two options: * Use the main process as a message broker between renderers. This would involve sending a message from one renderer to the main process, which would forward the message to the other renderer. * Pass a [MessagePort] from the main process to both renderers. This will allow direct communication between renderers after the initial setup. ## Object serialization Electron's IPC implementation uses the HTML standard [Structured Clone Algorithm][sca] to serialize objects passed between processes, meaning that only certain types of objects can be passed through IPC channels. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. [context isolation tutorial]: context-isolation.md [security reasons]: ./context-isolation.md#security-considerations [`ipcMain`]: ../api/ipc-main.md [`ipcMain.handle`]: ../api/ipc-main.md#ipcmainhandlechannel-listener [`ipcMain.on`]: ../api/ipc-main.md [IpcMainEvent]: ../api/structures/ipc-main-event.md [`ipcRenderer`]: ../api/ipc-renderer.md [`ipcRenderer.invoke`]: ../api/ipc-renderer.md#ipcrendererinvokechannel-args [`ipcRenderer.send`]: ../api/ipc-renderer.md [MessagePort]: ./message-ports.md [preload script]: process-model.md#preload-scripts [process model docs]: process-model.md [sca]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`WebContents`]: ../api/web-contents.md [webcontents-send]: ../api/web-contents.md#contentssendchannel-args
closed
electron/electron
https://github.com/electron/electron
32,867
[Bug]: Fiddle in Inter-Process Communication Documentation not working and code missing an import
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.8 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 16.0.8 ### Expected Behavior Fiddle in the Electron Documentation at https://www.electronjs.org/docs/latest/tutorial/ipc#pattern-3-main-to-renderer should load successfully and should include "ipcMain" in the imports of "main.js". ### Actual Behavior Fiddle will not load and when copying the code manually running the code will result in an Error since "ipcMain" is missing in the import of "main.js". ### Testcase Gist URL _No response_ ### Additional Information Couldn't find a seperate issue board for the documentation, so I posted this here.
https://github.com/electron/electron/issues/32867
https://github.com/electron/electron/pull/33262
02fe2455216578815d6300ba2a44d462a840142d
b27401172033e7c8fac38d3b2d784fe8f9a481b2
2022-02-11T10:35:39Z
c++
2022-03-16T15:01:29Z
docs/fiddles/ipc/pattern-3/renderer.js
const counter = document.getElementById('counter') window.electronAPI.handleCounter((event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue event.reply('counter-value', newValue) })
closed
electron/electron
https://github.com/electron/electron
32,867
[Bug]: Fiddle in Inter-Process Communication Documentation not working and code missing an import
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.8 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version 16.0.8 ### Expected Behavior Fiddle in the Electron Documentation at https://www.electronjs.org/docs/latest/tutorial/ipc#pattern-3-main-to-renderer should load successfully and should include "ipcMain" in the imports of "main.js". ### Actual Behavior Fiddle will not load and when copying the code manually running the code will result in an Error since "ipcMain" is missing in the import of "main.js". ### Testcase Gist URL _No response_ ### Additional Information Couldn't find a seperate issue board for the documentation, so I posted this here.
https://github.com/electron/electron/issues/32867
https://github.com/electron/electron/pull/33262
02fe2455216578815d6300ba2a44d462a840142d
b27401172033e7c8fac38d3b2d784fe8f9a481b2
2022-02-11T10:35:39Z
c++
2022-03-16T15:01:29Z
docs/tutorial/ipc.md
--- title: Inter-Process Communication description: Use the ipcMain and ipcRenderer modules to communicate between Electron processes slug: ipc hide_title: false --- # Inter-Process Communication Inter-process communication (IPC) is a key part of building feature-rich desktop applications in Electron. Because the main and renderer processes have different responsibilities in Electron's process model, IPC is the only way to perform many common tasks, such as calling a native API from your UI or triggering changes in your web contents from native menus. ## IPC channels In Electron, processes communicate by passing messages through developer-defined "channels" with the [`ipcMain`] and [`ipcRenderer`] modules. These channels are **arbitrary** (you can name them anything you want) and **bidirectional** (you can use the same channel name for both modules). In this guide, we'll be going over some fundamental IPC patterns with concrete examples that you can use as a reference for your app code. ## Understanding context-isolated processes Before proceeding to implementation details, you should be familiar with the idea of using a [preload script] to import Node.js and Electron modules in a context-isolated renderer process. * For a full overview of Electron's process model, you can read the [process model docs]. * For a primer into exposing APIs from your preload script using the `contextBridge` module, check out the [context isolation tutorial]. ## Pattern 1: Renderer to main (one-way) To fire a one-way IPC message from a renderer process to the main process, you can use the [`ipcRenderer.send`] API to send a message that is then received by the [`ipcMain.on`] API. You usually use this pattern to call a main process API from your web contents. We'll demonstrate this pattern by creating a simple app that can programmatically change its window title. For this demo, you'll need to add code to your main process, your renderer process, and a preload script. The full code is below, but we'll be explaining each file individually in the following sections. ```fiddle docs/fiddles/ipc/pattern-1 ``` ### 1. Listen for events with `ipcMain.on` In the main process, set an IPC listener on the `set-title` channel with the `ipcMain.on` API: ```javascript {6-10,22} title='main.js (Main Process)' const {app, BrowserWindow, ipcMain} = require('electron') const path = require('path') //... function handleSetTitle (event, title) { const webContents = event.sender const win = BrowserWindow.fromWebContents(webContents) win.setTitle(title) } function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.loadFile('index.html') } app.whenReady().then(() => { ipcMain.on('set-title', handleSetTitle) createWindow() } //... ``` The above `handleSetTitle` callback has two parameters: an [IpcMainEvent] structure and a `title` string. Whenever a message comes through the `set-title` channel, this function will find the BrowserWindow instance attached to the message sender and use the `win.setTitle` API on it. :::info Make sure you're loading the `index.html` and `preload.js` entry points for the following steps! ::: ### 2. Expose `ipcRenderer.send` via preload To send messages to the listener created above, you can use the `ipcRenderer.send` API. By default, the renderer process has no Node.js or Electron module access. As an app developer, you need to choose which APIs to expose from your preload script using the `contextBridge` API. In your preload script, add the following code, which will expose a global `window.electronAPI` variable to your renderer process. ```javascript title='preload.js (Preload Script)' const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { setTitle: (title) => ipcRenderer.send('set-title', title) }) ``` At this point, you'll be able to use the `window.electronAPI.setTitle()` function in the renderer process. :::caution Security warning We don't directly expose the whole `ipcRenderer.send` API for [security reasons]. Make sure to limit the renderer's access to Electron APIs as much as possible. ::: ### 3. Build the renderer process UI In our BrowserWindow's loaded HTML file, add a basic user interface consisting of a text input and a button: ```html {11-12} title='index.html' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Hello World!</title> </head> <body> Title: <input id="title"/> <button id="btn" type="button">Set</button> <script src="./renderer.js"></script> </body> </html> ``` To make these elements interactive, we'll be adding a few lines of code in the imported `renderer.js` file that leverages the `window.electronAPI` functionality exposed from the preload script: ```javascript title='renderer.js (Renderer Process)' const setButton = document.getElementById('btn') const titleInput = document.getElementById('title') setButton.addEventListener('click', () => { const title = titleInput.value window.electronAPI.setTitle(title) }); ``` At this point, your demo should be fully functional. Try using the input field and see what happens to your BrowserWindow title! ## Pattern 2: Renderer to main (two-way) A common application for two-way IPC is calling a main process module from your renderer process code and waiting for a result. This can be done by using [`ipcRenderer.invoke`] paired with [`ipcMain.handle`]. In the following example, we'll be opening a native file dialog from the renderer process and returning the selected file's path. For this demo, you'll need to add code to your main process, your renderer process, and a preload script. The full code is below, but we'll be explaining each file individually in the following sections. ```fiddle docs/fiddles/ipc/pattern-2 ``` ### 1. Listen for events with `ipcMain.handle` In the main process, we'll be creating a `handleFileOpen()` function that calls `dialog.showOpenDialog` and returns the value of the file path selected by the user. This function is used as a callback whenever an `ipcRender.invoke` message is sent through the `dialog:openFile` channel from the renderer process. The return value is then returned as a Promise to the original `invoke` call. :::caution A word on error handling Errors thrown through `handle` in the main process are not transparent as they are serialized and only the `message` property from the original error is provided to the renderer process. Please refer to [#24427](https://github.com/electron/electron/issues/24427) for details. ::: ```javascript {6-13,25} title='main.js (Main Process)' const { BrowserWindow, dialog, ipcMain } = require('electron') const path = require('path') //... async function handleFileOpen() { const { canceled, filePaths } = await dialog.showOpenDialog() if (canceled) { return } else { return filePaths[0] } } function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) mainWindow.loadFile('index.html') } app.whenReady(() => { ipcMain.handle('dialog:openFile', handleFileOpen) createWindow() }) //... ``` :::tip on channel names The `dialog:` prefix on the IPC channel name has no effect on the code. It only serves as a namespace that helps with code readability. ::: :::info Make sure you're loading the `index.html` and `preload.js` entry points for the following steps! ::: ### 2. Expose `ipcRenderer.invoke` via preload In the preload script, we expose a one-line `openFile` function that calls and returns the value of `ipcRenderer.invoke('dialog:openFile')`. We'll be using this API in the next step to call the native dialog from our renderer's user interface. ```javascript title='preload.js (Preload Script)' const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { openFile: () => ipcRenderer.invoke('dialog:openFile') }) ``` :::caution Security warning We don't directly expose the whole `ipcRenderer.invoke` API for [security reasons]. Make sure to limit the renderer's access to Electron APIs as much as possible. ::: ### 3. Build the renderer process UI Finally, let's build the HTML file that we load into our BrowserWindow. ```html {10-11} title='index.html' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Dialog</title> </head> <body> <button type="button" id="btn">Open a File</button> File path: <strong id="filePath"></strong> <script src='./renderer.js'></script> </body> </html> ``` The UI consists of a single `#btn` button element that will be used to trigger our preload API, and a `#filePath` element that will be used to display the path of the selected file. Making these pieces work will take a few lines of code in the renderer process script: ```javascript title='renderer.js (Renderer Process)' const btn = document.getElementById('btn') const filePathElement = document.getElementById('filePath') btn.addEventListener('click', async () => { const filePath = await window.electronAPI.openFile() filePathElement.innerText = filePath }) ``` In the above snippet, we listen for clicks on the `#btn` button, and call our `window.electronAPI.openFile()` API to activate the native Open File dialog. We then display the selected file path in the `#filePath` element. ### Note: legacy approaches The `ipcRenderer.invoke` API was added in Electron 7 as a developer-friendly way to tackle two-way IPC from the renderer process. However, there exist a couple alternative approaches to this IPC pattern. :::warning Avoid legacy approaches if possible We recommend using `ipcRenderer.invoke` whenever possible. The following two-way renderer-to-main patterns are documented for historical purposes. ::: :::info For the following examples, we're calling `ipcRenderer` directly from the preload script to keep the code samples small. ::: #### Using `ipcRenderer.send` The `ipcRenderer.send` API that we used for single-way communication can also be leveraged to perform two-way communication. This was the recommended way for asynchronous two-way communication via IPC prior to Electron 7. ```javascript title='preload.js (Preload Script)' // You can also put expose this code to the renderer // process with the `contextBridge` API const { ipcRenderer } = require('electron') ipcRenderer.on('asynchronous-reply', (_event, arg) => { console.log(arg) // prints "pong" in the DevTools console }) ipcRenderer.send('asynchronous-message', 'ping') ``` ```javascript title='main.js (Main Process)' ipcMain.on('asynchronous-message', (event, arg) => { console.log(arg) // prints "ping" in the Node console // works like `send`, but returning a message back // to the renderer that sent the original message event.reply('asynchronous-reply', 'pong') }) ``` There are a couple downsides to this approach: * You need to set up a second `ipcRenderer.on` listener to handle the response in the renderer process. With `invoke`, you get the response value returned as a Promise to the original API call. * There's no obvious way to pair the `asynchronous-reply` message to the original `asynchronous-message` one. If you have very frequent messages going back and forth through these channels, you would need to add additional app code to track each call and response individually. #### Using `ipcRenderer.sendSync` The `ipcRenderer.sendSync` API sends a message to the main process and waits _synchronously_ for a response. ```javascript title='main.js (Main Process)' const { ipcMain } = require('electron') ipcMain.on('synchronous-message', (event, arg) => { console.log(arg) // prints "ping" in the Node console event.returnValue = 'pong' }) ``` ```javascript title='preload.js (Preload Script)' // You can also put expose this code to the renderer // process with the `contextBridge` API const { ipcRenderer } = require('electron') const result = ipcRenderer.sendSync('synchronous-message', 'ping') console.log(result) // prints "pong" in the DevTools console ``` The structure of this code is very similar to the `invoke` model, but we recommend **avoiding this API** for performance reasons. Its synchronous nature means that it'll block the renderer process until a reply is received. ## Pattern 3: Main to renderer When sending a message from the main process to a renderer process, you need to specify which renderer is receiving the message. Messages need to be sent to a renderer process via its [`WebContents`] instance. This WebContents instance contains a [`send`][webcontents-send] method that can be used in the same way as `ipcRenderer.send`. To demonstrate this pattern, we'll be building a number counter controlled by the native operating system menu. For this demo, you'll need to add code to your main process, your renderer process, and a preload script. The full code is below, but we'll be explaining each file individually in the following sections. ```fiddle docs/fiddles/ipc/pattern-3 ``` ### 1. Send messages with the `webContents` module For this demo, we'll need to first build a custom menu in the main process using Electron's `Menu` module that uses the `webContents.send` API to send an IPC message from the main process to the target renderer. ```javascript {11-26} title='main.js (Main Process)' const {app, BrowserWindow, Menu} = require('electron') const path = require('path') function createWindow () { const mainWindow = new BrowserWindow({ webPreferences: { preload: path.join(__dirname, 'preload.js') } }) const menu = Menu.buildFromTemplate([ { label: app.name, submenu: [ { click: () => mainWindow.webContents.send('update-counter', 1), label: 'Increment', }, { click: () => mainWindow.webContents.send('update-counter', -1), label: 'Decrement', } ] } ]) Menu.setApplicationMenu(menu) mainWindow.loadFile('index.html') } //... ``` For the purposes of the tutorial, it's important to note that the `click` handler sends a message (either `1` or `-1`) to the renderer process through the `counter` channel. ```javascript click: () => mainWindow.webContents.send('update-counter', -1) ``` :::info Make sure you're loading the `index.html` and `preload.js` entry points for the following steps! ::: ### 2. Expose `ipcRenderer.on` via preload Like in the previous renderer-to-main example, we use the `contextBridge` and `ipcRenderer` modules in the preload script to expose IPC functionality to the renderer process: ```javascript title='preload.js (Preload Script)' const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { onUpdateCounter: (callback) => ipcRenderer.on('update-counter', callback) }) ``` After loading the preload script, your renderer process should have access to the `window.electronAPI.onUpdateCounter()` listener function. :::caution Security warning We don't directly expose the whole `ipcRenderer.on` API for [security reasons]. Make sure to limit the renderer's access to Electron APIs as much as possible. ::: :::info In the case of this minimal example, you can call `ipcRenderer.on` directly in the preload script rather than exposing it over the context bridge. ```javascript title='preload.js (Preload Script)' const { ipcRenderer } = require('electron') window.addEventListener('DOMContentLoaded', () => { const counter = document.getElementById('counter') ipcRenderer.on('update-counter', (_event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue }) }) ``` However, this approach has limited flexibility compared to exposing your preload APIs over the context bridge, since your listener can't directly interact with your renderer code. ::: ### 3. Build the renderer process UI To tie it all together, we'll create an interface in the loaded HTML file that contains a `#counter` element that we'll use to display the values: ```html {10} title='index.html' <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'"> <title>Menu Counter</title> </head> <body> Current value: <strong id="counter">0</strong> <script src="./renderer.js"></script> </body> </html> ``` Finally, to make the values update in the HTML document, we'll add a few lines of DOM manipulation so that the value of the `#counter` element is updated whenever we fire an `update-counter` event. ```javascript title='renderer.js (Renderer Process)' const counter = document.getElementById('counter') window.electronAPI.onUpdateCounter((_event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue }) ``` In the above code, we're passing in a callback to the `window.electronAPI.onUpdateCounter` function exposed from our preload script. The second `value` parameter corresponds to the `1` or `-1` we were passing in from the `webContents.send` call from the native menu. ### Optional: returning a reply There's no equivalent for `ipcRenderer.invoke` for main-to-renderer IPC. Instead, you can send a reply back to the main process from within the `ipcRenderer.on` callback. We can demonstrate this with slight modifications to the code from the previous example. In the renderer process, use the `event` parameter to send a reply back to the main process through the `counter-value` channel. ```javascript title='renderer.js (Renderer Process)' const counter = document.getElementById('counter') window.electronAPI.onUpdateCounter((event, value) => { const oldValue = Number(counter.innerText) const newValue = oldValue + value counter.innerText = newValue event.reply('counter-value', newValue) }) ``` In the main process, listen for `counter-value` events and handle them appropriately. ```javascript title='main.js (Main Process)' //... ipcMain.on('counter-value', (_event, value) => { console.log(value) // will print value to Node console }) //... ``` ## Pattern 4: Renderer to renderer There's no direct way to send messages between renderer processes in Electron using the `ipcMain` and `ipcRenderer` modules. To achieve this, you have two options: * Use the main process as a message broker between renderers. This would involve sending a message from one renderer to the main process, which would forward the message to the other renderer. * Pass a [MessagePort] from the main process to both renderers. This will allow direct communication between renderers after the initial setup. ## Object serialization Electron's IPC implementation uses the HTML standard [Structured Clone Algorithm][sca] to serialize objects passed between processes, meaning that only certain types of objects can be passed through IPC channels. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. [context isolation tutorial]: context-isolation.md [security reasons]: ./context-isolation.md#security-considerations [`ipcMain`]: ../api/ipc-main.md [`ipcMain.handle`]: ../api/ipc-main.md#ipcmainhandlechannel-listener [`ipcMain.on`]: ../api/ipc-main.md [IpcMainEvent]: ../api/structures/ipc-main-event.md [`ipcRenderer`]: ../api/ipc-renderer.md [`ipcRenderer.invoke`]: ../api/ipc-renderer.md#ipcrendererinvokechannel-args [`ipcRenderer.send`]: ../api/ipc-renderer.md [MessagePort]: ./message-ports.md [preload script]: process-model.md#preload-scripts [process model docs]: process-model.md [sca]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm [`WebContents`]: ../api/web-contents.md [webcontents-send]: ../api/web-contents.md#contentssendchannel-args
closed
electron/electron
https://github.com/electron/electron
33,164
[Bug]: Blank page on location change / reload if a filesystem asynchronous call was pending
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 13.6.9 ### Expected Behavior Assuming a BrowserWindow like this: ``` const mainWindow = new BrowserWindow({ ... webPreferences: { nodeIntegration: true, contextIsolation: false, } }) ``` And an asynchronous filesystem call on `fs.promises` API ``` // renderer.js const fs = require('fs'); async function asyncStuff() { let output = await fs.promises.readFile("datafile"); } ``` Then trying to reload the page when the fs asynchronous call is not finished yet will make the page fail (blank page). ``` // renderer.js async function testCrash() { asyncStuff() // No await here window.location.reload() // Here the renderer will crash }) ``` I expect that the page reloads correctly. ### Actual Behavior The page is blank, and DevTools are disconnected. ### Testcase Gist URL _No response_ ### Additional Information Notes: * Replace the `fs.promises.readFile()` by `fs.readFileSync()` and the page will reload fine * Replace the `fs.promises.readFile()` by `fs.readFile() with callback` and the page will reload fine * The bug is here also with a `window.location.href` * I tried with other async api and the page works fine (like `https.get()`, `timers.promises.setTimeout()`, or `fetch()`) I created a repo to reproduce the bug: https://github.com/remss/electron-issue-reload Just run `npm i && npm start` then click on `reloadMeWithAsyncStuff` button to see the blank page.
https://github.com/electron/electron/issues/33164
https://github.com/electron/electron/pull/33280
652680e8012983b1d8b9118b48297df4c1d9a939
b2c5623a13c91a561704b46480b6c3a7a51f2db7
2022-03-07T14:31:24Z
c++
2022-03-16T17:54:45Z
shell/renderer/electron_renderer_client.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/renderer/electron_renderer_client.h" #include <string> #include "base/command_line.h" #include "content/public/renderer/render_frame.h" #include "electron/buildflags/buildflags.h" #include "net/http/http_request_headers.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/renderer/electron_render_frame_observer.h" #include "shell/renderer/web_worker_observer.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" namespace electron { namespace { bool IsDevToolsExtension(content::RenderFrame* render_frame) { return static_cast<GURL>(render_frame->GetWebFrame()->GetDocument().Url()) .SchemeIs("chrome-extension"); } } // namespace ElectronRendererClient::ElectronRendererClient() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kRenderer)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {} ElectronRendererClient::~ElectronRendererClient() = default; void ElectronRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { new ElectronRenderFrameObserver(render_frame, this); RendererClientBase::RenderFrameCreated(render_frame); } void ElectronRendererClient::RunScriptsAtDocumentStart( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentStart(render_frame); // Inform the document start phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-start"); } void ElectronRendererClient::RunScriptsAtDocumentEnd( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentEnd(render_frame); // Inform the document end phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-end"); } void ElectronRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> renderer_context, content::RenderFrame* render_frame) { // TODO(zcbenz): Do not create Node environment if node integration is not // enabled. // Only load Node.js if we are a main frame or a devtools extension // unless Node.js support has been explicitly enabled for subframes. auto prefs = render_frame->GetBlinkPreferences(); bool is_main_frame = render_frame->IsMainFrame(); bool is_devtools = IsDevToolsExtension(render_frame); bool allow_node_in_subframes = prefs.node_integration_in_sub_frames; bool should_load_node = (is_main_frame || is_devtools || allow_node_in_subframes) && !IsWebViewFrame(renderer_context, render_frame); if (!should_load_node) return; injected_frames_.insert(render_frame); if (!node_integration_initialized_) { node_integration_initialized_ = true; node_bindings_->Initialize(); node_bindings_->PrepareMessageLoop(); } else { node_bindings_->PrepareMessageLoop(); } // Setup node tracing controller. if (!node::tracing::TraceEventHelper::GetAgent()) node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. bool initialized = node::InitializeContext(renderer_context); CHECK(initialized); node::Environment* env = node_bindings_->CreateEnvironment(renderer_context, nullptr); // If we have disabled the site instance overrides we should prevent loading // any non-context aware native module. env->options()->force_context_aware = true; // We do not want to crash the renderer process on unhandled rejections. env->options()->unhandled_rejections = "warn"; environments_.insert(env); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); gin_helper::Dictionary process_dict(env->isolate(), env->process_object()); BindProcess(env->isolate(), &process_dict, render_frame); // Load everything. node_bindings_->LoadEnvironment(env); if (node_bindings_->uv_env() == nullptr) { // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->RunMessageLoop(); } } void ElectronRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { if (injected_frames_.erase(render_frame) == 0) return; node::Environment* env = node::Environment::GetCurrent(context); if (environments_.erase(env) == 0) return; gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); // The main frame may be replaced. if (env == node_bindings_->uv_env()) node_bindings_->set_uv_env(nullptr); // Destroy the node environment. We only do this if node support has been // enabled for sub-frames to avoid a change-of-behavior / introduce crashes // for existing users. // We also do this if we have disable electron site instance overrides to // avoid memory leaks auto prefs = render_frame->GetBlinkPreferences(); gin_helper::MicrotasksScope microtasks_scope(env->isolate()); node::FreeEnvironment(env); if (env == node_bindings_->uv_env()) node::FreeIsolateData(node_bindings_->isolate_data()); // ElectronBindings is tracking node environments. electron_bindings_->EnvironmentDestroyed(env); } void ElectronRendererClient::WorkerScriptReadyForEvaluationOnWorkerThread( v8::Local<v8::Context> context) { // TODO(loc): Note that this will not be correct for in-process child windows // with webPreferences that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { WebWorkerObserver::GetCurrent()->WorkerScriptReadyForEvaluation(context); } } void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread( v8::Local<v8::Context> context) { // TODO(loc): Note that this will not be correct for in-process child windows // with webPreferences that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { WebWorkerObserver::GetCurrent()->ContextWillDestroy(context); } } node::Environment* ElectronRendererClient::GetEnvironment( content::RenderFrame* render_frame) const { if (injected_frames_.find(render_frame) == injected_frames_.end()) return nullptr; v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); auto context = GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent()); node::Environment* env = node::Environment::GetCurrent(context); if (environments_.find(env) == environments_.end()) return nullptr; return env; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,164
[Bug]: Blank page on location change / reload if a filesystem asynchronous call was pending
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 13.6.9 ### Expected Behavior Assuming a BrowserWindow like this: ``` const mainWindow = new BrowserWindow({ ... webPreferences: { nodeIntegration: true, contextIsolation: false, } }) ``` And an asynchronous filesystem call on `fs.promises` API ``` // renderer.js const fs = require('fs'); async function asyncStuff() { let output = await fs.promises.readFile("datafile"); } ``` Then trying to reload the page when the fs asynchronous call is not finished yet will make the page fail (blank page). ``` // renderer.js async function testCrash() { asyncStuff() // No await here window.location.reload() // Here the renderer will crash }) ``` I expect that the page reloads correctly. ### Actual Behavior The page is blank, and DevTools are disconnected. ### Testcase Gist URL _No response_ ### Additional Information Notes: * Replace the `fs.promises.readFile()` by `fs.readFileSync()` and the page will reload fine * Replace the `fs.promises.readFile()` by `fs.readFile() with callback` and the page will reload fine * The bug is here also with a `window.location.href` * I tried with other async api and the page works fine (like `https.get()`, `timers.promises.setTimeout()`, or `fetch()`) I created a repo to reproduce the bug: https://github.com/remss/electron-issue-reload Just run `npm i && npm start` then click on `reloadMeWithAsyncStuff` button to see the blank page.
https://github.com/electron/electron/issues/33164
https://github.com/electron/electron/pull/33280
652680e8012983b1d8b9118b48297df4c1d9a939
b2c5623a13c91a561704b46480b6c3a7a51f2db7
2022-03-07T14:31:24Z
c++
2022-03-16T17:54:45Z
shell/renderer/web_worker_observer.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/renderer/web_worker_observer.h" #include "base/lazy_instance.h" #include "base/threading/thread_local.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" namespace electron { namespace { static base::LazyInstance< base::ThreadLocalPointer<WebWorkerObserver>>::DestructorAtExit lazy_tls = LAZY_INSTANCE_INITIALIZER; } // namespace // static WebWorkerObserver* WebWorkerObserver::GetCurrent() { WebWorkerObserver* self = lazy_tls.Pointer()->Get(); return self ? self : new WebWorkerObserver; } WebWorkerObserver::WebWorkerObserver() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kWorker)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { lazy_tls.Pointer()->Set(this); } WebWorkerObserver::~WebWorkerObserver() { lazy_tls.Pointer()->Set(nullptr); gin_helper::MicrotasksScope microtasks_scope( node_bindings_->uv_env()->isolate()); node::FreeEnvironment(node_bindings_->uv_env()); node::FreeIsolateData(node_bindings_->isolate_data()); } void WebWorkerObserver::WorkerScriptReadyForEvaluation( v8::Local<v8::Context> worker_context) { v8::Context::Scope context_scope(worker_context); auto* isolate = worker_context->GetIsolate(); v8::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); // Start the embed thread. node_bindings_->PrepareMessageLoop(); // Setup node tracing controller. if (!node::tracing::TraceEventHelper::GetAgent()) node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. bool initialized = node::InitializeContext(worker_context); CHECK(initialized); node::Environment* env = node_bindings_->CreateEnvironment(worker_context, nullptr); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->RunMessageLoop(); } void WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) { node::Environment* env = node::Environment::GetCurrent(context); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); delete this; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,164
[Bug]: Blank page on location change / reload if a filesystem asynchronous call was pending
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 13.6.9 ### Expected Behavior Assuming a BrowserWindow like this: ``` const mainWindow = new BrowserWindow({ ... webPreferences: { nodeIntegration: true, contextIsolation: false, } }) ``` And an asynchronous filesystem call on `fs.promises` API ``` // renderer.js const fs = require('fs'); async function asyncStuff() { let output = await fs.promises.readFile("datafile"); } ``` Then trying to reload the page when the fs asynchronous call is not finished yet will make the page fail (blank page). ``` // renderer.js async function testCrash() { asyncStuff() // No await here window.location.reload() // Here the renderer will crash }) ``` I expect that the page reloads correctly. ### Actual Behavior The page is blank, and DevTools are disconnected. ### Testcase Gist URL _No response_ ### Additional Information Notes: * Replace the `fs.promises.readFile()` by `fs.readFileSync()` and the page will reload fine * Replace the `fs.promises.readFile()` by `fs.readFile() with callback` and the page will reload fine * The bug is here also with a `window.location.href` * I tried with other async api and the page works fine (like `https.get()`, `timers.promises.setTimeout()`, or `fetch()`) I created a repo to reproduce the bug: https://github.com/remss/electron-issue-reload Just run `npm i && npm start` then click on `reloadMeWithAsyncStuff` button to see the blank page.
https://github.com/electron/electron/issues/33164
https://github.com/electron/electron/pull/33280
652680e8012983b1d8b9118b48297df4c1d9a939
b2c5623a13c91a561704b46480b6c3a7a51f2db7
2022-03-07T14:31:24Z
c++
2022-03-16T17:54:45Z
spec-main/fixtures/crash-cases/fs-promises-renderer-crash/index.html
closed
electron/electron
https://github.com/electron/electron
33,164
[Bug]: Blank page on location change / reload if a filesystem asynchronous call was pending
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 13.6.9 ### Expected Behavior Assuming a BrowserWindow like this: ``` const mainWindow = new BrowserWindow({ ... webPreferences: { nodeIntegration: true, contextIsolation: false, } }) ``` And an asynchronous filesystem call on `fs.promises` API ``` // renderer.js const fs = require('fs'); async function asyncStuff() { let output = await fs.promises.readFile("datafile"); } ``` Then trying to reload the page when the fs asynchronous call is not finished yet will make the page fail (blank page). ``` // renderer.js async function testCrash() { asyncStuff() // No await here window.location.reload() // Here the renderer will crash }) ``` I expect that the page reloads correctly. ### Actual Behavior The page is blank, and DevTools are disconnected. ### Testcase Gist URL _No response_ ### Additional Information Notes: * Replace the `fs.promises.readFile()` by `fs.readFileSync()` and the page will reload fine * Replace the `fs.promises.readFile()` by `fs.readFile() with callback` and the page will reload fine * The bug is here also with a `window.location.href` * I tried with other async api and the page works fine (like `https.get()`, `timers.promises.setTimeout()`, or `fetch()`) I created a repo to reproduce the bug: https://github.com/remss/electron-issue-reload Just run `npm i && npm start` then click on `reloadMeWithAsyncStuff` button to see the blank page.
https://github.com/electron/electron/issues/33164
https://github.com/electron/electron/pull/33280
652680e8012983b1d8b9118b48297df4c1d9a939
b2c5623a13c91a561704b46480b6c3a7a51f2db7
2022-03-07T14:31:24Z
c++
2022-03-16T17:54:45Z
spec-main/fixtures/crash-cases/fs-promises-renderer-crash/index.js
closed
electron/electron
https://github.com/electron/electron
33,164
[Bug]: Blank page on location change / reload if a filesystem asynchronous call was pending
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 13.6.9 ### Expected Behavior Assuming a BrowserWindow like this: ``` const mainWindow = new BrowserWindow({ ... webPreferences: { nodeIntegration: true, contextIsolation: false, } }) ``` And an asynchronous filesystem call on `fs.promises` API ``` // renderer.js const fs = require('fs'); async function asyncStuff() { let output = await fs.promises.readFile("datafile"); } ``` Then trying to reload the page when the fs asynchronous call is not finished yet will make the page fail (blank page). ``` // renderer.js async function testCrash() { asyncStuff() // No await here window.location.reload() // Here the renderer will crash }) ``` I expect that the page reloads correctly. ### Actual Behavior The page is blank, and DevTools are disconnected. ### Testcase Gist URL _No response_ ### Additional Information Notes: * Replace the `fs.promises.readFile()` by `fs.readFileSync()` and the page will reload fine * Replace the `fs.promises.readFile()` by `fs.readFile() with callback` and the page will reload fine * The bug is here also with a `window.location.href` * I tried with other async api and the page works fine (like `https.get()`, `timers.promises.setTimeout()`, or `fetch()`) I created a repo to reproduce the bug: https://github.com/remss/electron-issue-reload Just run `npm i && npm start` then click on `reloadMeWithAsyncStuff` button to see the blank page.
https://github.com/electron/electron/issues/33164
https://github.com/electron/electron/pull/33280
652680e8012983b1d8b9118b48297df4c1d9a939
b2c5623a13c91a561704b46480b6c3a7a51f2db7
2022-03-07T14:31:24Z
c++
2022-03-16T17:54:45Z
shell/renderer/electron_renderer_client.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/renderer/electron_renderer_client.h" #include <string> #include "base/command_line.h" #include "content/public/renderer/render_frame.h" #include "electron/buildflags/buildflags.h" #include "net/http/http_request_headers.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/renderer/electron_render_frame_observer.h" #include "shell/renderer/web_worker_observer.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" #include "third_party/blink/public/web/web_document.h" #include "third_party/blink/public/web/web_local_frame.h" namespace electron { namespace { bool IsDevToolsExtension(content::RenderFrame* render_frame) { return static_cast<GURL>(render_frame->GetWebFrame()->GetDocument().Url()) .SchemeIs("chrome-extension"); } } // namespace ElectronRendererClient::ElectronRendererClient() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kRenderer)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) {} ElectronRendererClient::~ElectronRendererClient() = default; void ElectronRendererClient::RenderFrameCreated( content::RenderFrame* render_frame) { new ElectronRenderFrameObserver(render_frame, this); RendererClientBase::RenderFrameCreated(render_frame); } void ElectronRendererClient::RunScriptsAtDocumentStart( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentStart(render_frame); // Inform the document start phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-start"); } void ElectronRendererClient::RunScriptsAtDocumentEnd( content::RenderFrame* render_frame) { RendererClientBase::RunScriptsAtDocumentEnd(render_frame); // Inform the document end phase. v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); node::Environment* env = GetEnvironment(render_frame); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "document-end"); } void ElectronRendererClient::DidCreateScriptContext( v8::Handle<v8::Context> renderer_context, content::RenderFrame* render_frame) { // TODO(zcbenz): Do not create Node environment if node integration is not // enabled. // Only load Node.js if we are a main frame or a devtools extension // unless Node.js support has been explicitly enabled for subframes. auto prefs = render_frame->GetBlinkPreferences(); bool is_main_frame = render_frame->IsMainFrame(); bool is_devtools = IsDevToolsExtension(render_frame); bool allow_node_in_subframes = prefs.node_integration_in_sub_frames; bool should_load_node = (is_main_frame || is_devtools || allow_node_in_subframes) && !IsWebViewFrame(renderer_context, render_frame); if (!should_load_node) return; injected_frames_.insert(render_frame); if (!node_integration_initialized_) { node_integration_initialized_ = true; node_bindings_->Initialize(); node_bindings_->PrepareMessageLoop(); } else { node_bindings_->PrepareMessageLoop(); } // Setup node tracing controller. if (!node::tracing::TraceEventHelper::GetAgent()) node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. bool initialized = node::InitializeContext(renderer_context); CHECK(initialized); node::Environment* env = node_bindings_->CreateEnvironment(renderer_context, nullptr); // If we have disabled the site instance overrides we should prevent loading // any non-context aware native module. env->options()->force_context_aware = true; // We do not want to crash the renderer process on unhandled rejections. env->options()->unhandled_rejections = "warn"; environments_.insert(env); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); gin_helper::Dictionary process_dict(env->isolate(), env->process_object()); BindProcess(env->isolate(), &process_dict, render_frame); // Load everything. node_bindings_->LoadEnvironment(env); if (node_bindings_->uv_env() == nullptr) { // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->RunMessageLoop(); } } void ElectronRendererClient::WillReleaseScriptContext( v8::Handle<v8::Context> context, content::RenderFrame* render_frame) { if (injected_frames_.erase(render_frame) == 0) return; node::Environment* env = node::Environment::GetCurrent(context); if (environments_.erase(env) == 0) return; gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); // The main frame may be replaced. if (env == node_bindings_->uv_env()) node_bindings_->set_uv_env(nullptr); // Destroy the node environment. We only do this if node support has been // enabled for sub-frames to avoid a change-of-behavior / introduce crashes // for existing users. // We also do this if we have disable electron site instance overrides to // avoid memory leaks auto prefs = render_frame->GetBlinkPreferences(); gin_helper::MicrotasksScope microtasks_scope(env->isolate()); node::FreeEnvironment(env); if (env == node_bindings_->uv_env()) node::FreeIsolateData(node_bindings_->isolate_data()); // ElectronBindings is tracking node environments. electron_bindings_->EnvironmentDestroyed(env); } void ElectronRendererClient::WorkerScriptReadyForEvaluationOnWorkerThread( v8::Local<v8::Context> context) { // TODO(loc): Note that this will not be correct for in-process child windows // with webPreferences that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { WebWorkerObserver::GetCurrent()->WorkerScriptReadyForEvaluation(context); } } void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread( v8::Local<v8::Context> context) { // TODO(loc): Note that this will not be correct for in-process child windows // with webPreferences that have a different value for nodeIntegrationInWorker if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kNodeIntegrationInWorker)) { WebWorkerObserver::GetCurrent()->ContextWillDestroy(context); } } node::Environment* ElectronRendererClient::GetEnvironment( content::RenderFrame* render_frame) const { if (injected_frames_.find(render_frame) == injected_frames_.end()) return nullptr; v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); auto context = GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent()); node::Environment* env = node::Environment::GetCurrent(context); if (environments_.find(env) == environments_.end()) return nullptr; return env; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,164
[Bug]: Blank page on location change / reload if a filesystem asynchronous call was pending
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 13.6.9 ### Expected Behavior Assuming a BrowserWindow like this: ``` const mainWindow = new BrowserWindow({ ... webPreferences: { nodeIntegration: true, contextIsolation: false, } }) ``` And an asynchronous filesystem call on `fs.promises` API ``` // renderer.js const fs = require('fs'); async function asyncStuff() { let output = await fs.promises.readFile("datafile"); } ``` Then trying to reload the page when the fs asynchronous call is not finished yet will make the page fail (blank page). ``` // renderer.js async function testCrash() { asyncStuff() // No await here window.location.reload() // Here the renderer will crash }) ``` I expect that the page reloads correctly. ### Actual Behavior The page is blank, and DevTools are disconnected. ### Testcase Gist URL _No response_ ### Additional Information Notes: * Replace the `fs.promises.readFile()` by `fs.readFileSync()` and the page will reload fine * Replace the `fs.promises.readFile()` by `fs.readFile() with callback` and the page will reload fine * The bug is here also with a `window.location.href` * I tried with other async api and the page works fine (like `https.get()`, `timers.promises.setTimeout()`, or `fetch()`) I created a repo to reproduce the bug: https://github.com/remss/electron-issue-reload Just run `npm i && npm start` then click on `reloadMeWithAsyncStuff` button to see the blank page.
https://github.com/electron/electron/issues/33164
https://github.com/electron/electron/pull/33280
652680e8012983b1d8b9118b48297df4c1d9a939
b2c5623a13c91a561704b46480b6c3a7a51f2db7
2022-03-07T14:31:24Z
c++
2022-03-16T17:54:45Z
shell/renderer/web_worker_observer.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/renderer/web_worker_observer.h" #include "base/lazy_instance.h" #include "base/threading/thread_local.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/event_emitter_caller.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" namespace electron { namespace { static base::LazyInstance< base::ThreadLocalPointer<WebWorkerObserver>>::DestructorAtExit lazy_tls = LAZY_INSTANCE_INITIALIZER; } // namespace // static WebWorkerObserver* WebWorkerObserver::GetCurrent() { WebWorkerObserver* self = lazy_tls.Pointer()->Get(); return self ? self : new WebWorkerObserver; } WebWorkerObserver::WebWorkerObserver() : node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kWorker)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { lazy_tls.Pointer()->Set(this); } WebWorkerObserver::~WebWorkerObserver() { lazy_tls.Pointer()->Set(nullptr); gin_helper::MicrotasksScope microtasks_scope( node_bindings_->uv_env()->isolate()); node::FreeEnvironment(node_bindings_->uv_env()); node::FreeIsolateData(node_bindings_->isolate_data()); } void WebWorkerObserver::WorkerScriptReadyForEvaluation( v8::Local<v8::Context> worker_context) { v8::Context::Scope context_scope(worker_context); auto* isolate = worker_context->GetIsolate(); v8::MicrotasksScope microtasks_scope( isolate, v8::MicrotasksScope::kDoNotRunMicrotasks); // Start the embed thread. node_bindings_->PrepareMessageLoop(); // Setup node tracing controller. if (!node::tracing::TraceEventHelper::GetAgent()) node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. bool initialized = node::InitializeContext(worker_context); CHECK(initialized); node::Environment* env = node_bindings_->CreateEnvironment(worker_context, nullptr); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Make uv loop being wrapped by window context. node_bindings_->set_uv_env(env); // Give the node loop a run to make sure everything is ready. node_bindings_->RunMessageLoop(); } void WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) { node::Environment* env = node::Environment::GetCurrent(context); if (env) gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); delete this; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,164
[Bug]: Blank page on location change / reload if a filesystem asynchronous call was pending
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.1.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version 13.6.9 ### Expected Behavior Assuming a BrowserWindow like this: ``` const mainWindow = new BrowserWindow({ ... webPreferences: { nodeIntegration: true, contextIsolation: false, } }) ``` And an asynchronous filesystem call on `fs.promises` API ``` // renderer.js const fs = require('fs'); async function asyncStuff() { let output = await fs.promises.readFile("datafile"); } ``` Then trying to reload the page when the fs asynchronous call is not finished yet will make the page fail (blank page). ``` // renderer.js async function testCrash() { asyncStuff() // No await here window.location.reload() // Here the renderer will crash }) ``` I expect that the page reloads correctly. ### Actual Behavior The page is blank, and DevTools are disconnected. ### Testcase Gist URL _No response_ ### Additional Information Notes: * Replace the `fs.promises.readFile()` by `fs.readFileSync()` and the page will reload fine * Replace the `fs.promises.readFile()` by `fs.readFile() with callback` and the page will reload fine * The bug is here also with a `window.location.href` * I tried with other async api and the page works fine (like `https.get()`, `timers.promises.setTimeout()`, or `fetch()`) I created a repo to reproduce the bug: https://github.com/remss/electron-issue-reload Just run `npm i && npm start` then click on `reloadMeWithAsyncStuff` button to see the blank page.
https://github.com/electron/electron/issues/33164
https://github.com/electron/electron/pull/33280
652680e8012983b1d8b9118b48297df4c1d9a939
b2c5623a13c91a561704b46480b6c3a7a51f2db7
2022-03-07T14:31:24Z
c++
2022-03-16T17:54:45Z
spec-main/fixtures/crash-cases/fs-promises-renderer-crash/index.html